An alternative to @Value annotation in static func

2019-04-24 23:21发布

问题:

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 what is a good alternative to this?

回答1:

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


回答2:

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();



回答3:

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();