先写 Autowired
Autowired
简介
始于 Spring 2.5 版本,这个版本的框架是注解驱动的依赖注入,主要的注解就是@Autowired
,负责解析和注入 Bean。
使用
2.5 以前所有的 Bean 注入都是在 Spring 的配置文件中,Spring 容器能自动依赖注入。可以用于变量初始化(常用)、赋值和构造函数。
注册 Bean
@Component("fooFormatter")
public class FooFormatter {
public String format() {
return "foo";
}
}
用于变量初始化
@Component
public class FooService {
@Autowired
private FooFormatter fooFormatter;
}
用于赋值
public class FooService {
private FooFormatter fooFormatter;
@Autowired
public void setFormatter(FooFormatter fooFormatter) {
this.fooFormatter = fooFormatter;
}
}
用于构造函数
public class FooService {
private FooFormatter fooFormatter;
@Autowired
public FooService(FooFormatter fooFormatter) {
this.fooFormatter = fooFormatter;
}
}
注意点
@Autowired
不能是 static 的,因为静态变量会在类启动后最先加载,当类加载器加载静态变量时,Spring 的上下文环境还没有被加载。
@Autowired
本身就是单例模式,只会在程序启动时执行一次,所以不需要加 final。
可选项
当 Spring 不能解析 Bean 的时候就会跑异常
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.autowire.sample.FooDAO] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}