Home > Net >  Do variables initialized in the @PostConstruct method need to be declared as volatile in Spring Fram
Do variables initialized in the @PostConstruct method need to be declared as volatile in Spring Fram

Time:12-11

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.

CodePudding user response:

No, I think it is not necessity.

Only one bean is responsible to initialize the variables and registered it in spring context. So the visibility is guaranteed.

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-postconstruct-and-predestroy-annotations

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.html

CodePudding user response:

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;
    }
}
  • Related