Value参数创建LocalDate或LocalDateTime

Value参数创建LocalDate或LocalDateTime

本文介绍了Spring:从@Value参数创建LocalDate或LocalDateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在spring项目中,我想从@Autowire d构造函数参数创建一个LocalDate,其值在.properties文件中.我想做两件事:

In a spring project, I'd like to create a LocalDate from an @Autowired constructor parameter whose value is in a .properties file. Two things I'd like to do:

  1. 如果属性文件包含属性my.date,则应通过解析属性值来创建参数
  1. If the property file contains the property my.date, the parameter should be created by parsing the property value

设置属性后,以及使用以下命令时:

When the property is set, and when I use the following:

@DateTimeFormat(pattern = "yyyy-MM-dd") @Value("${my.date}") LocalDate myDate,
...

我收到此错误: java.lang.IllegalStateException:无法将类型"java.lang.String"的值转换为所需类型"java.time.LocalDate":找不到匹配的编辑器或转换策略

I get this error: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.time.LocalDate': no matching editors or conversion strategy found

我还使用iso = ...来使用具有相同结果的ISO日期.

I have also used the iso = ... to use an ISO date with the same result.

  1. 如果该属性不在属性文件中,则应使用LocalDate.now()
  2. 创建该参数
  1. If the property is not in the properties file, the parameter should be created using LocalDate.now()

我尝试使用默认值,例如:

I tried using a default value as such:

@Value("${my.date:#{T(java.time.LocalDate).now()}}") LocalDate myDate,
...

但是我遇到了同样的错误.

But I get the same error.

请原谅我对Spring的无知,但是如何在这里实现两个目标?

Forgive my ignorance with Spring, but how can I achieve the two objectives here?

推荐答案

我知道两种方法.一个对任何对象都是通用的-在自定义设置器上使用@Value注释

I know two ways. One is generic for any object - to use @Value annotation on custom setter

@Component
public class Example {

    private LocalDate localDate;

    @Value("${property.name}")
    private void setLocalDate(String localDateStr) {
        if (localDateStr != null && !localDateStr.isEmpty()) {
            localDate = LocalDate.parse(localDateStr);
        }
    }
}

第二个是LocalDate/LocalDateTime

The second is for LocalDate/LocalDateTime

public class Example {
    @Value("#{T(java.time.LocalDate).parse('${property.name}')}")
    private LocalDate localDate;
}

样本属性:

property.name=2018-06-20

这篇关于Spring:从@Value参数创建LocalDate或LocalDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 19:02