Spring中的@Autowired

来源:互联网 发布:nginx ip跳转域名 编辑:程序博客网 时间:2024/05/22 00:33
今天看代码老遇到@Autowired ,起初一直不懂这个玩意到底干吗用的,后来问了下度娘,大概懂了点,mark一下。

@Autowired是Spring2.5 中引入的注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。通过它的使用来消除 set ,get方法,帮我们把bean里面引用的对象的setter/getter方法省略,也就是说它会自动帮我们set/get。我们在编写spring 框架的代码时候,一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量。并且要配套写上 get 和 set方法。虽然可以通过eclipse等工具来自动生成setter/getter,但会造成代码的累赘,引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作,这样一来就会精简代码。

看下面一个例子:Student有name和age两个属性:
package com.lyc;
public class Student {  
    private Name name;  
    private Age age;  
 
     //此处省略 getter/setter    
 
    @Override 
    public String toString() {  
        return "name:" + name + "\n" + "age:" + age;  
    }  
}

我们在 Spring 容器中将 Name 和 Age 声明为 Bean,并注入到 Student Bean 中:下面是使用传统 XML 完成这个工作的配置文件 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" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
    <bean id="student" class="com.lyc.Student">  
        <property name="name" ref="name"/>  
        <property name="age" ref="age" />  
    </bean>  
    <bean id="age" class="com.lyc.Age">  
        <property name="age" value="22"/>  
    </bean>  
    <bean id="car" class="com.lyc.Name" scope="singleton">  
        <property name="dudian" value=" 成都"/>  
        <property name="xiyou" value="2000"/>  
    </bean>  
</beans>

现在我们引入@Autowired 注释,首先得在在applicationContext.xml中加入
<!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean 进行注入 --> 

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

使用 @Autowired 注释的 Student.java 

package com.lyc;
public class Student {  

    @Autowired
    private Name name;
    @Autowired 
    private Age age;  
 
.........
   
}


修改applicationContext.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">   
 
    <!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 -->   
    <bean class="org.springframework.beans.factory.annotation.   
        AutowiredAnnotationBeanPostProcessor"/>   
 
    <!-- 移除 student Bean 的属性注入配置的信息 -->   
    <bean id="student" class="com.lyc.Student"/>   
    
   <bean id="age" class="com.lyc.Age">  
        <property name="age" value="22"/>  
    </bean>  
    <bean id="car" class="com.lyc.Name" scope="singleton">  
        <property name="dudian" value=" 成都"/>  
        <property name="xiyou" value="2000"/>  
    </bean>  
</beans> 

这样,当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有 @Autowired 注释时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去。  
0 0
原创粉丝点击