Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无论如何,仅当@value出现解析错误时才设置默认值_Java_Spring_Config - Fatal编程技术网

Java 无论如何,仅当@value出现解析错误时才设置默认值

Java 无论如何,仅当@value出现解析错误时才设置默认值,java,spring,config,Java,Spring,Config,在Spring中,您可以使用@Value(${num:123}”)私有整数以插入值编号 显然,当配置文件中没有num字段时,默认值将起作用 但是,当存在格式错误时。Spring将抛出如下错误: 09:54:28.392 [main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization

在Spring中,您可以使用
@Value(${num:123}”)私有整数
以插入值编号

显然,当配置文件中没有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将使用默认值。

我想问的一个问题是,为什么配置文件中的值格式错误?配置文件应该是应用程序中的真实来源。如果您真的需要处理这种情况,解析字符串可能是最好的解决方案。我完全同意您的看法。然而,这不是我最初的代码。我只是想以这种方式重构它,以便通过代码审查。