Java 默认值为@value时的持续时间
我需要为java.time.Duration类型的实例变量指定默认值 我传递的默认值被读取为字符串,导致IllegalStateException 我的班级Java 默认值为@value时的持续时间,java,spring,spring-boot,Java,Spring,Spring Boot,我需要为java.time.Duration类型的实例变量指定默认值 我传递的默认值被读取为字符串,导致IllegalStateException 我的班级 public class Test { @Value("${kafka.consumer.commit.interval:5s}") private Duration commitInterval; . . . } 例外情况: Unsatisfied dependency expressed through f
public class Test {
@Value("${kafka.consumer.commit.interval:5s}")
private Duration commitInterval;
.
.
.
}
例外情况:
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
您可以直接使用SpEL表达式调用
Duration
类的工厂方法:
@Value("${kafka.consumer.commit.interval:#{T(java.time.Duration).of(5, T(java.time.temporal.ChronoUnit).SECONDS)}}")
private Duration commitInterval;
但是,正如您所看到的,它有点冗长。
或者更简单的版本,如评论中提到的OP:
@Value("${kafka.consumer.commit.interval:#{T(java.time.Duration).ofSeconds(5)}}")
private Duration commitInterval;
您可以直接使用SpEL表达式调用
Duration
类的工厂方法:
@Value("${kafka.consumer.commit.interval:#{T(java.time.Duration).of(5, T(java.time.temporal.ChronoUnit).SECONDS)}}")
private Duration commitInterval;
但是,正如您所看到的,它有点冗长。
或者更简单的版本,如评论中提到的OP:
@Value("${kafka.consumer.commit.interval:#{T(java.time.Duration).ofSeconds(5)}}")
private Duration commitInterval;
我认为您必须创建一个自定义属性编辑器支持。这就解释了:或者您可以使用Spring EL并使用Duration.of(commitInterval,TemporalUnit)或其他工厂方法。项目有哪些依赖项?@AdityaRewari,哦,我知道了,您的类没有用
@Component
或@Service
注释。因此没有任何Springbean的定义。因此,spring不是创建实例的人,您可以这样做。为了避免再次显示此错误,请尝试使用final属性从构造函数初始化它。它将帮助您了解您的bean创建是否进展顺利@AdityArewari我认为您必须创建一个自定义属性编辑器支持。这就解释了:或者您可以使用Spring EL并使用Duration.of(commitInterval,TemporalUnit)或其他工厂方法。项目有哪些依赖项?@AdityaRewari,哦,我知道了,您的类没有用@Component
或@Service
注释。因此没有任何Springbean的定义。因此,spring不是创建实例的人,您可以这样做。为了避免再次显示此错误,请尝试使用final属性从构造函数初始化它。它将帮助您了解您的bean创建是否进展顺利@AdityaRewari@Value(${kafka.consumer.commit.interval:#{T(java.time.Duration).ofSeconds(5)}”)
更简单的版本!:)@Value(${kafka.consumer.commit.interval:#{T(java.time.Duration).ofSeconds(5)}”)
一个更简单的版本!:)