An alternative to @Value annotation in static function

22,886

Solution 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.

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

Share:
22,886
Sanghyun Lee
Author by

Sanghyun Lee

Updated on July 09, 2022

Comments

  • Sanghyun Lee
    Sanghyun Lee almost 2 years

    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?

  • Sanghyun Lee
    Sanghyun Lee almost 13 years
    Can I access to properties value from static function in non-spring way?
  • Ralph
    Ralph almost 13 years
    @Sangdol: via the application context: sujitpal.blogspot.com/2007/03/…
  • membersound
    membersound over 7 years
    I tried this and it does not work (of course, because you construct the ConfigUtil using the new operator.
  • Gaetano Piazzolla
    Gaetano Piazzolla about 6 years
    True, it does not work even if it's annotated with @configurable.
  • Adriaan Koster
    Adriaan Koster over 4 years
    Upvoted for food solution to OP's question (given that static context is required). However I would not call this a 'trick' but mention the pattern's name: Singleton: en.wikipedia.org/wiki/Singleton_pattern
  • jack3694078
    jack3694078 over 4 years
    NullPointException is thrown because INSTANCE is null when I test this code. I'm suspecting ConfigUtil needs to be injected itself for @PostConstruct to work (which kinds of defeat the purpose of using static methods)
  • Vikki
    Vikki almost 4 years
    @jack3694078 I also got NullPointException