I've been playing with Spring and had a quick question...
I have a loop within
class A which instantiates new objects of
class B. To do this I've used the
new operator however I cannot reference any Spring beans injected into instances of
class B as I get a null pointer exception. I think I understand that this would be due to spring not managing these instances as beans and therefore not being able to manage the lifecycle however I was just wondering what the best way to go about creating multiple instances would be i.e. should I used
First - are right with your assumptions. Using
new means spring doesn't manage the object.
Solutions can be:<ul><li>
appContext.getBean("beanA"), where the bean is of scope "prototype". You obtain the
appContextby injecting it, or by implementing
@Configurableand apsectJ weaving. That way even objects instantiated with
newbecome managed by spring (the weaver plugs into the compiler or the vm)</li> <li>using a <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-lookup-method-injection" rel="nofollow">
lookup-method</a> - it's the same as the first option (again requires prototype-scoped bean), but you get a method of your class that returns a new instance each time you call it.</li> </ul>
Normally, however, you shouldn't need that. In the rare cases you do, I'd recommend the 3rd option.