Spring IOC 依赖注入的两种方式:XML和注解

IoC,直观地讲,就是容器控制程序之间的关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在。控制权由应用代码中转到了外部容器,控制权的转移是所谓反转。IoC还有另外一个名字——“依赖注入(Dependency Injection)”。从名字上理解,所谓依赖注入,即组件之间的依赖关系由容器在运行期决定,形象地说,即由容器动态地将某种依赖关系注入到组件之中。

依赖注入的原理
依赖注入的方式---XML配置
依赖注入的方式---注解的方式

Spring 它的核心就是IOC和AOP。而IOC中实现Bean注入的实现方式之一就是DI(依赖注入)。

一 DI的原理

DI的基本原理:对象之间的依赖关系只会通过三种方式:构造函数参数,工厂方法的参数以及构造函数或工厂方法创建的对象属性设置。因此,容器的工作哦就是在创建Bean时注入所有的依赖关系。相对于由Bean自己控制其实例化,直接在构造器中指定依赖关系或者类似服务定位器(Service Locator)这三种自主控制依赖关系注入的方法,而控制权从根本上发生改变,即控制反转(Inverse of Controll)---IOC.
应用DI规则后,我们不用在关注对象之间的依赖关系,从而达到高层次的松耦合。DI有两种实现方式---Setter/getter方式(传值方式)和构造器方式(引用方式)。

下面通过一个生动形象的例子介绍控制反转。

比如,一个女孩希望找到合适的男朋友,如图6-2所示,可以有3种方式,即青梅竹马、亲友介绍、父母包办。







第1种方式是青梅竹马,如图6-3所示。





通过代码表示如下。

public class Girl {

  void kiss(){

    Boy boy = new Boy();

  }

}



第2种方式是亲友介绍,如图6-4所示。





通过代码表示如下。

public class Girl {

  void kiss(){

    Boy boy = BoyFactory.createBoy();

  }

}

第3种方式是父母包办,如图6-5所示。





通过代码表示如下。

public class Girl {

  void kiss(Boy boy){

    // kiss boy

   boy.kiss();

  }

}

哪一种为控制反转IoC呢?虽然在现实生活中我们都希望青梅竹马,但在Spring世界里,选择的却是父母包办,它就是控制反转,而这里具有控制力的父母,就是Spring所谓的容器概念。

典型的IoC可以如图6-6所示。

 

二、DI的方式---XML配置


第1种是通过接口注射,这种方式要求我们的类必须实现容器给定的一个接口,然后容器会利用这个接口给我们这个类注射它所依赖的类。

1. Setter/getter方法

这种方式也是Spring推荐的方式

1)、beans.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"
       xmlns:context="http://www.springframework.org/schema/context"      
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">              
   <bean id="personDao" class="com.spring.dao.impl.PersonDaoImpl"></bean> 
           <bean id="personService" class="com.spring.service.impl.PersonServiceBean" > 
       <property name="personDao" ref="personDao"/> 
   </bean>
</beans>

2) PersonDao.java

 

package com.spring.dao;

public interface PersonDao {
public void add();  
}

3) PersonDaoImpl.java

 

package com.spring.dao.impl;

import com.spring.dao.PersonDao;

public class PersonDaoImpl implements PersonDao {
public void add() {
   System.out.println("PersonDao.add() is running.");  
}
}

4) PersonService.java

 

package com.spring.service;

public interface PersonService {
public  void save();  
}

5) PersonServiceBean.java

 

package com.spring.service.impl;

import com.spring.dao.*;
import com.spring.service.PersonService;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class PersonServiceBean implements PersonService {
      private PersonDao personDao;  
        
  public PersonServiceBean(){  
          System.out.println("personServiceBean.constructor() is running.");  
      }  
 
      public PersonDao getPersonDao() {  
          return personDao;  
      }  
    
     public void setPersonDao(PersonDao personDao) {  
         this.personDao = personDao;  
      }  
      public void save(){  
          System.out.println("Name:" );  
          personDao.add();  
      }  
      @PostConstruct 
      public void init(){  
         System.out.println("PersonServiceBean.init() is running.");  
      }  
       
      @PreDestroy 
      public void destory(){  
          System.out.println("PersonServiceBean.destory() is running.");  
      }  
}

