使用静态方法克服上下文不可用

时间:2017-05-10 23:03:05

标签: java spring dependency-injection static-methods

我正在使用Axis2的遗留SOAP应用程序做一些工作。我想介绍一些基本的Spring injection。该应用程序具有Axis2服务配置,指定:

<ramp:RampartConfig xmlns:ramp="http://ws.apache.org/rampart/policy">
    <ramp:timestampTTL>300</ramp:timestampTTL>  
    <ramp:timestampMaxSkew>300</ramp:timestampMaxSkew>
    <ramp:user>service</ramp:user>
    <ramp:encryptionUser>useReqSigCert</ramp:encryptionUser>
    <ramp:passwordCallbackClass>
        com.myapp.SomeCallbackHandler
    </ramp:passwordCallbackClass>

Axis2使用反射实例化 SomeCallbackHandler (最终是新的,与Spring的工作方式发生冲突),在该类中我想注入一个通过ContextLoaderListener加载的bean。我尝试使用axis2-spring,虽然似乎有一种方法来桥接这两个并将Spring上下文bean注入到Axis2服务类中,但问题是SomeCallbackHandler不是服务。所以我找不到一种将它与Spring上下文联系起来的正确方法。

我解决的方法是创建一个包装类,其中包含我想要注入的变量并使其静态可用:

public class ContextCarrier {

    //I get vomit in my throat when I have to use static
    private static MyConfig config;

    public void setConfig(MyConfig _config) {
        config = _config;
    }

    //I really hate this but it works
    public static MyConfig getConfig() {
        return config;
    }
}

在我的context.xml

<bean id="hackBean" class="my.app.ContextCarrier">
    <property name="config" ref="serverConfig" />
</bean>

<bean id="serverConfig" class="my.app.MyConfig">
    <property name="connection" ref="cxnBean" />
</bean>

SomeCallbackHandler(Apache Rampart&#password.sallbackClass实现):

public void handle(Callback[] callbacks) throws IOException,
            UnsupportedCallbackException {

            ...
            MyConfig myConfig = ContextCarrier.getConfig();
            ...

我的问题是,通过静态方法克服Spring上下文不可访问性的黑客有多糟糕?我真的希望永远不必在任何地方使用静态方法,除了可能的常量和工厂,因为它们违背了面向对象的目的。

相关:

0 个答案:

没有答案
相关问题