Both @Component and @Named for the same bean class

前端 未结 3 1611
孤独总比滥情好
孤独总比滥情好 2020-12-29 02:11

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

相关标签:
3条回答
  • 2020-12-29 02:55

    @Component and @Named are annotations that basically do the same thing, but come from different APIs.

    @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 belongs to javax.inject API. It marks class to be autodetected as a bean and requires you to specify a name.

    Spring supports both these APIs. It doesn't make sense to use both annotations at the same class since they provide the same functionality.

    See also:

    • 3.10 Classpath scanning and managed components
    0 讨论(0)
  • 2020-12-29 02:56

    Spring supports @Named annotation (JSR-330) as an alternative to @Component (Spring).

    Generally, @Named is poorly named since doesn't describe what it does, so I would prefer to use @Component whenever I can.

    0 讨论(0)
  • 2020-12-29 03:03

    Either of the both should be used. Using both @Component and @Named don't make any sense. Adding to above (Other's) comment @Component("[someComponentID]") and @Named("[someNamedID]") to assign an ID to a bean by passing the ID in the parenthesis, if not implicitly assigned one.

    0 讨论(0)
提交回复
热议问题