somecto
somecto

Reputation: 239

How to enforce a prototype scope of Spring beans

I have a stateful Spring bean. How can I enforce its usage scope to prototype in my application?

How can I prevent another developper on my project of injecting this bean with the singleton scope?

I know you can configure scope either via annotation or via the xml configuration. Of what I have seen, when using Spring 3, the scope configured by annotation gets overriden by the scope defined manually in the xml. How can I enforce my scope, thru configuration or programatically, so my bean will never be used as a singleton?

I thought about inspecting the bean scope on the startup of the application, but it doesn't sound like an elegant solution.

Upvotes: 2

Views: 1324

Answers (3)

Aravindan R
Aravindan R

Reputation: 3084

This is not elegant, but AFAIK this is the only way to achieve what you are looking for

public class MyStatefulBean implements InitializingBean, ApplicationContextAware, BeanNameAware {

    private String myName;

    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void setBeanName(String s) {
        this.myName = s;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if(this.context.isSingleton(this.myName))
            throw new RuntimeException("Bean CANNOT be singleton");
    }
}

Upvotes: 3

Dave Newton
Dave Newton

Reputation: 160191

If you don't want to rely on the API user doing what's expected of them, expose the bean via a factory.

Upvotes: 0

Affe
Affe

Reputation: 47954

Document it? There's no way for it to know if someone is keeping a reference to the bean and reusing it or sharing it across threads when they should have been using getBean() to get the prototype.

Spring cannot stop your peers from writing code that is simply incorrect, which is all that such a usage would be.

Upvotes: 0

Related Questions