Spring Inject value into static variables
By:Roy.LiuLast updated:2019-08-17
Spring doesn’t allow to inject value into static variables, for example:
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class GlobalValue { @Value("${mongodb.db}") 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; @Component public class GlobalValue { public static String DATABASE; @Value("${mongodb.db}") public void setDatabase(String db) { DATABASE = db;
Output
GlobalValue.DATABASE = "mongodb database name"
From:一号门
COMMENTS