Skip to main content

Spring@Autowired注解与自动装配


 

Spring@Autowired注解与自动装配

分类: Web 11623人阅读 评论(6) 收藏 举报
1   配置文件的方法

我们编写spring 框架的代码时候。一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量。并且要配套写上 get 和 set方法。


Boss 拥有 Office 和 Car 类型的两个属性:  
 
 
清单 3. Boss.java


  1. package com.baobaotao;     
  2.     
  3. public class Boss {     
  4.     private Car car;     
  5.     private Office office;     
  6.     
  7.     // 省略 get/setter     
  8.     
  9.     @Override    
  10.     public String toString() {     
  11.         return "car:" + car + "/n" + "office:" + office;     
  12.     }     
  13. }     

   
  System.out.println必须实现toString方法
 
我们在 Spring 容器中将 Office 和 Car 声明为 Bean,并注入到 Boss Bean 中:下面是使用传统 XML 完成这个工作的配置文件 beans.xml:  
 
 
清单 4. beans.xml 将以上三个类配置成 Bean  
                  
  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.     xsi:schemaLocation="http://www.springframework.org/schema/beans      
  5. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">     
  6.     <bean id="boss" class="com.baobaotao.Boss">     
  7.         <property name="car" ref="car"/>     
  8.         <property name="office" ref="office" />     
  9.     </bean>     
  10.     <bean id="office" class="com.baobaotao.Office">     
  11.         <property name="officeNo" value="002"/>     
  12.     </bean>     
  13.     <bean id="car" class="com.baobaotao.Car" scope="singleton">     
  14.         <property name="brand" value=" 红旗 CA72"/>     
  15.         <property name="price" value="2000"/>     
  16.     </bean>     
  17. </beans>     

   
 
 
当我们运行以下代码时,控制台将正确打出 boss 的信息:  
 
 
清单 5. 测试类:AnnoIoCTest.java  
                  
  1. import org.springframework.context.ApplicationContext;     
  2. import org.springframework.context.support.ClassPathXmlApplicationContext;     
  3. public class AnnoIoCTest {     
  4.     
  5.     public static void main(String[] args) {     
  6.         String[] locations = {"beans.xml"};     
  7.         ApplicationContext ctx =      
  8.             new ClassPathXmlApplicationContext(locations);     
  9.         Boss boss = (Boss) ctx.getBean("boss");     
  10.         System.out.println(boss);     
  11.     }     
  12. }     
  13.       

 
 
这说明 Spring 容器已经正确完成了 Bean 创建和装配的工作。   



2   @Autowired 

Spring 2.5 引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @Autowired的使用来消除 set ,get方法。


要实现我们要精简程序的目的。需要这样来处理:

* 在applicationContext.xml中加入:
 
[c-sharp] view plaincopy
  1.      
  2.   class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>  

Spring 通过一个 BeanPostProcessor 对 @Autowired 进行解析,所以要让 @Autowired 起作用必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。  

* 修改在原来注入spirng容器中的bean的方法。
     在域变量上加上标签@Autowired,并且去掉 相应的get 和set方法

清单 6. 使用 @Autowired 注释的 Boss.java  
                  
  1. package com.baobaotao;     
  2. import org.springframework.beans.factory.annotation.Autowired;     
  3.     
  4. public class Boss {     
  5.     
  6.     @Autowired    
  7.     private Car car;     
  8.     
  9.     @Autowired    
  10.     private Office office;     
  11.     
  12.     …     
  13. }     



* 在applicatonContext.xml中 把原来 引用的标签也去掉。

        
  1.             
  2. xml version="1.0" encoding="UTF-8" ?>     
  3. <beans xmlns="http://www.springframework.org/schema/beans"    
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans      
  6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">     
  7.     
  8.          
  9.     <bean class="org.springframework.beans.factory.annotation.     
  10.         AutowiredAnnotationBeanPostProcessor"/>     
  11.     
  12.          
  13.     <bean id="boss" class="com.baobaotao.Boss"/>     
  14.       
  15.     <bean id="office" class="com.baobaotao.Office">     
  16.         <property name="officeNo" value="001"/>     
  17.     </bean>     
  18.     <bean id="car" class="com.baobaotao.Car" scope="singleton">     
  19.         <property name="brand" value=" 红旗 CA72"/>     
  20.         <property name="price" value="2000"/>     
  21.     </bean>     
  22. </beans>    

 这样,当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有 @Autowired 注释时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去。  
 
