小编典典

如何使Spring注入值进入静态场

spring

我知道这看起来像是一个先前提出的问题,但是我在这里面临另一个问题。

我有一个只有静态方法的实用程序类。我不会,也不会从中获得实例。

public class Utils{
    private static Properties dataBaseAttr;
    public static void methodA(){

    }

    public static void methodB(){

    }
}

现在我需要Spring用数据库属性Properties填充dataBaseAttr.Spring的配置是:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

<util:properties id="dataBaseAttr"
        location="file:#{classPathVariable.path}/dataBaseAttr.properties" />
</beans>

我已经在其他bean中做到了,但是此类(Utils)中的问题不是bean,如果我将其变成bean,则没有任何变化,但我仍然无法使用变量,因为该类不会被实例化并且总是变量等于null。


阅读 555

收藏
2020-04-11

共1个答案

小编典典

你有两种可能性:

  1. 静态属性/字段的非静态设置器;
  2. 通过org.springframework.beans.factory.config.MethodInvokingFactoryBean调用静态的制定者。
    在第一个选项中,你有一个带有常规setter的bean,但设置实例属性的是设置静态属性/字段。
public void setTheProperty(Object value) {
    foo.bar.Class.STATIC_VALUE = value;
}

但是为了做到这一点,你需要有一个将实例化此setter的bean实例(它更像一个变通方法)。

在第二种情况下,将执行以下操作:

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Class.setTheProperty"/>
    <property name="arguments">
        <list>
            <ref bean="theProperty"/>
        </list>
   </property>
</bean>

根据你的情况,你将在Utils课程上添加一个新的二传手:

public static setDataBaseAttr(Properties p)

并且在你的上下文中,你将使用上述示例性方法对其进行配置,大致类似:

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Utils.setDataBaseAttr"/>
    <property name="arguments">
        <list>
            <ref bean="dataBaseAttr"/>
        </list>
   </property>
</bean>
2020-04-11