我知道这可能看起来像以前提出的问题,但我在这里遇到了不同的问题。
我有一个只有静态方法的实用程序类。我没有,我也不会从中获取实例。
public class Utils{
private static Properties dataBaseAttr;
public static void methodA(){
}
public static void methodB(){
}
}
现在我需要 Spring 用数据库属性 Properties.Spring 配置填充 dataBaseAttr:
<?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。
最佳答案
你有两种可能:
- 静态属性/字段的非静态 setter ;
- 使用
org.springframework.beans.factory.config.MethodInvokingFactoryBean
调用静态 setter 。
在第一个选项中,您有一个带有常规 setter 的 bean,但您设置的是静态属性/字段,而不是设置实例属性。
public void setTheProperty(Object value) {
foo.bar.Class.STATIC_VALUE = value;
}
但为了做到这一点,你需要一个 bean 的实例来公开这个 setter(它更像是一个解决方法)。
在第二种情况下,将按如下方式完成:
<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
类上添加一个新的 setter :
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>
关于java - 如何使 Spring 将值注入(inject)静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11324372/