An alternative to @Value annotation in static function

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


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