40

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.

Finally which name is taken by the application if the @Named annotation does not specify any name for the bean?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
TechSpellBound
  • 2,505
  • 6
  • 25
  • 36

3 Answers3

73

@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:

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • Worth noting. There are various libraries etc that work with spring that work differently with '@Named' vs '@Component'. – Jesse Nelson Dec 30 '22 at 16:47
13

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.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
MagGGG
  • 19,198
  • 2
  • 29
  • 30
  • Agreed, (a)Named is poorly named. However, many classes are a shared resource amongst projects from different frameworks. Using @Named to bean-ify the class requires javax.injection as a dependency for each application, much better than another framework depending on Spring for the annotation.. – Freestyle076 Oct 12 '17 at 21:39
0

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.