首页 > 解决方案 > 无论如何,仅当 @value 存在解析错误时才设置默认值

问题描述

在 Spring 中,您可以使用@Value("${num:123}") private int number;注入值编号。

显然,当配置文件中没有 num 字段时,默认值将起作用。

但是,当有一个格式错误的时候。Spring 会抛出如下错误:

09:54:28.392 [main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: 
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'valuesApp': Unsatisfied dependency expressed through field 'number'; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "string"

我知道您可以将值注入类型设为字符串,然后手动将其转换为整数类型(可以捕获错误等)。但是,有没有更优雅的方式来处理这样的案例?这样Spring将在配置文件格式错误的情况下使用默认值。

标签: javaspringconfig

解决方案


推荐阅读