`
garrincha
  • 浏览: 12852 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
社区版块
存档分类
最新评论

2Spring xml配置IOC——注入对象

阅读更多
上一讲介绍了如何使用xml注入值类型,这里我们要注入的是对象。
这里我们需要用到2个类,分别是UserDao和UserService,UserDao是直接与数据库打交道的类,而UserService是面向业务给业务提供调取方法的类。

UserService是需要调取UserDao用于实现自己的业务逻辑的。

继续使用上一个例子的代码

1、新建UserDao类,包com.spring.dao
这里我们并没有真正的操作数据库,打印一行文字来代替
package com.spring.dao;

public class UserDao {

	public void add()
	{
		System.out.println("执行UserDao.add()方法");
	}
}

2、新建UserService类 包com.spring.service
package com.spring.service;

import com.spring.dao.UserDao;

public class UserService {

	private UserDao dao;
	public UserDao getDao() {
		return dao;
	}
	public void setDao(UserDao dao) {
		this.dao = dao;
	}
	public void add()
	{
		dao.add();
	}
	
}

3、xml文件springbeans.xml
我们将要使用xml把dao这个属性通过setDao方法注入到UserService中。
xml文件如下
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
            
            <bean id = "dao" class="com.spring.dao.UserDao"></bean>
            <bean id="userService" class ="com.spring.service.UserService">
            		<property name="dao" ref="dao"></property>
            </bean>        
</beans>

这段xml中配置了2个bean,分别对应UserDao类和UserService类的实例。这两个bean经过spring的解析之后会生成2个对象。而ref = "dao"这里的dao对应了id="dao"这句。把UserDao的对象实例注入到了UserService的dao属性中。
4新建测试类UserServiceTest包com.spring.service.test
package com.spring.service.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.service.UserService;
public class UserServiceTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		ApplicationContext ctx = new ClassPathXmlApplicationContext("springbeans.xml");		
		UserService service = (UserService) ctx.getBean("userService");
		service.add();
	}

}

如果没有spring,这段代码会报null的异常,因为UserService中的dao属性并没有被设置,是null,这样调用service.add()方法时候会调用到dao.add()方法。会报null的exception。而spring帮我们根据名字自动注入了dao属性。这就是spring做的工作。
现在测试一下。

2014-8-26 19:45:15 [color=red]org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@61b383e9: display name [org.springframework.context.support.ClassPathXmlApplicationContext@61b383e9]; startup date [Tue Aug 26 19:45:15 HKT 2014]; root of context hierarchy
2014-8-26 19:45:15 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [springbeans.xml]
2014-8-26 19:45:15 org.springframework.context.support.ClassPathXmlApplicationContext obtainFreshBeanFactory
信息: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@61b383e9]: org.springframework.beans.factory.support.DefaultListableBeanFactory@4839e5b5
2014-8-26 19:45:15 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4839e5b5: defining beans [dao,userService]; root of factory hierarchy[/color]
执行UserDao.add()方法


正确执行

下面是错误的调用方法
倘若测试代码部分改为
package com.spring.service.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.service.UserService;
public class UserServiceTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		UserService service = new UserService();
		service.add();//因为service对象中的dao属性是null,所以在这里会报错
	}

}

会报空指针异常,结果如下
Exception in thread "main" java.lang.NullPointerException
	at com.spring.service.UserService.add(UserService.java:16)
	at com.spring.service.test.UserServiceTest.main(UserServiceTest.java:12)


分享到:
评论

相关推荐

    Spring——IOC(控制反转)与DI(依赖注入).docx

    IOC与DI的理解及使用 控制反转IOC(Inversion of Control)是一种设计思想,DI(依赖注入)是实现IOC的一种方法 。... 在Spring中实现控制反转的是IOC容器 ,其 实现方法是依赖注入 (Dependency Injection,DI)

    Spring——DI和通过注解实现IOC和DI

    当spring容器创建对象的时候,通过xml配置文件,把需要赋值的JavaBean属性设置在配置文件中,这样就可以把值赋到了对应的属性上。 – 成员属性和JavaBean属性: JavaBean属性=成员属性吗?答案是否定的,成员属性是...

    Spring.3.x企业应用开发实战(完整版).part2

     《Spring3.x企业应用开发实战》是在《精通Spring2.x——企业应用开发详解》的基础上,经过历时一年的重大调整改版而成的,本书延续了上一版本追求深度,注重原理,不停留在技术表面的写作风格,力求使读者在熟练...

    Spring3.x企业应用开发实战(完整版) part1

     《Spring3.x企业应用开发实战》是在《精通Spring2.x——企业应用开发详解》的基础上,经过历时一年的重大调整改版而成的,本书延续了上一版本追求深度,注重原理,不停留在技术表面的写作风格,力求使读者在熟练...

    spring2.5 注解

    使用Spring2.5的Autowired实现注释型的IOC , 使用Spring2.5的新特性——Autowired可以实现快速的自动注入,而无需在xml文档里面添加bean的声明,大大减少了xml文档的维护

    低清版 大型门户网站是这样炼成的.pdf

    6.1.3 spring 2.5拿手戏——控制反转与依赖注入 353 6.1.4 何为“面向切面编程aop” 356 6.1.5 spring 2.5圣经——面向接口编程 358 6.1.6 开始spring 2.5旅程—hello world 359 6.2 spring 2.5核心技术 364 ...

    Java Web编程宝典-十年典藏版.pdf.part2(共2个)

    主要包括Java Web开发环境、JSP语法、JSP内置对象、Java Bean技术、Servlet技术、EL与JSTL标签库、数据库应用开发、初识Struts2基础、揭密Struts2高级技术、Hib锄劬e技术入门、Hibernate高级应用、Spring核心之IoC、...

    Java Web程序设计教程

    11.4理解spring的核心——ioc 234 11.4.1控制反转 234 11.4.2依赖注入的3种方式 236 11.5beanfactory与applicationcontext 238 11.5.1认识beanfactory 238 11.5.2使用applicationcontext 238 11.6项目实战——...

    Struts2 in action中文版

    9.1.2 Spring如何管理对象和注入依赖 199 9.1.3 使用接口隐藏实现 200 9.2 将Spring添加到Struts 2 202 9.2.1 让Spring管理动作、拦截器和结果的创建 203 9.2.2 使用自动连线将依赖注入到动作、拦截器和结果 205 9.3...

    电子商城系统设计实习报告.doc

    Spring MVC缺点: 大量的XML配置文件,太过灵活——没有公共的父控制器,没有内置的Ajax支持。 2 HTML语言: 超文本标记语言,标准通用标记语言下的一个应用。"超文本"就是指页面内可以包含 图片、链接,甚至音乐、...

    asp.net知识库

    动态调用对象的属性和方法——性能和灵活性兼备的方法 消除由try/catch语句带来的warning 微软的应试题完整版(附答案) 一个时间转换的问题,顺便谈谈搜索技巧 .net中的正则表达式使用高级技巧 (一) C#静态成员和...

    基于J2EE框架的个人博客系统项目毕业设计论文(源码和论文)

    由于J2EE的开源的框架中提供了MVC模式实现框架Struts、对象关系模型中的Hibernate 的框架及拥有事务管理和依赖注入的Spring。利用现存框架可以更快开发系统。所以选择Java技术作为blog 的开发工具。 为了增加系统的...

Global site tag (gtag.js) - Google Analytics