Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we use @Component in Spring?

Tags:

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)?

like image 945
OneNoOne Avatar asked Apr 22 '19 14:04

OneNoOne


People also ask

When should we use @component annotation?

@Component is a class-level annotation. It is used to denote a class as a Component. We can use @Component across the application to mark the beans as Spring's managed components.

When should I use component scan in Spring boot?

Using @ComponentScan in a Spring Application. With Spring, we use the @ComponentScan annotation along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.

Can I use @component instead of service?

If your component is a generic component, not really living at the service layer, or is accessible but could hold state, then use @Component . If your component is a specific service, living at the service layer, or is accessible and does not inherently hold state, use @Service .

What is difference between @component and @configuration in Spring?

The main difference between these annotations is that @ComponentScan scans for Spring components while @EnableAutoConfiguration is used for auto-configuring beans present in the classpath in Spring Boot applications.


1 Answers

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

like image 94
KeukenkastjeXYZ Avatar answered Nov 15 '22 06:11

KeukenkastjeXYZ