An alternative to @Value annotation in static function
It's not possible to use @Value
on a static variable.
@Value("${some.value}")
static private int someValue;
static public void useValue() {
System.out.println(someValue);
}
When I do this, 0
is printed. So 开发者_JS百科what is a good alternative to this?
Spring inject noting in static field (by default).
So you have two alternatives:
- (the better one) make the field non static
- (the ugly hack) add an none static setter which writes in the static field, and add the
@Value
annotation to the setter.
- and then there is the trick with the MethodInvokingFactoryBean -- this example is for autowired fiels, but I guess you can adapt it for
@Value
too
Use this simple trick to achieve what you want (way better than having the value injected into non-static setters and writing so a static field - as suggested in the accepted answer):
@Service
public class ConfigUtil {
public static ConfigUtil INSTANCE;
@Value("${some.value})
private String value;
@PostConstruct
public void init() {
INSTANCE = this;
}
public String getValue() {
return value;
}
}
Use like:
ConfigUtil.INSTANCE.getValue();
To prevent ever repeating injections of the same value making a field non-static in a class that gets instantiated very often, I preferred to create a simple Singleton ConfigUtil as a workaround:
package de.agitos.app.util;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
/**
* Helper class to get injected configuration values from static methods
*
* @author Florian Sager
*
*/
@Configurable
public class ConfigUtil {
private static ConfigUtil instance = new ConfigUtil();
public static ConfigUtil getInstance() {
return instance;
}
private @Value("${my.value1}") Integer value1;
public Integer getValue1() {
return value1;
}
}
Inside the class I tried to inject the value first as a static Integer:
private static Integer value1 = ConfigUtil.getInstance().getValue1();
The following codes work for me,
public class MappingUtils {
private static String productTypeList;
@Value("${productType-list}")
public void setProductTypeList(String productTypeList) {
MappingUtils.getProductTypeList = productTypeList;
}
}
let's say you have a class name called config so you initialize the static variable. May be one can use the below approach for the same
class Config
{
private static int someValue;
private Config(@Value("${some.value}") int valueDuringInitialization)//private constructor
{
Config.someValue=valueDuringInitialization;
}
static public void useValue() {
System.out.println(someValue);
}
}
精彩评论