使用注解按名称自动装配Spring bean [英] Autowiring spring bean by name using annotation

查看:390
本文介绍了使用注解按名称自动装配Spring bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Springs最新版本中,我们可以使用@Autowired注释自动装配bean.这将使用其类型(或构造函数,如果应用在其上)自动装配bean. 有什么方法可以基于我们正在使用的bean名称使用@Autowired批注,而在Spring的XML文件中,没有注释的话,就是 autowire ="byName" ?

In Springs latest version, we can autowire a bean using annotation as @Autowired. This will autowire the bean using its type(or constructor, if applied on it). Is there any way I can use the @Autowired annotation based on the bean name which we were doing without annotation in Spring's XML file as autowire="byName"?

推荐答案

除非需要构造函数注入或多参数方法注入,否则可以使用JSR-250 @Resource来进行自动bean命名.

You can use JSR-250 @Resource for by-name bean autowiring, unless you need constructor injection or multi-parameter method injection.

从文档中

如果您打算按名称表示注释驱动的注入,则即使技术上可以通过@Qualifier值引用bean名称,也不要主要使用@Autowired.而是使用JSR-250 @Resource批注,该批注的语义定义是通过其唯一名称来标识特定目标组件,而声明的类型与匹配过程无关.

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, use 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.

这篇关于使用注解按名称自动装配Spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