spring - @Resource 和 @Autowired 的区别

标签 spring

我不明白为什么当我用@Resource注释下面的行时会出现错误,当我写@Autowired时我不会收到此错误。

@Resource(name = "systemConfigService")
private SystemConfigService systemConfigService;

它告诉,无法解析 bean systemConfigService

SystemConfigService 是一个接口(interface)。

最佳答案

@Autowired 与@Qualifier 结合也可以按名称 Autowiring 。主要区别在于 @Autowired 是 spring 注释,而 @Resource 由 JSR-250 指定。所以后者是普通java的一部分,而@Autowired只能由spring使用。

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.

As a specific consequence of this semantic difference, beans which are themselves defined as a collection or map type cannot be injected via @Autowired since type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection/map bean by unique name.

注意: 与适用于字段、构造函数和多参数方法的 @Autowired 相比(允许通过参数级别的限定符注释缩小范围),@Resource 仅支持字段和具有单个参数的 bean 属性 setter 方法。因此,如果您的注入(inject)目标是构造函数或多参数方法,请坚持使用限定符。

关于spring - @Resource 和 @Autowired 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50696100/

相关文章:

java - 当数据库返回null时,SimpleJDBCTemplate.queryForInt做了什么?

spring - 如何测试使用 Hibernate Search 的服务?

javascript - Angular JS 和 Spring - 如何过滤 JSON 对象

java - 在 Spring Boot 中使用 CrudRepository 检索 DiscriminatorColumn

java - 在 Spring 中获取 FileNotFoundException

java - 为什么 JpaRepository 的删除方法实际上并没有从数据库中删除元素?

java - Spring Boot - 嵌套 ConfigurationProperties

java - 在 64 位机器上运行时出现 NoClassDefFoundError

java - Spring Boot 。找不到类型为 'org.hibernate.SessionFactory' 的 bean

java - Tomcat/Spring - 获取未解码的参数