I was doing my daily staff and I've realized despite I use @Configuration oftenly I don't know how it works exactly, after reading the spring.io documentations I can't tell for sure if @Configuration is a way of making a class a singleton.
So.... I guess my question is:
What should I use to proper make a singleton @Configuration or @Component? and why's that'?
I've been investigating about this 2 options with 2 examples like this:
1st example
@Configuration
public static class Config {
@Bean
public SimpleBean simpleBean() {
return new SimpleBean();
}
@Bean
public SimpleBeanConsumer simpleBeanConsumer() {
return new SimpleBeanConsumer(simpleBean());
}
}
2nd example
@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.
So I guess I've answered my own question but not sure if I'm missing something.