英文:
Creating a static Settings class from inside that class but non static fields not updating
问题
所以,我有一个项目的设置文件,看起来像下面这样。
@Component
public class Settings {
private transient final BuildProperties buildProperties;
private static Settings settingsStatic;
private String TF_VERSION = "EMPTY";
private static final Logger LOGGER = LoggerFactory.getLogger(Settings.class);
private final String REPO_TF_SUBSCRIPTION =
"git::https://github.xxx.com/xxxxx/xxxx//subscription?ref=" + TF_VERSION);
@Autowired
private Settings(BuildProperties buildProperties) {
this.buildProperties = buildProperties;
TF_VERSION = this.buildProperties.getVersion();
LOGGER.info("TF_VERSION is {}", this.buildProperties.getVersion());
settingsStatic = this;
}
public static String getTerraformSubscriptionRepository() {
return settingsStatic.REPO_TF_SUBSCRIPTION;
}
}
Logger输出了正确的版本,即3.4.0,但当我调用getTerraformSubscriptionRepository()时,它返回的是TF_VERSION=empty,而不是我预期的3.4.0。
有人能解释一下为什么会发生这种情况吗?
英文:
So I have settings file for my project that looks like the following.
@Component
public class Settings {
private transient final BuildProperties buildProperties;
private static Settings settingsStatic;
private String TF_VERSION = "EMPTY";
private static final Logger LOGGER = LoggerFactory.getLogger(Settings.class);
private final String REPO_TF_SUBSCRIPTION =
"git::https://github.xxx.com/xxxxx/xxxx//subscription?ref=" + TF_VERSION);
@Autowired
private Settings(BuildProperties buildProperties) {
this.buildProperties = buildProperties;
TF_VERSION = this.buildProperties.getVersion();
LOGGER.info("TF_VERSION is {}", this.buildProperties.getVersion());
settingsStatic = this;
}
public static String getTerraformSubscriptionRepository() {
return settingsStatic.REPO_TF_SUBSCRIPTION;
}
}
The Logger outputs the correct version ie. 3.4.0, but when I call getTerraformSubscriptionRepository() it comes back with TF_VERSION=empty instead of what I expected, 3.4.0.
Can anyone explain to me why that would be happening.
答案1
得分: 1
以下是翻译好的部分:
你初始化REPO_TF_SUBSCRIPTION时使用了TF_VERSION = "EMPTY",但由于REPO_TF_SUBSCRIPTION是final的,所以你无法后续修改它,因此即使你修改TF_VERSION,它仍然是相同的对象。
英文:
private String TF_VERSION = "EMPTY";
private final String REPO_TF_SUBSCRIPTION =
"git::https://github.xxx.com/xxxxx/xxxx//subscription?ref=" + TF_VERSION);
You initialize REPO_TF_SUBSCRIPTION with TF_VERSION = "EMPTY", but because REPO_TF_SUBSCRIPTION is final, you can't modify it later, so it always be the same object, even if you modify TF_VERSION
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论