加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – Spring依赖注入,使用@Named还是@Resource?

发布时间:2020-12-15 01:28:45 所属栏目:大数据 来源:网络整理
导读:在Spring中,有两个单独的注释用于按名称执行依赖注入,javax.annotation.Resource和javax.inject.Named. documentation at Spring表示@Resource应该按名称用于注入: If you intend to express annotation-driven injection by name,do not primarily use @Au

在Spring中,有两个单独的注释用于按名称执行依赖注入,javax.annotation.Resource和javax.inject.Named. documentation at Spring表示@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只提倡@Resource而不是@Autowired和@Qualifer.直到later in the documentation才提及@Named.

JSR-250定义了@Resource,而JSR-330定义了@Inject和@Named.我知道它们可以很容易地在Spring中混合和匹配.使用哪个JSR?

看起来像Guice和CDI的可移植性会很好,因此使用JSR-330注释.另一方面,文档还指出Spring中使用JSR-330注释时的几个limitations.

注释注释的最佳实践(如果有)是什么?

谢谢.

最佳答案
@Resource是较旧的,自Spring 2.5开始受支持,而在Spring 3.0中添加了@Named支持,它们都可用于实现同名注入的目的.

使用Spring时,我更倾向于选择一个而不是另一个,而是向后兼容Spring 2.5以及是否可以在类路径中添加/假设javax.inject.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读