1. 程式人生 > 實用技巧 >Spring-05-註解實現自動注入

Spring-05-註解實現自動注入

1、實現自動注入的前提條件

<!--在Spring配置檔案中新增 註解 的支援-->
<context:annotation-config/>

2、實現方式

  • @AutoWired

    • @Autowired為Spring提供的註解,需要匯入包org.springframework.beans.factory.annotation.Autowired;

    • @Autowired 等同於 @Autowired(required = true),表示注入的時候,該bean必須存在,否則就會注入失敗。@Autowired(required = false),表示如果當前有bean直接注入,沒有則跳過,不會報錯。

    • 可以寫在欄位和setter方法上,寫在欄位上,那麼就不需要再寫setter方法

    • @Autowired採取的策略為ByType

    • 按照型別注入會產生一個問題,當一個型別有多個bean值的時候,會產生混亂,不知道具體注入哪一個

      <bean id="cat1" class="com.hmx.pojo.Cat"></bean>
      <bean id="cat2" class="com.hmx.pojo.Cat"></bean>
      public class People {
      @Autowired
      private Cat cat;
      //Could not autowire. There is more than one bean of 'Cat' type.
      }

      此時需要和@Qualifier(value = "")一起使用,‘value =’ 可以省略,實現唯一的注入

      public class People {

      @Qualifier("cat1")
      @Autowired
      private Cat cat;
      }

  • @Resource

    • @Resource註解由J2EE提供,需要匯入包

      javax.annotation.Resource

    • @Resource(name = "",type = 類名.class)

    • 可以寫在欄位和setter方法上,寫在欄位上,那麼就不需要再寫setter方法

    • @Resource預設按照ByName

      自動注入

      <bean id="cat1" class="com.hmx.pojo.Cat">
      <property name="name" value="布偶"/>
      </bean>

      <bean id="cat2" class="com.hmx.pojo.Cat">
      <property name="name" value="英短"/>
      </bean>
      //既沒有指定name,又沒有指定type,則自動按照byName方式進行裝配
      public class People {
      @Resource
      private Cat cat1;
      }
      //指定了name,則從上下文中查詢名稱(id)匹配的bean進行裝配,找不到則丟擲異常
      public class People {
      @Resource(name = "cat1")
      private Cat cat1;
      }
      //指定了type,則從上下文中找到類似匹配的唯一bean進行裝配,找不到或是找到多個,都會丟擲異常
      public class People {
      @Resource(type = Dog.class)
      private Cat cat1;
      }
      //同時指定了name和type,則從Spring上下文中找到唯一匹配的bean進行裝配,找不到則丟擲異常
      public class People {

      @Resource(name = "cat1",type = Dog.class)
      private Cat cat1;
      }