`
chenpi529
  • 浏览: 6094 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

转载 spring注解 @autowired 使用详解

阅读更多
1   配置文件的方法



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



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



view plain

    package com.baobaotao;    
       
    public class Boss {    
        private Car car;    
        private Office office;    
       
        // 省略 get/setter    
       
        @Override   
        public String toString() {    
            return "car:" + car + "/n" + "office:" + office;    
        }    
    }    


   
  System.out.println必须实现toString方法
 
我们在 Spring 容器中将 Office 和 Car 声明为 Bean,并注入到 Boss Bean 中:下面是使用传统 XML 完成这个工作的配置文件 beans.xml:  
 
 
清单 4. beans.xml 将以上三个类配置成 Bean  
                  
view plain

    <?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="boss" class="com.baobaotao.Boss">    
            <property name="car" ref="car"/>    
            <property name="office" ref="office" />    
        </bean>    
        <bean id="office" class="com.baobaotao.Office">    
            <property name="officeNo" value="002"/>    
        </bean>    
        <bean id="car" class="com.baobaotao.Car" scope="singleton">    
            <property name="brand" value=" 红旗 CA72"/>    
            <property name="price" value="2000"/>    
        </bean>    
    </beans>    


   
 
 
当我们运行以下代码时,控制台将正确打出 boss 的信息:  
 
 
清单 5. 测试类:AnnoIoCTest.java  
                  
view plain

    import org.springframework.context.ApplicationContext;    
    import org.springframework.context.support.ClassPathXmlApplicationContext;    
    public class AnnoIoCTest {    
       
        public static void main(String[] args) {    
            String[] locations = {"beans.xml"};    
            ApplicationContext ctx =     
                new ClassPathXmlApplicationContext(locations);    
            Boss boss = (Boss) ctx.getBean("boss");    
            System.out.println(boss);    
        }    
    }    
         


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





2   @Autowired



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





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

* 在applicationContext.xml中加入:
 
view plain

    <!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean 进行注入 -->    
      <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 



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


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



清单 6. 使用 @Autowired 注释的 Boss.java  
                  
view plain

    package com.baobaotao;    
    import org.springframework.beans.factory.annotation.Autowired;    
       
    public class Boss {    
       
        @Autowired   
        private Car car;    
       
        @Autowired   
        private Office office;    
       
        …    
    }    







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



        
view plain

               
    <?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"/>    
       
        <!-- 移除 boss Bean 的属性注入配置的信息 -->    
        <bean id="boss" class="com.baobaotao.Boss"/>    
         
        <bean id="office" class="com.baobaotao.Office">    
            <property name="officeNo" value="001"/>    
        </bean>    
        <bean id="car" class="com.baobaotao.Car" scope="singleton">    
            <property name="brand" value=" 红旗 CA72"/>    
            <property name="price" value="2000"/>    
        </bean>    
    </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。来看下面的代码:  对方法



view plain

    package com.baobaotao;    
       
    public class Boss {    
        private Car car;    
        private Office office;    
       
         @Autowired   
        public void setCar(Car car) {    
            this.car = car;    
        }    
         
        @Autowired   
        public void setOffice(Office office) {    
            this.office = office;    
        }    
        …    
    }    





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

view plain

    package com.baobaotao;    
       
    public class Boss {    
        private Car car;    
        private Office office;    
         
        @Autowired   
        public Boss(Car car ,Office office){    
            this.car = car;    
            this.office = office ;    
        }    
         
        …    
    }    





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

相关推荐

    Spring注解@Resource和@Autowired区别对比详解

    主要介绍了Spring注解@Resource和@Autowired区别对比详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    详解Spring注解--@Autowired、@Resource和@Service

    本篇文章主要介绍最重要的三个Spring注解,也就是@Autowired、@Resource和@Service,具有很好的参考价值。下面跟着小编一起来看下吧

    详解 Spring注解的(List&Map)特殊注入功能

    详解 Spring注解的(List&Map)特殊注入功能 最近接手一个新项目,已经没有原开发人员维护了。项目框架是基于spring boot进行开发。其中有两处Spring的注解花费了大量的时间才弄明白到底是怎么用的,这也涉及到...

    Spring常用的7大注解详解代码分析.docx

    1、核心注解 @Required 此注解用于bean的setter方法上。表示此属性是必须的,必须在配置...当在field上使用此注解,并且使用属性来传递值时,Spring会自动把值赋给此field。也可以将此注解用于私有属性(不推荐),如下。

    SpringBoot常用注解详解含使用示例(值得珍藏)

    本文将详细介绍Spring Boot中最常用的注解,包括@SpringBootApplication、@Component、@Service、@Repository、@Controller、@RequestMapping、@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@Autowired...

    Spring Annotation (注解)详解

    关于Spring annotation的详细介绍,包括 @Component,@Autowired 等,感觉还不错。

    spring杂谈 作者zhang KaiTao

    1.10 基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)到底有什么区别。 1.11 在spring中获取代理对象代理的目标对象工具类 1.12 如何为spring代理类设置属性值 1.13 我对SpringDAO层支持...

    spring-zeebe:在Spring或Spring Boot项目中轻松使用Zeebe Java客户端

    春天Zeebe 该项目允许在您的Spring或Spring Boot环境中轻松利用Zeebe。 基本上,它是的包装。 如何使用 连接到Zeebe经纪人 ... @Autowired private ZeebeClient client; 部署工作流程模型 使用@Zee

    spring.doc

    3 Spring基本功能详解 8 3.1 SpringIOC 8 3.2别名Alias 11 别名拓展: 11 3.3 Spring容器内部对象的创建 12 Spring容器内部对象创建拓展: 12 3.3.1使用类构造器实例化(默认无参数) 14 3.3.2使用静态工厂方法实例化...

    Spring中文帮助文档

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    Spring API

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

Global site tag (gtag.js) - Google Analytics