我试图了解这两个注释之间的差异以及它们如何影响 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/