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

解决办法

为了解决此类问题,需要创建一个“none static 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"

 

posted @ 2019-03-14 16:20  XLimp  阅读(601)  评论(0编辑  收藏  举报