@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,並注入到對應的地方中去。  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM