【@Autowired】
冷知识:
@Autowired
private MovieCatalog[] movieCatalogs; // 根据类型注入全部的bean对象数组
@Autowired
private Set<MovieCatalog> movieCatalogs; //根据类型注入全部的bean对象集合
@Autowired
private Map<String, MovieCatalog> movieCatalogs; //根据类型注入全部的bean对象,key=bean对象的名称
@Autowired
private Optional<MovieFinder> movieCatalogs; // 注入非必须的
除以上:还支持泛型注入
@Configuration
public class MyConfiguration {
@Bean
public StringStore stringStore() {
return new StringStore();
}
@Bean
public IntegerStore integerStore() {
return new IntegerStore();
}
}
@Autowired
private Store<String> s1; // <String> qualifier, injects the stringStore bean
@Autowired
private Store<Integer> s2; // <Integer> qualifier, injects the integerStore bean
【@Primary】
作用:
- 当容器按照类型自动装配时,可能存在多个满足条件的bean,当使用@Primary修饰bean时该bean在自动装配时的优先级最高
【@Qualifiers】
作用:
- 当容器按照类型自动装配时,可能存在多个满足条件的bean,可以使用@Qualifiers指定需要注入的bean的名称
@Autowired
@Qualifier("main")
private MovieCatalog movieCatalog;
自定义
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Genre {
String value();
}
@Autowired
@Genre("Action")
private MovieCatalog actionCatalog;
【自定义并注册Qualifier】
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomerQualifier {
}
@Bean
public CustomAutowireConfigurer customAutowireConfigurer () {
CustomAutowireConfigurer configurer = new CustomAutowireConfigurer();
configurer.setCustomQualifierTypes(Collections.singleton(CustomerQualifier.class));
return configurer;
}