![](/img/trans.png)
[英]Do variables initialized in the override ApplicationContextAware.setApplicationContext method need to be declared as volatile in Spring Framework?
[英]Do variables initialized in the @PostConstruct method need to be declared as volatile in Spring Framework?
我在 Spring singleton bean @PostConstruct 方法(简化代码)中做了一些初始化:
@Component
public class Env {
public String currentEnv;
@PostConstruct
public void init() {
currentEnv = "dev";
}
}
我是否应该担心 currentEnv 对其他 bean(其他线程)的可见性并将其标记为 volatile。
不,我认为这不是必需品。
只有一个 bean 负责初始化变量并将其注册到 spring 上下文中。 所以能见度是有保证的。
默认情况下,使用@Component
定义的 Spring 管理的 Bean 是 Singleton。 这意味着如果您将Env
注入到另一个 Spring 管理的 Bean 中并且假设currentEnv
是公共的,那么另一个 Bean 可以访问它。
我建议将currentEnv
私有并为该属性创建一个 getter:
@Component
public class Env {
private String currentEnv;
@PostConstruct
public void init() {
currentEnv = "dev";
}
public String getCurrentEnv() {
return currentEnv;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.