Difference Between @Configuration and @Component, @ComponentScan | Spring Annotation Tutorial

Описание к видео Difference Between @Configuration and @Component, @ComponentScan | Spring Annotation Tutorial

#Configuration vs #ComponentScan vs #ComponentScan

GitHub Account for Free Code download: https://github.com/admindebu
Follow me on FaceBook:   / techtalkdebu  
Instagram: techtalk_debu
LinkedIn :   / debu-paul  

if you like my video, please subscribe to my channel and share the video

#The main purpose of @Configuration annotation is to avoid XML based config.
#Component is Stereotype annotation.

(beans ...)
(context:component-scan base-package="my.base.package"/)
... other configuration ...
(/beans)
and:

@Configuration
@ComponentScan(basePackages = "my.base.package")
public class RootConfig {
... other configuration ...
}

===================

@Configuration
public static class Config {

@Bean
public SimpleBean simpleBean() {
return new SimpleBean();
}

@Bean
public SimpleBeanConsumer simpleBeanConsumer() {
return new SimpleBeanConsumer(simpleBean());
}
}
@Component
public static class Config {

@Bean
public SimpleBean simpleBean() {
return new SimpleBean();
}

@Bean
public SimpleBeanConsumer simpleBeanConsumer() {
return new SimpleBeanConsumer(simpleBean());
}
}
The first piece of code works fine, and as expected, SimpleBeanConsumer will get a link to singleton SimpleBean. But unfortunately, it doesn’t work in a signed enviroment.

The second configuration is totally incorrect because spring will create a singleton bean of SimpleBean, but SimpleBeanConsumer will obtain another instance of SimpleBean which is out of the spring context control.

The reason for this behaviour can be explained as follows:

If you use @Configuration, all methods marked as @Bean will be wrapped into a CGLIB wrapper which works as if it’s the first call of this method, then the original method’s body will be executed and the resulting object will be registered in the spring context. All further calls just return the bean retrieved from the context.

In the second code block above, new SimpleBeanConsumer(simpleBean()) just calls a pure java method. To correct the second code block, we can do something like this:

Thanks & Regards,
Debu Paul

Комментарии

Информация по комментариям в разработке