问题来源

I don’t see any difference between two ways, @Qualifier is always used with @Autowired.

  1. @Autowired
  2. @Qualifier("alpha")

VS

  1. @Resource(name="alpha")

Anyone could let me know the difference? Thanks!

它们之间的区别

@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 is wired by name too . So if @Autowired is used together with @Qualifier , it is the same as the @Resource. 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. It is suggested to use @Resource for fields and setter injection. Stick with @Qualifier and @Autowired for constructor or a multi-argument method injection.

@Autowired可以单独使用。如果单独使用,则按类型连接。
因此,如果容器中声明了多个相同类型的bean,就会出现问题,因为@Autowired不知道使用哪个bean来注入。
因此,同时使用@Qualifier@Autowired通过指定bean名称(通过名字来连接)来明确哪些bean需要被注入。
@Resource也是通过名称连接的。所以如果@Autowired@Qualifier一起使用,它的作用和@Resource是一样的。
区别在于@Autowired@Qualifier是spring注解,而@Resource是标准的java注解(来自JSR-250)。此外,@Resource只支持字段和setter注入,而@Autowired支持字段、setter、构造函数和多分配方法注入。

建议对字段和setter注入使用@Resource。坚持使用@Qualifier@Autowired 在构造函数或者多分配方法注入。
原因:

If you intend to express annotation-driven injection by name, do not primarily use @Autowired - even if is technically capable of referring to a bean name through @Qualifier values. Instead, prefer the JSR-250 @Resource annotation which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.

如果您打算通过名称来表达注释驱动的注入,请不要主要使用@Autowired——即使在技术上它可以通过@Qualifier值来引用bean名称。
相反,最好使用JSR-250 @Resource注释,它在语义上定义为通过惟一的名称标识特定的目标组件,声明的类型与匹配过程无关。