6) SpringIOCTest.java(测试类)

 

package junit.test;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.service.PersonService;

public class SpringIOCTest {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
     @Test public void instanceSpring(){  
           AbstractApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");  
           PersonService personService = (PersonService)context.getBean("personService");  
           personService.save();  
//          context.close();  
   }  
}

我们还可以采用内部注入的方式来处理:

Beans.xml修改如下:

<bean id="personService"> 
                <property name="personDao"> 
                     <bean.../> 
                 </property> 
</bean>

2、构造器注入

这种方式Spring同样给予了实现,它和通过setter方式一样,都在类里无任何侵入性,但是,不是没有侵入性,只是把侵入性转移了,显然第1种方式要求实现特定的接口,侵入性非常强,不方便以后移植

 

   <bean id="personDao" class="com.spring.dao.impl.PersonDaoImpl"></bean>
    <bean id="personService"  class="com.spring.service.impl.PersonServiceBean" init-method="init" destroy-method="destory"> 
                <constructor-arg index="0" type="com.spring.dao.PersonDao" ref="personDao"/> 
    <constructor-arg index="1" value="Jamson" />  
              </bean>

2) PersonService.java:同Setter方法注入
3) PersonServiceBean.java

 

public class PersonServiceBean implements PersonService {
      private PersonDao personDao;  
      private String name;
        
  public PersonServiceBean(){  
          System.out.println("personServiceBean.constructor() is running.");  
      }  
 

      public PersonServiceBean(PersonDao personDao, String name) {  
       this.personDao = personDao;  
        this.name = name;  
     }  
   
//      public PersonDao getPersonDao() {  
//          return personDao;  
//      }      
//     public void setPersonDao(PersonDao personDao) {  
//         this.personDao = personDao;  
//      }  
      public void save(){  
          System.out.println("Name:"+name );  
          personDao.add();  
      }  
      @PostConstruct 
      public void init(){  
         System.out.println("PersonServiceBean.init() is running.");  
      }  
       
      @PreDestroy 
      public void destory(){  
          System.out.println("PersonServiceBean.destory() is running.");  
      }  
}

4) PersonDao.java:同Setter方法注入
5) PersonDaoImpl.java:同Setter方法注入
6) 测试类(SpringIOCTest.java):同上

控制台信息

 

PersonServiceBean.init() is running.
Name:Jamson
PersonDao.add() is running.
PersonServiceBean.destory() is running.

 

三 DI的方式---注解的配置

 自从Jdk5中引入Annotation类后,在EJB和Spring中得到广泛的使用,也越来越被开发者们在平时的应用中使用。主要是用在Field上的注入。在日常的应用开发中,一个项目中有很多的bean,如果使用XML文件配置,就会导致配置文件难以管理。使用注解注入的时候,能够使bean的配置文件内容不至于繁杂。

1、古老的注入方式:


实现类:

