Spring 中静态变量,不能按照普通变量一样,进行注入和获取,需要特殊进行配置。
下面举一个采购网前台的例子。
l 为静态变量设置静态方法。
Java 类定义
ApplicationProperties .java
public class ApplicationProperties {
private static Properties prop ;
public static void setProp (Properties properties) {
prop = properties;
}
public static String getProproperty(String key){
return prop .getProperty(key);
}
}
l 静态变量注入
XML 配置如下:
ApplicationContext-base.xml
< bean id = "applicationProperties" class = "cn.bidlink.eb.common.ApplicationProperties" >
</ bean >
< bean id = "applicationPropertiesInjector" class = "org.springframework.beans.factory.config.MethodInvokingFactoryBean" >
< property name = "staticMethod" > < value > cn.bidlink.eb.common.ApplicationProperties.setProp </ value >
</ property >
< property name = "arguments" >
< ref bean = "propertyBean" />
</ property >
</ bean >
l 静态变量获取
Spring 2.0 之前:
1. <bean id= "..." class = "..." >
2. <property name= " prop " >
3. <bean id= " cn.binlink.eb.common.ApplicationProperties.prop "
4. class = "org.springframework.beans.factory.config.FieldRetrievingFactoryBean" />
5. </property>
6. </bean>
Spring 2.0 之后:
1. <bean id= "..." class = "..." >
2. <property name= " prop " >
3. <util:constant static -field= " cn.binlink.eb.common.ApplicationProperties.prop " />
4. </property>
5. </bean>