弹簧线静态类 [英] Spring Wire a Static Class
问题描述
我正在处理一个遗留代码库,其中在Spring中未连接的类需要获取在
I'm dealing with a legacy code base where a class which is not wired up in spring needs to obtain a class that is wired up in spring. I was hoping to create a factory class that was wired up on startup and then I could just call the getInstance() method to obtain a wired up object. What is the best way to go about this?
示例:
public class LegacyA {
public void doSomething() {
...
Foo foo = FooFactory.getInstance();
...
}
}
public class FooFactory {
private static Foo foo;
public static Foo getInstance() {
if (foo == null) throw new IllegalStateException();
return foo;
}
}
我需要在启动时连接FooFactory,以便LegacyA可以简单地调用getInstance(),以便它返回Foo的实例(这也是在应用程序上下文中定义的bean).
I need FooFactory to be wired up on startup so that LegacyA can simply call getInstance() so that it returns an instance of Foo (which is also a bean defined in the application context).
<bean id="legacyA" class="LegacyA"/>
<bean id="foo" class="Foo"/>
<!-- I need this bean to be injected with foo so that the FooFactory can return a foo -->
<bean id="fooFactory" class="FooFactory"/>
我不得不重新整理我的示例,因为我自己的脑袋有点困惑...
I had to re-work my example a bit as I got it a bit confuzzled in my own head...
推荐答案
像这样使用静态变量确实违背了Spring IoC的原则,但是如果您真的拥有可以使用它们,那么我建议编写一个简单的Spring钩子,该钩子将Foo
并注入到FooFactory
中,例如
Using statics like this really goes against the grain of Spring IoC, but if you really have to use them, then I would suggest writing a simple Spring hook which takes the Foo
and injects it into the FooFactory
, e.g.
public class FooFactoryProcessor implements InitializingBean {
private Foo foo;
public void setFoo(Foo foo) {
this.foo = foo;
}
public void afterPropertiesSet() throws Exception {
Foofactory.setFoo(foo);
}
}
在您的XML中:
<bean id="foo" class="Foo"/>
<bean class="FooFactoryProcessor">
<property name="foo" ref="foo"/>
</bean>
无需修改Foo
或FooFactory
这篇关于弹簧线静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!