Spring-@Named和@Component之间的区别 [英] Spring - differences between @Named and @Component

查看:656
本文介绍了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 -


原因:
org.springframework.beans.factory.NoSuchBeanDefinitionException:没有
类型的合格Bean [ com.hogehoge.SomeProperties]被发现具有
依赖性:期望至少有1个bean具有此依赖项的自动装配
候选资格。依赖项注释:{}

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参考文档,并说了区别这是-

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


JSR-330没有提供可组合的模型,只是一种识别
命名组件的方式。

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

那是什么意思?这是否意味着我不能使用 @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 -


JSR-330没有提供可组合的模型,只是一种方法标识
命名组件。

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

表示 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之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