简体   繁体   English

实例化spring bean对象

[英]Instantiating spring bean objects

I've been playing with Spring and had a quick question... 我一直在玩Spring并且有一个快速的问题......

I have a loop within class A which instantiates new objects of class B . 我在class A实例化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. 为此,我使用了new运算符但是我无法引用任何注入class B实例的Spring bean,因为我得到了一个空指针异常。 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 ie should I used appContext.getBean("beanA"); 我想我明白这可能是因为Spring没有将这些实例作为bean管理,因此无法管理生命周期,但我只是想知道创建多个实例的最佳方法是,我应该使用appContext.getBean("beanA"); ?

First - are right with your assumptions. 首先 - 对你的假设是正确的。 Using new means spring doesn't manage the object. 使用new方法spring不管理对象。

Solutions can be: 解决方案可以是:

  • appContext.getBean("beanA") , where the bean is of scope "prototype". appContext.getBean("beanA") ,其中bean的范围是“prototype”。 You obtain the appContext by injecting it, or by implementing ApplicationContextAware appContext通过注入或通过实现ApplicationContextAware获取appContext
  • using @Configurable and apsectJ weaving. 使用@Configurable和apsectJ编织。 That way even objects instantiated with new become managed by spring (the weaver plugs into the compiler or the vm) 这样,即使用new实例化的对象也会被spring管理(weaver插入编译器或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. 使用lookup-method - 它与第一个选项相同(同样需要原型范围的bean),但是您获得了一个类的方法,每次调用它时都会返回一个新实例。

Normally, however, you shouldn't need that. 但是,通常情况下,你不应该那样做。 In the rare cases you do, I'd recommend the 3rd option. 在极少数情况下,我会推荐第3种选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM