java - 无论如何,仅当 @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将在配置文件格式错误的情况下使用默认值。
解决方案
推荐阅读
- android-studio - Android Studio 的播放按钮未启用
- javascript - 仅自动滚动子组件,而不是父组件
- r - R中的字符串替换不正确
- ios - 使用 IOS 13 在 Xamarin.iOS 上向右滑动不会动画效果
- c# - Entity Framework Core 3 - 具有来自存储过程的一些字段的模型
- c# - OfType() 还是?
- javascript - IE Uncaught ReferenceError: jQ is not defined, but works in Chrome
- c# - C# 异步任务不会继续
- python - 如何使用 x/y/r 像素坐标裁剪图像?
- django - 使用 Django ORM 对它们的 FK 进行额外过滤,使用由多个列连接的不同模型的值更新对象