问题描述
我认为两种方式之间没有任何区别, @Qualifier 总是与 @Autowired 一起使用。
I don’t see any difference between two ways, @Qualifier is always used with @Autowired.
@Autowired
@Qualifier("alpha")
VS
@Resource(name="alpha")
任何人都可以告诉我这个区别吗?谢谢!
Anyone could let me know the difference? Thanks!
推荐答案
@Autowired
可以单独使用。如果单独使用,它将按类型连接。因此,如果在容器中声明了多个相同类型的bean,则会出现问题,因为 @Autowired
不知道要使用哪个bean来注入。因此,使用 @Qualifier
与 @Autowired
一起,通过指定bean名称来阐明实际连接的bean (按姓名连线)
@Autowired
can be used alone . If it is used alone , it will be wired by type . So problems arises if more than one bean of the same type are declared in the container as @Autowired
does not know which beans to use to inject. As a result , use @Qualifier
together with @Autowired
to clarify which beans to be actually wired by specifying the bean name (wired by name)
@Resource
也按姓名连线。因此,如果 @Autowired
与 @Qualifier
一起使用,则它与 @相同资源
。
@Resource
is wired by name too . So if @Autowired
is used together with @Qualifier
, it is the same as the @Resource
.
区别在于 @Autowired
和 @Qualifier
是弹簧注释,而 @Resource
是标准的java注释(来自JSR-250)。此外, @Resource
仅支持字段和setter注入,而 @Autowired
支持字段,setter,构造函数和多参数方法注入。
The difference are that @Autowired
and @Qualifier
are the spring annotation while @Resource
is the standard java annotation (from JSR-250) . Besides , @Resource
only supports for fields and setter injection while @Autowired
supports fields , setter ,constructors and multi-argument methods injection.
建议使用 @Resource
进行字段和setter注入。坚持使用 @Qualifier
和 @Autowired
进行构造函数或多参数方法注入。
It is suggested to use @Resource
for fields and setter injection. Stick with @Qualifier
and @Autowired
for constructor or a multi-argument method injection.
参见:
这篇关于@Qualifier和@Resource之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!