一些spring的开发人员在使用这三个标签进行注入的时候感到困惑。我来尝试解释一下这三个注解的主要区别。事实上,这三者非常相似,只存在一些微小的差别。在稍后的文章中会进行解释。
- @Resource-在javax.annotation包中定义
- @Inject-在javax.inject包中定义
- @Autowired-在org.springframework.bean.factory包中定义
我们创建一个Car接口和两个实现类Volkswagen和Toyota.分别通过三种标签来注入来观察差异. 接口和类的定义如下.这里只提供了代码片段,如果你想运行这个例子,需要新建一个spring项目.
//Car.java
package javabeat.net.basic;
public interface Car {
}
//Volkswagen.java
package javabeat.net.basic;
import org.springframework.stereotype.Component;
@Component
public class Volkswagen implements Car{}
//Toyota.java
package javabeat.net.basic;
import org.springframework.stereotype.Component;
@Component
public class Toyota implements Car{}
Inject Interface
@Resource
private Car car;
@Autowired
private Car car;
@Inject
private Car car;
下面是抛出的异常:
Resource注解抛出:org.springframework.beans.factory.NoSuchBeanDefinitionException:
Autowired注解抛出:No unique bean of type [javabeat.net.basics.Car] is defined:
Inject注解抛出:expected single matching bean but found 2: [volkswagen, toyota]
Field Type
@Resource
private Volkswagen car;
@Autowired
private Volkswagen car;
@Inject
private Volkswagen car;
上面的代码工作的很好。 通过bean type,三个注解都注入了Volkswagen.
Qualifier name
@Resource
@Qualifier("volkswagen")
private Car car;
@Autowired
@Qualifier("volkswagen")
private Car car;
@Inject
@Qualifier("volkswagen")
private Car car;
上面三个注解结合了@Qualifier将Volkswagen成功注入了。
Conflicting Information
@Resource
@Qualifier("nkl")
private Car volkswagen;
@Autowired
@Qualifier("nkl")
private Car volkswagen;
@Inject
@Qualifier("nkl")
private Car volkswagen;
上面的代码,只有@Resource注入了Volkswagen类型.但是,@Autowired和@Injects都抛出了异常.
Resource注解抛出:org.springframework.beans.factory.NoSuchBeanDefinitionException:
Autowired注解抛出:No matching bean of type [javabeat.net.basics.Car] found for dependency:
所以主要的区别是:@Autowired和@Inject无区别,这两个注解都是通过AutowiredAnnotationBeanPostProcessor来注入依赖。但是@Resource使用CommonAnnotationBeanPostProcessor来注入依赖。主要的区别是在检查的顺序上。
@Autowired and @Inject
- 1.Matches by Type
- 2.Restricts by Qualifiers
- 3.Matches by Name
@Resource
- 1.Matches by Name
- 2.Matches by Type
- 3.Restricts by Qualifiers (ignored if match is found by name)