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
解
要解决此问题,请创建一个“无静态设置器”以为静态变量分配注入值。 例如 :
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"
翻译自: https://mkyong.com/spring/spring-inject-a-value-into-static-variables/