No. It is used to explicitly declare a single bean, rather than letting Spring do it automatically. If any class is annotated with @Component it will be automatically detect by using classpath scan. We should use @bean, if you want specific implementation based on dynamic condition.
We cannot create a bean of a class using @Component, if the class is outside spring container whereas we can create a bean of a class using @Bean even if the class is present outside the spring container.
@Component is an annotation that allows Spring to automatically detect our custom beans. In other words, without having to write any explicit code, Spring will: Scan our application for classes annotated with @Component. Instantiate them and inject any specified dependencies into them. Inject them wherever needed.
Concretely, it means as the @Service annotation is itself annotated with @Component , Spring will consider a candidate class annotated with @Service as a bean to instantiate. So, your guesswork is right : Classes that implement such interface will be treated as components as well.
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.
By default - Yes.
However, you can override this behavior using the @Scope
annotation. For example: @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With