Do variables initialized in the @PostConstruct method need to be declared as volatile in Spring Framework?

2.1k views Asked by At

I do some initialization in Spring singleton bean @PostConstruct method (simplified code):

@Component
public class Env {
    public String currentEnv;

    @PostConstruct
    public void init() {
        currentEnv = "dev";
    }
}

Should I worry about currentEnv visibility to other beans(other thread) and mark it volatile.

2

There are 2 answers

4
Huy Nguyen On
2
João Dias On

By default, a Spring-managed Bean defined with @Component is a Singleton. This means that if you inject Env into another Spring-managed Bean and given that currentEnv is public, this other Bean could access it.

I would suggest making currentEnv private and creating a getter for the property instead:

@Component
public class Env {
    private String currentEnv;

    @PostConstruct
    public void init() {
        currentEnv = "dev";
    }

    public String getCurrentEnv() {
        return currentEnv;
    }
}