@Required(不常用)
@Autowired(常用)
下面用例子解釋以上內容:
@Autowired注解的三種方式如下,第一種是直接在屬性名上加注解,這樣就可以不用在寫set方法進行注入,這種方式與set方式作用一樣;第二種是在set方法上加注解;第三種是在構造器上加注解
測試代碼如下:
xml配置文件正常即可:
圖解:可以在當前類中,聲明ApplicationContext的引用,然后可以用@Autowired進行注解,這時候可以在當前類中得到這個容器,並且可以使用這個容器了
圖解:
數組也就是Set或List等,提供所有特定類型的bean是指:當Set中聲明MovieCatalog時,當前的ApplicationContext中所有是Set泛型中聲明類型的這種bean或它的子類,都可以被@Autowired注解,把這些bean的實例放到當前的集合當中。
這里的key也就是所有bean的id,value也就是bean的對象,同時我們希望放在Map或者是Set和List的集合中,這種bean的實例是有順序的,可以實現以上接口來實現。
例子如下:
interface的兩個實現類:
調用類實現:

1 @Component 2 public class BeanInvoker { 3 4 //可以利用@Autowired注解,將兩個實現類的實例同時注入list或map中 5 //list中會被注解進來bean的實例,只有bean的對象 6 @Autowired 7 private List<BeanInterface> list; 8 9 //map中會被注解進來bean的id和實例,bean的id就是class的類名第一個字母小寫 10 @Autowired 11 private Map<String, BeanInterface> map; 12 13 //將@Qualifier與@Autowired一起用,可以指定注入的某一個實現類的實例 14 @Autowired 15 @Qualifier("beanImplOne") 16 private BeanInterface beanInterface; 17 18 public void say() { 19 if(null != list && 0 != list.size()) { 20 System.out.println("list..."); 21 for(BeanInterface bean:list) { 22 System.out.println(bean.getClass().getName()); 23 } 24 } 25 else { 26 System.out.println("List<BeanInterface> list is null...."); 27 } 28 29 System.out.println(); 30 31 if(null != map && 0 != map.size()) { 32 System.out.println("map..."); 33 for(Map.Entry<String, BeanInterface> entry:map.entrySet()) { 34 System.out.println(entry.getKey() + "......" + entry.getValue().getClass().getName()); 35 } 36 } 37 else { 38 System.out.println("Map<String, BeanInterface> map is null..."); 39 } 40 41 System.out.println(); 42 43 if(null != beanInterface){ 44 System.out.println(beanInterface.getClass().getName()); 45 } 46 else { 47 System.out.println("beanInterface is null..."); 48 } 49 } 50 }
測試類:
注釋:當某個接口有多個實現類時,可以將@Qualifier與@Autowired一起用, 指定應該注入的對象的實例。@Qualifier中應該是要指定注入的bean的id
打印結果如下: