Adi*_*ari 3 java spring spring-boot
我需要为java.time.Duration类型的实例变量指定默认值
我传递的默认值被读取为字符串,导致 IllegalStateException
我的课
public class Test {
@Value("${kafka.consumer.commit.interval:5s}")
private Duration commitInterval;
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
例外:
Unsatisfied dependency expressed through field 'commitInterval';
nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.time.Duration';
nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.time.Duration': no matching editors or conversion strategy found
Run Code Online (Sandbox Code Playgroud)
您可以直接使用 SpEL 表达式来调用Duration类的工厂方法:
@Value("${kafka.consumer.commit.interval:#{T(java.time.Duration).of(5, T(java.time.temporal.ChronoUnit).SECONDS)}}")
private Duration commitInterval;
Run Code Online (Sandbox Code Playgroud)
然而正如你所看到的,它有点冗长。或者像评论中提到的OP更简单的版本:
@Value("${kafka.consumer.commit.interval:#{T(java.time.Duration).ofSeconds(5)}}")
private Duration commitInterval;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4138 次 |
| 最近记录: |