@Autowired / @Resource / @Inject用法总结
一直以来,写的项目中用到的自动注入注解都是@autowired,突然有次面试问到三者区别,却不知如何回答,这里趁着手上的项目完结,集中总结一下。
首先创建一个类,交给spring管理
import org.springframework.stereotype.Component;
@Component("test")
public class TestComonent {
public static final String TEST="测试成功啦~~~~";
}
一、@Autowired
spring自带的注解,根据类型进行自动装配,可以使用在成员变量、setter方法、构造方法上,如果和@Qualifier一起使用,则按照名称装配,同时,@Qualifier使用在成员变量、setter方法入参、构造方法入参上
代码块
1.@Autowired用在成员变量上,例如:
@Autowired
private TestComonent component;
@Autowired
@Qualifier("test")
private TestComonent component;
2.@Autowired使用在setter方法上
private TestComonent component;
@Autowired
public void setComponent(TestComonent component) {
this.component = component;
}
private TestComonent component;
@Autowired
public void setComponent(@Qualifier("test")TestComonent component) {
this.component = component;
}
3.@Autowired使用在构造方法上
private TestComonent component;
@Autowired
public TestController(TestComonent component){
this.componente =component;
}
private TestComonent component;
@Autowired
public TestController(@Qualifier("test")TestComonent component){
this.component=component;
}
二、@Inject
SR330中的规范,需要导入java x.inject.Inject;实现注入。
@Inje行自动装配,与@Named(“XXX”)配合使名称进行装配。
@Inject使用在成员变量、setter方法、构造方法上,@Named使用在成员变量、setter方法入参、构造方法入参上
注:使用方法和@Autowired一致。
不同点:@Autowired有个属性为required,默认为true,如果配置为false之后,当没有找到相应bean的时候,系统不会抛错;
三、 @Resource
SR250中的规范,按照名称进行装配,需要导入javax.annotation实现注入
@Resource可以作用在变量、setter方法上。
@Resource(name="test")
private TestComonent component;
private TestComonent component;
@Resource(name="test")
public TestController(TestComonent component){
this.component=component;
}