本文介绍了Spring-@Named和@Component之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to understand the differences between these two annotations and how they affect injection in Spring. Consider the following piece of code -

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

当我用此注释标记课程时-

When I mark a class with this annotation -

@ExternalPropertiesHolder
public class SomeProperties {}

然后使用 @Inject 注入此依赖项完美-

and then this dependency is injected using @Inject, it works perfectly -

@Service
public class SomeService {
    private SomeProperties someProperties;

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

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

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

然后注入失败,并出现通常的bean找不到异常-

Then the injection fails with the usual bean not found exception -

我搜索了Spring参考文档,并说了区别-

I searched the Spring reference documentation, and all it has to say about the difference is this -

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

What does that mean? Does it mean that I cannot use @Named to compose a custom marker like this? Or is there something else?

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

P.S.: Of course by @Component I am referring to org.springframework.stereotype.Component and by @Named I am referring to javax.inject.Named.

推荐答案

所以我直接从Juergen Hoeller得到了答案。 ,此行-

So I got the answer directly from Juergen Hoeller. According to him, this line -

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

means that the javax.inject.Named can only be declared directly on a given bean class. The composable annotation story just works with Spring's own annotations, which is exactly what I suspected.

这篇关于Spring-@Named和@Component之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 23:52