When annotating a class with @Component, does this mean it is a Spring Bean and Singleton?

SpringAnnotations

Spring Problem Overview


Being fairly new to Spring I have a question about annotating a class. When annotating a class with @Component does this mean this class will be a Spring Bean and by default a singleton?

Spring Solutions


Solution 1 - Spring

Yes, that is correct, @Component is a Spring bean and a Singleton.

If the class belongs to the service layer you may want to annotate it with @Service instead

But have in mind that in order for these annotations to be detected, you need to place this line in applicationContext.xml:

<context:component-scan base-package="com.yourcompany" />

About singletons - spring beans are all in singleton scope by default. The only thing you have to have in mind is that you should not store state in field variables (they should only hold dependencies). Thus your application will be thread-safe, and you won't require a new instance of a bean each time. In other words, your beans are stateless.

Solution 2 - Spring

By default - Yes.

However, you can override this behavior using the @Scope annotation. For example: @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcoView Question on Stackoverflow
Solution 1 - SpringBozhoView Answer on Stackoverflow
Solution 2 - SpringLea ZusView Answer on Stackoverflow