Spring靜態變數注入
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>