spring-如何给静态变量注入值
spring 不允许/不支持把值注入到静态变量中,如:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GlobalValue {
@Value("${mongodb.db}")
public static String DATABASE;
}
如果你获取GlobalValue.DATABASE,会得到null
GlobalValue.DATABASE = null
那我们如何解决这个问题呢。
好在spring支持set方法注入,我们可以利用非静态setter 方法注入静态变量。如:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GlobalValue {
public static String DATABASE;
@Value("${mongodb.db}")
public void setDatabase(String db) {
DATABASE = db;
}
}
输出:
GlobalValue.DATABASE = "mongodb database name"
原文:http://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/