Java代码 收藏代码
  1. /**
  2. * @title UserServiceImpl.java
  3. * @description UserService实现类
  4. * @author cao_xhu
  5. * @version
  6. * @create_date Oct 30, 2009
  7. * @copyright (c) CVIC SE
  8. */ 
  9. public class UserServiceImpl implements UserService { 
  10.  
  11.     private UserDAO userDAO; 
  12.  
  13.     public void setUserDAO(UserDAO userDAO) { 
  14.         this.userDAO = userDAO; 
  15.     } 
  16. ... 


配置文件:

Xml代码 收藏代码
  1. <bean id="userDAO" class="springlive.dao.impl.UserDAOImpl"> 
  2.     <property name="sessionFactory"> 
  3.         <ref local="sessionFactory" /> 
  4.     </property> 
  5. </bean> 
  6. <bean id="userServiceImpl" 
  7.     class="springlive.service.impl.UserServiceImpl"> 
  8.     <property name="userDAO"> 
  9.         <ref local="userDAO" /> 
  10.     </property> 
  11. </bean> 

 

2、使用注解的方式:

 
2.1、Autowired注解


<1>对成员变量注解
实现类:

Java代码 收藏代码
  1.     @Autowired 
  2.     private IndustryDao industryDao; 
  3. ... 
  4.      


<2>set方法注解

Java代码 收藏代码
  1. @Autowired 
  2. public void setDao(IndustryDao industryDao) 
  3.     super.setDao(industryDao); 


配置文件:

Xml代码 收藏代码
  1. <!-- 使用 <context:annotation-config/> 简化配置 
  2.  
  3. Spring 2.1 添加了一个新的 context 的 Schema 命名空间,该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配置。我们知道注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来。  
  4.  
  5. 而我们前面所介绍的 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor 就是处理这些注释元数据的处理器。但是直接在 Spring 配置文件中定义这些 Bean 显得比较笨拙。Spring 为我们提供了一种方便的注册这些 BeanPostProcessor 的方式,这就是 <context:annotation-config/>。 
  6. --> 
  7. <context:annotation-config /> 
  8.     <bean id="industryDao" 
  9.         class="efs.sadapter.system.industry.dao.hibernate.HibernateIndustryDao" /> 
  10.     <bean id="industryService" 
  11.         class="efs.sadapter.system.industry.service.impl.IndustryServiceImpl" /> 



@Autowired可以对成员变量、方法和构造函数进行标注,来完成自动注入。
@Autowired的标注位置不同,它们都会在Spring在初始化industryService这个bean时,自动装配industryDao这个属性,区别是:第一种实现中,Spring会直接将IndustryDao类型的唯一一个bean赋值给industryDao这个成员变量;第二种实现中,Spring会调用setDao方法来将IndustryDao类型的唯一一个bean装配到industryDao这个属性。

2.2、@Qualifier


@Autowired是根据类型进行自动注入的,如果spring配置文件中存在多个IndustryDao类型的bean时,或者不存在IndustryDao类型的bean,都会抛出异常。
存在多个类型的实例时,按id注入@Qualifier("core.system.hibernateService")

Java代码 收藏代码
  1. HibernateService hibernateService; 
  2.  
  3. @Autowired 
  4. public void setHibernateService(@Qualifier("core.system.hibernateService"
  5. HibernateService hibernateService) 
  6.     this.hibernateService = hibernateService; 


若不存在某类型的实例:告诉 Spring:在找不到匹配 Bean 时也不报错

Java代码 收藏代码
  1. @Autowired(required = false
  2.     public void setHibernateService(@Qualifier("core.system.hibernateService"
  3.     HibernateService hibernateService) 
  4.     { 
  5.         this.hibernateService = hibernateService; 
  6.     } 


 

2.3、使用 JSR-250 的注解


<1> @Resource
spring支持@Resource、@PostConstruct以及@PreDestroyJSR-250的标准注解。
@Resource可以按type注入,也可以按name注入。@Resource默认按byName自动注入。
Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。

@Resource装配顺序
如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
如果既没有指定name,又没有指定type,则自动按照byName方式进行装配(见2);如果没有匹配,则回退为一个原始类型(UserDao)进行匹配,如果匹配则自动装配;
<2> @PostConstruct 和 @PreDestroy
Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,您既可以通过实现 InitializingBean/DisposableBean 接口来定制初始化之后 / 销毁之前的操作方法,也可以通过 <bean> 元素的 init-method/destroy-method 属性指定初始化之后 / 销毁之前调用的操作方法。
JSR-250 为初始化之后/销毁之前方法的指定定义了两个注释类,分别是 @PostConstruct 和 @PreDestroy,这两个注释只能应用于方法上。标注了 @PostConstruct 注释的方法将在类实例化后调用,而标注了 @PreDestroy 的方法将在类销毁之前调用。

使用 @PostConstruct 和 @PreDestroy 注释的 Boss.java

Java代码 收藏代码
  1. package com.baobaotao; 
  2.  
  3. import javax.annotation.Resource; 
  4. import javax.annotation.PostConstruct; 
  5. import javax.annotation.PreDestroy; 
  6.  
  7. public class Boss { 
  8.     @Resource 
  9.     private Car car; 
  10.  
  11.     @Resource(name = "office"
  12.     private Office office; 
  13.  
  14.     @PostConstruct 
  15.     public void postConstruct1(){ 
  16.         System.out.println("postConstruct1"); 
  17.     } 
  18.  
  19.     @PreDestroy 
  20.     public void preDestroy1(){ 
  21.         System.out.println("preDestroy1");  
  22.     } 
  23.     … 



测试类代码:

Java代码 收藏代码
  1. package com.baobaotao; 
  2.  
  3. import org.springframework.context.support.ClassPathXmlApplicationContext; 
  4.  
  5. public class AnnoIoCTest { 
  6.  
  7.     public static void main(String[] args) { 
  8.         String[] locations = {"beans.xml"}; 
  9.         ClassPathXmlApplicationContext ctx =  
  10.             new ClassPathXmlApplicationContext(locations); 
  11.         Boss boss = (Boss) ctx.getBean("boss"); 
  12.         System.out.println(boss); 
  13.         ctx.destroy();// 关闭 Spring 容器,以触发 Bean 销毁方法的执行 
  14.     } 


标注了 @PostConstruct 的 postConstruct1() 方法将在 Spring 容器启动时,创建 Boss Bean 的时候被触发执行,而标注了 @PreDestroy 注释的 preDestroy1() 方法将在 Spring 容器关闭前销毁 Boss Bean 的时候被触发执行。

3、使用 @Component

虽然我们可以通过 @Autowired 或 @Resource 在 Bean 类中使用自动注入功能,但是 Bean 还是在 XML 文件中通过 <bean> 进行定义 —— 也就是说,在 XML 配置文件中定义 Bean,通过 @Autowired 或 @Resource 为 Bean 的成员变量、方法入参或构造函数入参提供自动注入的功能。能否也通过注释定义 Bean,从 XML 配置文件中完全移除 Bean 定义的配置呢?答案是肯定的,我们通过 Spring 2.5 提供的 @Component 注释就可以达到这个目标了。

下面,我们完全使用注释定义 Bean 并完成 Bean 之间装配:
使用 @Component 注释的Woman.java

Java代码 收藏代码
  1. @Component 
  2. public class Woman{ 
  3.     … 



使用 @Component 注释的Woman.java

Java代码 收藏代码
  1. @Component 
  2. public class Man{ 
  3.     … 


这样,我们就可以在 Human类中通过 @Autowired 注入前面定义的 Woman和 Man Bean 了。

Java代码 收藏代码
  1. @Component("human"
  2. public class Human{ 
  3.     @Autowired 
  4.     private Woman woman; 
  5.  
  6.     @Autowired 
  7.     private Man man; 
  8.     … 



一般情况下,Bean 都是 singleton 的,需要注入 Bean 的地方仅需要通过 byType 策略就可以自动注入了,所以大可不必指定 Bean 的名称。如果需要使用其它作用范围的 Bean,可以通过 @Scope 注释来达到目标:

Java代码 收藏代码
  1. @Scope("prototype"
  2. @Component("human"
  3. public class Human{ 
  4.        … 



在使用 @Component 注释后,Spring 容器必须启用类扫描机制以启用注释驱动 Bean 定义和注释驱动 Bean 自动注入的策略。Spring 2.5 对 context 命名空间进行了扩展,提供了这一功能,请看下面的配置:

Xml代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  4.     xmlns:context="http://www.springframework.org/schema/context" 
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
  7. http://www.springframework.org/schema/context  
  8. http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 
  9.     <context:component-scan base-package="springlive.learn.component "/> 
  10. </beans> 

参考资料:
使用 Spring 2.5 注释驱动的 IoC 功能http://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/?ca=drs-tp0808

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值