在我的 application.properties 文件中,我有以下由连接 3 个属性组成的属性:
eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:}
我的意图是,当变量属性未初始化时,eureka.instance.appname 应通过连接变量属性的默认空字符串来形成,以便该值将为 ${spring.application.name}${spring .profiles.active} 单独。
但是如果我按照上面指定的格式定义它,最终的字符串将无法正确形成。我找不到将空字符串指定为变体默认值的方法。 当我使用 ${variant:''} 时,当 spring.application.name 是 SERVICE 且 spring.profiles.active 是 DEV 并且变量未分配值时,选择默认值 ' ,我得到一个 eureka.instance.appname作为 SERVICEDEV''。
到目前为止我尝试过的:
eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:}
不工作并且可能崩溃。
eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:''}
给出 SERVICEDEV'',其中 spring.application.name 是 SERVICE,spring.profiles.active 是 DEV,并且变量未分配值
最佳答案
eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:}
这对我有用。
其他方式:您可以让您的PropertySourcesPlaceholderConfigurer
检查变体的值。如果为 null 则可以将其更改为空字符串。
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer() {
@Override
public void setEnvironment(Environment environment) {
if (environment instanceof ConfigurableEnvironment && environment.getProperty("variant") == null) {
ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
env.getPropertySources().addLast(new MapPropertySource("Public key default", Collections.singletonMap("variant", "")));
}
super.setEnvironment(environment);
}
};
}
关于spring - 使用空字符串作为属性的默认值,以便可以将其与其他字符串连接以形成值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56565097/