5

Using Spring 3.1. If I want to retrieve a bean with prototype scope (i.e. I want a different instance of the class each time), is it possible to retrieve the bean without having to use an ApplicationContextaware class?

This is how I do it at present

@Component
@Qualifier("MyService")
public class MyServiceImpl implements MyService {

    @Override
    public void doSomething() {
        Blah blah = (Blah)ApplicationContextProvider.getContext().getBean("blah");
        blah.setThing("thing");
        blah.doSomething();
    }
}


@Component("blah")
@Scope("prototype")
public class Blah {
    ....
}

where ApplicationContextProvider implements ApplicationContextAware.

Is it possible to do this with annotations or simple Spring configuration without having to use an ApplicationContextAware class?

CodeClimber
  • 4,584
  • 8
  • 46
  • 55

2 Answers2

1

Spring has some fairly sophosticated methods for achieving what you're after...

See the spring documentation: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-factory-scopes-other-injection

Searching for spring proxy scope on google also threw up some results...

Michael Wiles
  • 20,902
  • 18
  • 71
  • 101
  • 2
    Yep, think this is what I'm looking for. This SO question shows how to do it with annotations: http://stackoverflow.com/questions/4503606/annotation-equivalent-of-aopscoped-proxy – CodeClimber Jan 11 '13 at 10:15
0

You don't really need a ApplicationContextAware. You just need a BeanFactory (ApplicationContextAware is just a convinient way to get it).

A bean with scope prototype just means that everytime ApplicationContext.getBean is called a new instance of the bean is created. If you try to inject a prototype bean in a singleton, your prototype bean will be injected once (and so is no more a prototype).

There is something called method injection that may help you if you really need it, but it is more complex than simply calling applicationContext.getBean().

ben75
  • 29,217
  • 10
  • 88
  • 134
  • 1
    Thanks for response. I'm trying to get away from writing any Spring specific Java be it implementing ApplicationContextAware or using a BeanFactory. – CodeClimber Jan 11 '13 at 10:23