I'm currently converting XML spring config to Java annotations, and I've ran into a little bit of an annoying situation.
I need to create 3 beans, which use the same class internally, but need to be seperate instances. However, these internal beans need to register their shutdown method with Spring.
I can't think how to do this without creating 9 beans in java (which is fine, but it seems a little bit wrong to be polluting the class like this)
In XML config it looks something like this:
<bean class="outer1">
<constructor-arg>
<bean class="middle">
<constructor-arg>
<bean class="inner" />
</constructor-arg>
</bean>
</constructor-arg>
</bean>
<bean class="outer2">
<constructor-arg>
<bean class="middle">
<constructor-arg>
<bean class="inner" />
</constructor-arg>
</bean>
</constructor-arg>
</bean>
<bean class="outer3">
<constructor-arg>
<bean class="middle">
<constructor-arg>
<bean class="inner" />
</constructor-arg>
</bean>
</constructor-arg>
</bean>
One solution would be:
@Configuration
public class MyConfig{
@Bean(destroyMethod="cleanup")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Inner inner(){
return new Inner();
}
@Bean(destroyMethod="cleanup")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Middle middle(){
return new Middle(inner());
}
@Bean
public Outer outer1(){
return new Outer(middle());
}
@Bean
public Outer outer2(){
return new Outer(middle());
}
@Bean
public Outer outer3(){
return new Outer(middle());
}
}
From reference documentation:
The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made.
This means that every call to the middle() and inner() method creates a new instance of your 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