raven-king
raven-king

Reputation: 1550

Instantiating spring bean objects

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"); ?

Upvotes: 0

Views: 5634

Answers (1)

Bozho
Bozho

Reputation: 597382

First - are right with your assumptions. Using new means spring doesn't manage the object.

Solutions can be:

  • appContext.getBean("beanA"), where the bean is of scope "prototype". You obtain the appContext by injecting it, or by implementing ApplicationContextAware
  • using @Configurable and apsectJ weaving. That way even objects instantiated with new become managed by spring (the weaver plugs into the compiler or the vm)
  • using a 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.

Upvotes: 2

Related Questions