Fork me on GitHub

Spring Bean装配之Autowired注解

1.可以将@Autowired注解为setter方法

1
2
3
4
@Autowired
public void setInjectionDAO(InjectionDAO injectionDAO) {
this.injectionDAO = injectionDAO;
}

2.可以用于构造器或成员变量

1
2
3
4
@Autowired(required=false)
public void setInjectionDAO(InjectionDAO injectionDAO) {
this.injectionDAO = injectionDAO;
}

默认情况下,如果因找不到合适的bean将会导致autowiring失败抛出异常,可以通过将其required设置为false表示并非必须,每个类只能有一个构造器标记为required=true,也就是只能有一个构造器为必须,这种情况下建议使用@Required注解:

1
2
3
4
@Required
public void setInjectionDAO(InjectionDAO injectionDAO) {
this.injectionDAO = injectionDAO;
}

@Required表示标记的bean属性在bean装配时必须被填充,通过在bean定义或者自动装配一个明确的属性值


3.用于注解众所周知的解析依赖性借口,如BeanFactory,ApplicationCon,Environment,ResourceLoader,ApplicationEventPublisher,MessageSource 等

1
2
3
4
public class BeanSutowired{
@Autowired
private ApplicationContext context;
}

4.可通过添加注解给需要该类型的数组的字段或方法,提供ApplicationContext中的所有特定类型的bean

下面的示例中,list添加了@Autowired注解,那么所有的实现BeanInterface接口的bean,假如有BeanimplOneBeanimplTwo都实现了BeanInterface接口,那么这时list中将包含有BeanimplOneBeanimplTwo

1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class BeanInvoker implements BeanInterface{

@Autowired
private List<BeanInterface> list;

public void say(){
System.out.println("list...");
for (BeanInterface bean : list) {
System.out.println(bean.getClass().getName());
}
}

如果希望数组有序,可以使用@Order注解或者实现org.springframework.core.Ordered接口,但是对map无效

1
2
3
4
@Order(1)
@Component
public class BeanimplTwo implements BeanInterface{
}

5.用于装配key为String的Map

下面的示例中,map添加了@Autowired注解,那么所有的实现BeanInterface接口的bean,加入有BeanimplOneBeanimplTwo都实现了BeanInterface接口,那么这时map中将包含有键为bean名称和值为bean的两个元素。

1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class BeanInvoker implements BeanInterface{

@Autowired
private Map<String, BeanInterface> map;

public void say(){
System.out.println("map...");
for (Map.Entry<String, BeanInterface> entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue().getClass().getName());
}
}


6.@Qualifier

  • 按类型自动装配可能多个bean实例的情况,可以使用Qualifier注解缩小范围或指定唯一
1
2
3
@Autowired
@Qualifier("beanImplTwo")
private BeanInterface beanInterface;
  • 用于指定单独的构造器参数或方法参数
  • 用于注解集合类型变量

可以在bean的定义中使用@Qualifier注解给他限定一个范围,比如

1
2
3
4
@Qualifier("beanImpl")
@Component
public class BeanImplTwo implements BeanInterface{
}

然后在注入时,使用@Qualifier限定,则下面的list将会匹配到所有@Qualifier("beanImp")bean

1
2
3
@Autowired
@Qualifier("beanImpl")
private List<BeanInterface> list;

参阅:
慕课网:Spring入门篇

-------------本文结束感谢您的阅读-------------