您的位置:首页 > 编程语言 > Java开发

Spring依赖注入之对象注入

2010-11-18 22:12 423 查看
依赖注入(Dependency Injection)

 

当我们把依赖对象交给外部容器负责创建,那么PersonServiceBean 类可以改成如下:
public class PersonServiceBean {
     private PersonDao personDao ;
    //通过构造器参数,让容器把创建好的依赖对象注入进PersonServiceBean,当然也可以使用setter方法进行注入。
     public PersonServiceBean(PersonDao personDao){
         this.personDao=personDao;
     } 
      public void save(Person person){
            personDao.save(person);
     }
}

所谓依赖注入就是指:在运行期,由外部容器动态地将依赖对象注入到组件中。
依赖对象:指PersonServiceBean依赖对象personDao。
beans.xml:
<bean id="userServiceDao" class="com.asm.dao.UserServiceDao">
<constructor-arg index="0"><value>1</value></constructor-arg>
<constructor-arg  index="1"><value>qqqq</value></constructor-arg>
</bean>
<bean id="userServiceBean" class="com.asm.service.UserServiceBean.UserServiceBean">
<constructor-arg index="0"><value>Yee</value></constructor-arg>
<constructor-arg  index="1">
<ref bean="userServiceDao"/>
</constructor-arg>
<!-- 
此例为依赖注入
<property name="userServiceDao">
<ref bean="userServiceDao" />
</property>
-->
</bean>
对象userServiceDao注入到userServiceBean,先在配置文件中写userServiceDao的bean,并注入属性值。然后写userServiceBean的bean,利用构造方法依赖注入属性和对象。
所谓控制反转就是应用本身不负责依赖对象的创建及维护,依赖对象的创建及维护是由外部容器负责的。这样控制权就由应用转移到了外部容器,控制权的转移就是所谓反转。
测试类test中放入方法:
public void testSave() {
  ApplicationContext ctx = new
  ClassPathXmlApplicationContext("beans.xml");
  UserServiceBean userServiceBean = (UserServiceBean) ctx.getBean("userServiceBean");
//既是控制反转
  System.out.println(userServiceBean.userservicedao.getId()); 
  System.out.println(userServiceBean.userservicedao.getName()); 
  System.out.println(userServiceBean.getUsername());  
 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring bean class setter 测试