弹簧线静态类 [英] Spring Wire a Static Class

查看:77
本文介绍了弹簧线静态类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个遗留代码库,其中在Spring中未连接的类需要获取在中连接的 的类.我希望创建一个在启动时已连接的工厂类,然后可以调用getInstance()方法来获取一个连接对象.最好的方法是什么?

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>

无需修改FooFooFactory

这篇关于弹簧线静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