This annotation allows Spring to resolve and inject collaborating beans into your bean.
我们将介绍如何启用自动装配,以各种 方式连接bean ,使bean可选,使用@Qualifier注释解决bean冲突以及潜在的异常情况。
### Autowired on Properties
注释可以直接用于属性,因此不需要getter和setter:
@Component("fooFormatter")
public class FooFormatter{
public String format(){
return "foo";
}
}
@Component
public class FooService{
@Autowired
private FooFormatter fooFormatter;
}
### Autowired on Setters
@Autowired注解可以在setter方法中使用。当在setter方法上使用注释时,在创建FooService时使用FooFormatter实例调用setter方法:
public class FooService{
private FooFormatter fooFormatter;
@AutoWired
public void setFooFormatter(FooFormatter fooFormatter){
this.fooFormatter = fooFormatter;
}
}
### Autowired on Constructors
@Autowired 注释也可以在构造函数中使用。
publicclassFooService {
private FooFormatter fooFormatter;
@Autowired
public FooService (FooFormatter fooFormatter) {
this.fooFormatter = fooFormatter;
}
}
### @Qualifier 消除歧义
@Component("fooFormatter")
public class FooFormatter implements Formatter {
public String format() {
return"foo";
}
}
@Component("barFormatter")
public class BarFormatter implements Formatter {
public String format() {
return"bar";
}
}
public class FooService {
@Autowired
@Qualifier("FooFormatter")
private Formatter formatter;
}