Issue
First time using Spring with annotions. I'm trying to define a singleton bean like:
@Bean
public ActionProducer actionProducer() {
return new ActionProducer();
}
But i feel like this is not a correct way to do since returns a "new" bean each time. Should i instead define like below?
@Bean
public ActionProducer actionProducer() {
if (bean==null)
bean=new ActionProducer();
return bean
}
Thanks in advance.
Solution
For each @Configuration
class, Spring will create a proxy which controls the calls to those @Bean
methods. So if you have a @Bean
method, which should create a singleton bean (which it does by default, if you don't specify another scope) the proxy will make sure, that the method is only called once to create the bean. All further calls are intercepted by the proxy and the already existing bean will be returned.
This way, you could even just call that bean method, if you have other beans in that class, which depend on it, without thinking about scopes, duplicate instances etc.:
@Bean
public AnotherClass anotherClass() {
return new AnotherClass(actionProducer());
}
So don't work around the Spring functionality and just implement the method as following:
@Bean
public ActionProducer actionProducer() {
return new ActionProducer();
}
Answered By - dunni
Answer Checked By - Marie Seifert (JavaFixing Admin)