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 appContext.getBean("beanA"); ?
First – are right with your assumptions. Using
newmeans spring doesn’t manage the object.Solutions can be:
appContext.getBean("beanA"), where the bean is of scope “prototype”. You obtain theappContextby injecting it, or by implementingApplicationContextAware@Configurableand apsectJ weaving. That way even objects instantiated withnewbecome managed by spring (the weaver plugs into the compiler or the vm)lookup-method– 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.Normally, however, you shouldn’t need that. In the rare cases you do, I’d recommend the 3rd option.