按照上面的配置,Spring 将直接采用 Java 反射机制对 Boss 中的 car 和 office 这两个私有成员变量进行自动注入。所以对成员变量使用 @Autowired 后,您大可将它们的 setter 方法(setCar() 和 setOffice())从 Boss 中删除。  
 
当然,您也可以通过 @Autowired 对方法或构造函数进行标注,如果构造函数有两个入参,分别是 bean1 和 bean2,@Autowired 将分别寻找和它们类型匹配的 Bean,将它们作为 CountryService (Bean1 bean1 ,Bean2 bean2) 的入参来创建 CountryService Bean。来看下面的代码:  对方法


  1. package com.baobaotao;     
  2.     
  3. public class Boss {     
  4.     private Car car;     
  5.     private Office office;     
  6.     
  7.      @Autowired    
  8.     public void setCar(Car car) {     
  9.         this.car = car;     
  10.     }     
  11.       
  12.     @Autowired    
  13.     public void setOffice(Office office) {     
  14.         this.office = office;     
  15.     }     
  16.     …     
  17. }     


这时,@Autowired 将查找被标注的方法的入参类型的 Bean,并调用方法自动注入这些 Bean。而下面的使用方法则对构造函数进行标注:  

  1. package com.baobaotao;     
  2.     
  3. public class Boss {     
  4.     private Car car;     
  5.     private Office office;     
  6.       
  7.     @Autowired    
  8.     public Boss(Car car ,Office office){     
  9.         this.car = car;     
  10.         this.office = office ;     
  11.     }     
  12.       
  13.     …     
  14. }     


由于 Boss() 构造函数有两个入参,分别是 car 和 office,@Autowired 将分别寻找和它们类型匹配的 Bean,将它们作为 Boss(Car car ,Office office) 的入参来创建 Boss Bean。 

Comments

Popular posts from this blog

Java中的Serializable浅谈

from  http://www.cnblogs.com/vicenteforever/articles/1471775.html 对象的串行化(Serialization) 一、串行化的概念和目的 1.什么是串行化             对象的寿命通常随着生成该对象的程序的终止而终止。有时候,可能需要将对象的状态保存下来,在需要时再将对象恢复。我们把对象的这种能记录自己的状态以便将来再生的能力。叫作对象的持续性(persistence)。对象通过写出描述自己状态的数值来记录自己 ,这个过程叫对象的串行化(Serialization) 。串行化的主要任务是写出对象实例变量的数值。如果交量是另一对象的引用,则引用的对象也要串行化。这个过程是递归的,串行化可能要涉及一个复杂树结构的单行化,包括原有对象、对象的对象、对象的对象的对象等等。对象所有权的层次结构称为图表(graph)。 2.串行化的目的             Java对象的单行化的目标是为Java的运行环境提供一组特性,如下所示: 1)       尽量保持对象串行化的简单扼要 ,但要提供一种途径使其可根据开发者的要求进行扩展或定制。 2)       串行化机制应严格遵守Java的对象模型 。对象的串行化状态中应该存有所有的关于种类的安全特性的信息。 3)       对象的串行化机制应支持Java的对象持续性。 4)       对象的串行化机制应有足够的 可扩展能力以支持对象的远程方法调用(RMI)。 5)       对象串行化应允许对象定义自身 的格式即其自身的数据流表示形式,可外部化接口来完成这项功能。 什么情况下需要序列化 a)当...

How to install JSVC on Linux WidenHome Log | WidenHome Log

How to install JSVC on Linux WidenHome Log | WidenHome Log In our team, we have a lot of Java standalone applications which should be run as daemon on Unix/Linux system, and we found JSVC is the best choice for us to wrap Java programs to daemons. This article records the steps on how to install JSVC executable on Linux, which is our stage/prod environment. Download JSVC source package First of all, we need to download JSVC source package from this URL: http://commons.apache.org/daemon/download_daemon.cgi , for example, I downloaded commons-daemon-1.0.5-src.tar.gz file. Or, download it via wget: wget -c http://apache.etoak.com/commons/daemon/source/commons-daemon-1.0.5-src.tar.gz Build JSVC executable Unzip the source package and build JSVC executable. chmod 755 commons-daemon-1.0.5-src.tar.gz tar zxvf commons-daemon-1.0.5-src.tar.gz cd commons-daemon-1.0.5-src/src/native/unix Before building the JSVC executable, please make sure you have set JAVA_HOME variable correctly. And make sur...