Spring - Registering beans within @Component classes [Updated: Sep 1, 2016, Created: Aug 30, 2016] |
|
||
Classes annotated with any of the stereotype component annotations (@Component, @Service, @Repository etc), can also expose new bean definitions using @Bean annotation on their methods. ![]() @Component classes are not CGLIB proxiedClasses annotated with @Configuration are CGLIB proxied. @Component classes, however, are not enhanced with CGILIB to intercept the bean method invocation, that means a direct call will not route through the container and will return a new instance every time. In the component classes, we can use any valid annotation along with @Bean method and it's parameters, exactly the same way we use them in @Configuration classes (e.g. @Lazy, @Qualifier, @Primary etc). Lite @Beans modeWhen @Bean methods' enclosing class is not annotated with @Configuration like in above @Component case, they are said to operating in a 'lite' mode. Accoring to Spring referece doc :
@Configuration classes can also be scannedWe can even use @Configuration classes instead of @Component classes to achieve the same. @Configuration basically itself is a component (it's annotated with @Component). In that case, the methods annotated with @Bean will be CGILIB enhanced and will be proxied. AnnotationConfigApplicationContext and @Component classesAnnotationConfigApplicationContext is an implementation of ApplicationContext to bootstrap the Spring container. Other than @Configuration classes, AnnotationConfigApplicationContext is capable to accept the class(s) annotated with @Component (or any other stereotype) as well, but as mentioned above doing so will cause the beans to operate in lite mode. Possible use casesThe primary purpose of defining beans that way is: we want our component beans to act like a factory. Other than that, there might be some scenarios where we cannot modify the main @Configuration(s) files or we want to define/customize beans only within a particular module. Example projectDependencies and Technologies Used:
|
|
||
|
|||
|
|||
|