我有应随机生成的应用程序属性 APP_ID
(UUID),并且对于整个 Spring Boot 应用程序应具有相同的值。
我所做的如下:我在 application.properties
文件中定义了 APP_ID=${random.uuid}
。
UUID 已成功创建,但是对于每个属性引用 @Value("${APP_ID}")
,我将获得不同的 UUID。
示例:在类 Foo
中,我想使用 appId
:
@Value("${APP_ID}")
private String appId;
在 Bar
类中,我也想使用 appId
:
@Value("${APP_ID}")
private String appId;
但是,Bar
中的appId
始终与Foo
中的appId
不同。
我已阅读此 thread这种行为是正确的。
怎样才能始终获得相同的 APP_ID
?
最佳答案
一种方法(如 wilkinsoa 中的 this thread 所建议)是“将单个随机值绑定(bind)到一个 @ConfigurationProperties
注释的 bean 中,然后使用该 bean 来配置其他任何东西需要相同的值。”
这会产生一个 application.properties
文件:
app.id=${random.uuid}
配置属性文件是:
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String id;
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
}
使用id的类:
@Component
public class DoStuff {
private AppProperties appProperties;
@Autowired
public DoStuff(AppProperties appProperties) {
this.appProperties = appProperties;
}
}
关于java - Spring 启动配置 : how to return always same random value when referenced?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49274032/