[英]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
@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) 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.