java - Spring - @Named 和 @Component 之间的区别

标签 java spring dependency-injection

我试图了解这两个注释之间的差异以及它们如何影响 Spring 中的注入(inject)。考虑下面的代码 -

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ExternalPropertiesHolder {}

当我用这个注释标记一个类时 -

@ExternalPropertiesHolder
public class SomeProperties {}

然后使用@Inject注入(inject)这个依赖项,它完美地工作 -

@Service
public class SomeService {
    private SomeProperties someProperties;

    @Inject
    public SomeService(SomeProperties someProperties) {
        this.someProperties = someProperties;
    }
}

但是,当我用 @Named 替换 @Component 时 -

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Named           // --> Here!
public @interface ExternalPropertiesHolder {}

然后注入(inject)失败,并出现通常的 bean not found 异常 -

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.hogehoge.SomeProperties] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

我搜索了 Spring 引用文档,以及它关于差异的所有内容 is this -

JSR-330 does not provide a composable model, just a way to identify named components.

这是什么意思?这是否意味着我不能使用 @Named 来组成这样的自定义标记?还是还有别的什么?

P.S.:当然,@Component我指的是org.springframework.stereotype.Component@Named 我指的是javax.inject.Named

最佳答案

所以我直接从 Juergen Hoeller 那里得到了答案。 According to him ,这一行-

JSR-330 does not provide a composable model, just a way to identify named components.

意味着javax.inject.Named只能在给定的bean类上直接声明。可组合注释的故事只适用于 Spring 自己的注释,这正是我所怀疑的。

关于java - Spring - @Named 和 @Component 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36203489/

相关文章:

java - Scala:for循环:迭代目录流

java - 带递归的Codewars Persistence方法?

c# - 了解控制台应用程序中的 .net Core 依赖注入(inject)

java - 将流中的项目相乘

spring - 使用纯Java配置且没有web.xml开发spring mvc应用程序时如何设置欢迎文件?

spring - 为什么 Spring REST Controller 返回时我的图像 byte[] 会被编码?

java - 如何在 @Configuration/@Bean 使用的单元测试中禁用 Spring Autowiring

java - Dagger Android View 注入(inject)错误

Spring boot @SpyBean 导致测试套件出错,可能是由于上下文未重置的问题

java - Android intentService 指南