Spring – Inject value into static variables

Spring doesn’t allow to inject value into static variables, for example:


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; public class GlobalValue { public static String DATABASE;


}

If you print out the GlobalValue.DATABASE, a null will be displayed.

 GlobalValue.DATABASE = null

Solution

To fix it, create a “none static setter” to assign the injected value for the static variable. For example :


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; public class GlobalValue { public static String DATABASE; public void setDatabase(String db) {
        DATABASE = db;
    }

}

Output

 GlobalValue.DATABASE = "mongodb database name"

首页 - Wiki
Copyright © 2011-2026 iteam. Current version is 2.154.0. UTC+08:00, 2026-02-26 02:30
浙ICP备14020137号-1 $访客地图$