SpringBoot - application.yml配置文件中yes/no,on/off在代码中读取的值为true/false

写在前面
在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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值