@Component和@Named都是同一个bean类 [英] Both @Component and @Named for the same bean class

查看:627
本文介绍了@Component和@Named都是同一个bean类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring应用程序中充当bean的类是否需要 @Component @Named at同时?

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 <,那么应用程序将采用哪个名称? / code> annotation没有指定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 Classpath scanning and managed components

这篇关于@Component和@Named都是同一个bean类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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