写在前面
在SpringBoot的项目中,当在配置文件中配置的值为yes/no或者on/off时,在SpringBoot内部解析时会将yes/no,on/off解析为true/false。
参数配置
参数配置如下:
spring:
application:
# 应用名称
name: damp-drools2
drools:
use-redis: yes # 解析为true
path: classpath:com/tiantu/damp/**/*.drl
mode: stream
auto-update: no # 解析为false
update: 60
listener: on # 解析为true
verify: off # 解析为false
问题分析
根据SpringBoot启动时加载配置文件的原理,查看源代码发现:
public class SafeConstructor extends BaseConstructor {
public SafeConstructor(LoaderOptions loadingConfig) {
super(loadingConfig);
this.yamlConstructors.put(Tag.NULL, new SafeConstructor.ConstructYamlNull());
this.yamlConstructors.put(Tag.BOOL, new SafeConstructor.ConstructYamlBool());
}
public class ConstructYamlBool extends AbstractConstruct {
public ConstructYamlBool() {
}
public Object construct(Node node) {
String val = SafeConstructor.this.constructScalar((ScalarNode)node);
return SafeConstructor.BOOL_VALUES.get(val.toLowerCase());
}
}
static {
BOOL_VALUES.put("yes", Boolean.TRUE);
BOOL_VALUES.put("no", Boolean.FALSE);
BOOL_VALUES.put("true", Boolean.TRUE);
BOOL_VALUES.put("false", Boolean.FALSE);
BOOL_VALUES.put("on", Boolean.TRUE);
BOOL_VALUES.put("off", Boolean.FALSE);
RADIX_MAX = new int[17][2];
int[] radixList = new int[]{2, 8, 10, 16};
int[] var1 = radixList;
int var2 = radixList.length;
for(int var3 = 0; var3 < var2; ++var3) {
int radix = var1[var3];
RADIX_MAX[radix] = new int[]{maxLen(2147483647, radix), maxLen(9223372036854775807L, radix)};
}
TIMESTAMP_REGEXP = Pattern.compile("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:(?:[Tt]|[ \t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \t]*(?:Z|([-+][0-9][0-9]?)(?::([0-9][0-9])?)?))?)?$");
YMD_REGEXP = Pattern.compile("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)$");
}
}
解决方案
如果在配置中参数必须使用yes/no,on/off且期望在代码中读取的值也为yes/no,on/off,可以加上单引号或者双引号。
spring:
application:
# 应用名称
name: damp-drools2
drools:
use-redis: 'yes' # 解析为yes
path: classpath:com/tiantu/damp/**/*.drl
mode: stream
auto-update: 'no' # 解析为no
update: 60
listener: "on" # 解析为on
verify: "off" # 解析为off