简体   繁体   中英

When should we use @Component in Spring?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM