哪个注释,@Resource (jsr250)或@Autowired (spring特定)我应该在DI中使用?

我已经成功地使用在过去,@资源(名称="blah")和@Autowired @Qualifier("blah")

我的直觉是坚持使用@Resource标签,因为它已经被jsr的人批准了。 有人对此有强烈的想法吗?


当前回答

@Autowired(或@Inject)和@Resource都能很好地工作。但在概念上或意义上存在差异

@Resource意思是让我知道一个已知的资源的名称。名称从带注释的setter或字段的名称中提取,或者从name- parameter中提取。 @Inject或@Autowired尝试按类型插入合适的其他组件。

基本上这是两个截然不同的概念。不幸的是,@Resource的spring实现有一个内置的回退,当名称解析失败时就会启动。在本例中,它返回到按类型的@Autowired-kind解析。虽然这种回退很方便,但恕我说,它会引起很多混乱,因为人们没有意识到概念上的差异,并且倾向于使用@Resource进行基于类型的自动装配。

其他回答

这是我从Spring 3.0中得到的。x参考手册:-

Tip 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. As a specific consequence of this semantic difference, beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name. @Autowired applies to fields, constructors, and multi-argument methods, allowing for narrowing through qualifier annotations at the parameter level. By contrast, @Resource is supported only for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.

这里有一个注释: SpringBeanAutowiringSupport。processInjectionBasedOnCurrentContext和SpringBeanAutowiringSupport。processInjectionBasedOnServletContext不能使用@Resource注释。所以,这是有区别的。

@Autowired(或@Inject)和@Resource都能很好地工作。但在概念上或意义上存在差异

@Resource意思是让我知道一个已知的资源的名称。名称从带注释的setter或字段的名称中提取,或者从name- parameter中提取。 @Inject或@Autowired尝试按类型插入合适的其他组件。

基本上这是两个截然不同的概念。不幸的是,@Resource的spring实现有一个内置的回退,当名称解析失败时就会启动。在本例中,它返回到按类型的@Autowired-kind解析。虽然这种回退很方便,但恕我说,它会引起很多混乱,因为人们没有意识到概念上的差异,并且倾向于使用@Resource进行基于类型的自动装配。

@Resource通常由通过JNDI定义的高级对象使用。@Autowired或@Inject将被更常见的bean使用。

据我所知,这不是一个规范,甚至不是一个约定。这更像是标准代码使用这些注释的逻辑方式。

他们两个都一样好。使用Resource的优势在于,如果将来您想使用spring以外的另一个DI框架,您的代码更改将会简单得多。使用Autowired您的代码与spring DI紧密耦合。