Reputation: 164
Is there any difference between behaviour of @Configuration
and @Component
annotation in Spring framework?
Is there any situation when changing @Configuration
to @Component
will change program's behaviour?
I did a few experiments and from what I see so far, they always work the same. Notice that I'm interested specifically in the difference of behaviour - I already know that the two annotations are usually used in different situations.
Upvotes: 2
Views: 1912
Reputation: 516
While they both make annotated classes beans, they serve different purposes.
Treat a class with @Configuration
as a part of your application context where you define beans. Usually, you have @Bean
definitions in your @Configuration
class.
@Component
annotation, on the other hand, means that your class IS a bean itself and that it.
So, for example you need a bean MyService
.
You can define it in two ways:
@Configuration
public class MyAppConfig {
@Bean
public MyService myService(){
return new MyServiceImpl();
}
}
or just
@Component
public class MyServiceImpl {
...
}
So, when you use your @Configuration
as a configuration, adding things specific to it (@ComponentScan, @Bean, ...)
it would have a different behaviour and it won't work with just @Component
instead.
Upvotes: 2
Reputation: 58772
Your @Configuration
class can be annotated also with @ComponentScan
we use the @ComponentScan annotation along with @Configuration annotation to specify the packages that we want to be scanned
If you change to @Component
it won't work as expected
See also difference between @Configuration and @Component
@Configuration is also a @Component but a @Component cannot act like a @Cofinguration
Upvotes: 3