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"