Both @Component and @Named for the same bean class(@Component 和 @Named 都用于同一个 bean 类)
问题描述
在 Spring 应用程序中充当 bean 的类是否同时需要 @Component
和 @Named
?
Does a class which will act as a bean in a Spring application require both @Component
and @Named
at the same time?
如果两者都这样使用有什么意义?
What is the significance if both are used so?
我尝试在网上搜索并查看了这些注释的标准文档,发现它们有点混乱.
I tried searching the net as well as saw the standard documentation of these annotations and found them a bit confusing.
如果 @Named
注释没有为 bean 指定任何名称,那么最终应用程序会采用哪个名称?
Finally which name is taken by the application if the @Named
annotation does not specify any name for the bean?
推荐答案
@Component
和 @Named
是基本上做同样事情的注解,但来自不同的 API.
@Component
and @Named
are annotations that basically do the same thing, but come from different APIs.
@Component
属于 Spring API.它将要自动检测为 bean 的类标记为可以选择允许您为该 bean 指定一个名称 (@Component("foo")
).如果没有明确的名称规范,检测到的 bean 将获得一个从其类的名称派生的默认名称.
@Component
belongs to Spring API. It marks class to be autodetected as a bean and optionally allows you to specify a name for that bean (@Component("foo")
). Without explicit name specification detected bean will get a default name derived from the name of its class.
@Named
属于 javax.inject
API.它将类标记为自动检测为 bean,并要求您指定名称.
@Named
belongs to javax.inject
API. It marks class to be autodetected as a bean and requires you to specify a name.
Spring 支持这两种 API.在同一个类中使用这两个注解是没有意义的,因为它们提供相同的功能.
Spring supports both these APIs. It doesn't make sense to use both annotations at the same class since they provide the same functionality.
另请参阅:
- 3.10 类路径扫描和托管组件
这篇关于@Component 和 @Named 都用于同一个 bean 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:@Component 和 @Named 都用于同一个 bean 类
基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01