Spring bean scope based on dynamic constructor value

I need to create a bean where it should be cached based on the value of the dynamic constructor. Example: I need an OrganizationResource bean, where the organization "x" (constructor value) will have its own values ​​for specific instances, and "y" (constructor value) will have different values. But I do not want to create a new object for each x value, I want it to be cached.

I know that for a dynamic constructor value, there are 2 scopes, singleton and prototype. I plan to use a prototype, but it seems that every time it will create a new object, how can I implement a cache based on the constructor value in spring?

+4
source share
1 answer

FactoryBean is the way to go. It is very simple, try it. All you have to do is create a class that implements FactoryBean and reference it in the bean definition file:

 package some.package; import org.springframework.beans.factory.FactoryBean; public class ExampleFactory implements FactoryBean { private String type; public Object getObject() throws Exception { //Logic to return beans based on 'type' } public Class getObjectType() { return YourBaseType.class; } public boolean isSingleton() { //set false to make sure Spring will not cache instances for you. return false; } public void setType(final String type) { this.type = type; }} 

Now, in the bean definition file, put:

 <bean id="cached1" class="some.package.ExampleFactory"> <property name="type" value="X" /> </bean> <bean id="cached2" class="some.package.ExampleFactory"> <property name="type" value="Y" /> </bean> 

It will create objects based on the strategy implemented in ExampleFactory.getObject() .

+2
source

Source: https://habr.com/ru/post/1444097/


All Articles