7

From a software design perspective, when should we use @Component instead of a traditional Java class (that needs to be explicitly instantiated by 'new')? For example, if we need to create a class that is one of the following patterns:

  • Adapter

  • Bridge

  • Façade

  • Strategy

  • Translator

Should the class have the @Component annotation (or any Spring derivative annotation such as @Repository/@Controller/@Service)?

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
OneNoOne
  • 587
  • 7
  • 23
  • Mark a class as @Component (or derivative) when some other class depends on the marked class. It allows Spring to wire up the dependencies. – Andrew S Apr 22 '19 at 14:43
  • 2
    It should be annotated when you want it to be a Spring bean, which can thus be injected into other Spring beans, and have other Spring beans injected into it. Whether the class is an adapter or a bridge or anything else is irrelevant. – JB Nizet Apr 22 '19 at 14:44

1 Answers1

5

Spring applies the Inversion of Control principle, which drills down to that the framework handles stuff for you, so you don't have to worry about it.

By using @Component on the class you let Spring create a bean for you. This way Spring can, for example, inject this bean on runtime when you need it. (For example by Autowiring your constructor).

It is up to you to decide if you want to make use of this functionality for your class. A facade for example could very well be a Spring component, this way you could possibly inject an API implementation that is exposed via a facade on runtime, without the need to think about the dependency injection implementation.
I would not recommend using this annotation on a DTO or model class for example. These classes mostly consist of data and don't fit the need to be managed by Spring.

Other interesting related questions that can help you decide when to create a component:
What's the difference between @Component, @Repository & @Service annotations in Spring?

Spring: @Component versus @Bean

serv-inc
  • 35,772
  • 9
  • 166
  • 188