4

I have to create a bean where it needs to be cached based on the dynamic constructor value. Example: I need an OrganizationResource bean where "x" (constructor value) organization will have its own specific instance values and "y" (constructor value) will have different values. But I don't want to create a new object for every x value, I want it to be cached.

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

7
  • 5
    Sounds to me like you should consider a Factory pattern here? Commented Nov 5, 2012 at 12:13
  • Thanks for the response, does spring not provide any other way? Commented Nov 5, 2012 at 12:25
  • 1.I don't think that creating an extra object will have any noticable impact on the performance - GC is pretty much optimized for collecting young objects. 2. I'm not sure that IoC container is a good place to create business objects - especially entities, which are likely to be better managed with a JPA compatible framework . Commented Nov 5, 2012 at 13:20
  • You might be able to do this with a custom scope. You do NOT have to use scopes that Spring provides... Commented Nov 5, 2012 at 14:27
  • @nicholas I'm not sure that it's prohibited to specify a factory-method for the prototype scoped beans that will either return a reference to the existing object or will return a new object - depending on the environment state or the argument values. Commented Nov 5, 2012 at 17:44

1 Answer 1

2

FactoryBean is a way to go. It is very simple, give it a try. All you have to do is create a class implementing FactoryBean and reference it in 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 your 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 make objects based on strategy you implemented in ExampleFactory.getObject().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.