@Autowired注解的使用

使用 @Autowired 注释的 Boss.java  

1.package com.baobaotao;    

import org.springframework.beans.factory.annotation.Autowired;    

  public class Boss {    

     @Autowired   

    private Car car;    

    @Autowired   

    private Office office;    

此处省略了getter和setter方法。

在域变量上加上标签@Autowired,并且去掉 相应的get 和set方法

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

<!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 -->    

  事先在Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。  

    <bean class="org.springframework.beans.factory.annotation.    

        AutowiredAnnotationBeanPostProcessor"/>    

   <!-- 移除 boss Bean 的属性注入配置的信息<property> -->     

    <bean id="boss" class="com.baobaotao.Boss"/>    

     此处省略了<property>配置信息。

    <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,并注入到对应的地方中去。  

 

原文地址:https://www.cnblogs.com/panzai/p/11728296.html