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.
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;
}
}