Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 589
Sanghyun Lee Avatar asked Aug 01 '11 10:08

Sanghyun Lee


1 Answers

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

like image 159
membersound Avatar answered Sep 30 '22 20:09

membersound