@ComponentScan
creates beans using both @Configuration
and @Component
. Both these annotations work fine when swapped. What is the difference then?
One of the most important annotations in spring is @Configuration annotation which indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application. This annotation is part of the spring core framework.
You can use @EnableAutoConfiguration annotation along with @Configuration annotation. It has two optional elements, exclude : if you want to exclude the auto-configuration of a class. excludeName : if you want to exclude the auto-configuration of a class using fully qualified name of class.
@Component is a class-level annotation, but @Bean is at the method level, so @Component is only an option when a class's source code is editable. @Bean can always be used, but it's more verbose. @Component is compatible with Spring's auto-detection, but @Bean requires manual class instantiation.
@Component and @ComponentScan are for different purposes. @Component indicates that a class might be a candidate for creating a bean. It's like putting a hand up. @ComponentScan is searching packages for Components.
@Configuration Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime
@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
@Configuration is meta-annotated with @Component, therefore @Configuration classes are candidates for component scanning
You can see more here:
http://docs.spring.io/spring-framework/docs/4.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/Configuration.html
A @Configuration is also a @Component, but a @Component cannot act like a @Configuration.
Actually answer is not complete, is it true that:
@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
But you do can create i.e MyConfiguration.java class then stereotype with @Component
and add @Beans
declaration to it. In this way it will looks as a configuration, main difference is that when annotated class with @Configuration
@Bean
annotated methods are proxy using CGLIB which made in code calls after the first one to return bean from context instead of execute method again and create another instance as happens when using @Component with @Bean
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