SpringBoot配置文件日期属性转换实例

本文介绍如何在SpringBoot中正确配置日期格式,并通过Java代码读取。通过在配置文件设置日期,结合使用ConversionService和DateTimeFormatterRegistrar确保日期能被正确转换。

本文展示一下如何在springboot中配置文件指定日期,在java里头用LocalDateTime接收。

配置文件

startTime=2017-09-15 10:15:00

value注入

    @Value("${startTime}")
    Date startTime;

正常情况,这样注入会报错

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoController': Unsatisfied dependency expressed through field 'startTime'; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Date': no matching editors or conversion strategy found
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.5.RELEASE.jar:1.5.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.5.RELEASE.jar:1.5.5.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.5.RELEASE.jar:1.5.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.5.RELEASE.jar:1.5.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.5.RELEASE.jar:1.5.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.5.RELEASE.jar:1.5.5.RELEASE]

解决

配置ConversionService

    @Bean
    public ConversionService conversionService() {
        FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean();
        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setUseIsoFormat(true);
        factory.setFormatterRegistrars(Collections.singleton(registrar));
        factory.afterPropertiesSet();
        return factory.getObject();
    }

指定格式

    @Value("${startTime}")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    Date startTime;

这样就大功告成了

doc

### 配置Spring Boot全局消息转换器 在Spring Boot应用程序中,可以通过自定义`HttpMessageConverters`来实现全局的消息转换功能。这可以用于解决日期字段的时间格式化以及长日志字符串的序列化和反序列化问题。 #### 自定义全局消息转换器 为了支持时间字段的正确序列化与反序列化,通常需要配置Jackson库的相关属性。以下是具体方法: 1. **创建一个配置类** 创建一个新的配置类并注册自定义的`ObjectMapper`实例。此实例将被注入到所有的`MappingJackson2HttpMessageConverter`中。 ```java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import java.util.List; @Configuration public class WebConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); // 添加JSR310模块以支持Java 8日期/时间API mapper.registerModule(new JavaTimeModule()); // 设置默认日期格式 mapper.findAndRegisterModules(); // 注册其他可用模块 return mapper; } @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) { return new MappingJackson2HttpMessageConverter(objectMapper); } @Bean public HttpMessageConverters customConverters(MappingJackson2HttpMessageConverter converter) { return new HttpMessageConverters(converter); } } ``` 上述代码片段展示了如何通过`ObjectMapper`设置日期格式,并将其应用于整个应用中的JSON序列化过程[^4]。 2. **调整Couchbase视图超时设置** 如果项目涉及Couchbase数据库操作,则需注意其环境变量配置可能影响性能表现。例如,在引用中提到的`spring.couchbase.env.timeouts.view=7500`表示常规视图查询的最大等待时间为7500毫秒[^1]。因此建议合理优化这些参数以匹配实际业务需求。 3. **处理中文乱码问题** 当遇到表单提交导致的编码错误时(如引用所描述的情况),应确认服务器端字符集是否已正确定义为UTF-8。可以在启动脚本或者application.properties文件里加入如下设定项[^3]: ```properties server.servlet.encoding.charset=UTF-8 server.servlet.encoding.enabled=true server.servlet.encoding.force=true ``` 以上措施能够有效防止因编码不一致而引发的数据传输异常现象。 4. **针对长日志串做特殊处理** 对于特别冗长的日志记录内容,默认情况下可能会超出某些框架预设长度限制从而造成截断等问题。此时可通过扩展JsonSerializer来自定义逻辑: ```java import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import java.io.IOException; public class LongLogSerializer extends StdSerializer<String> { protected LongLogSerializer(Class<String> t) { super(t); } @Override public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (value != null && value.length() > 1000){ String truncatedValue = value.substring(0,997)+"..."; gen.writeString(truncatedValue); }else{ gen.writeString(value); } } } ``` 接着把此类绑定至特定字段上即可完成定制化的输出效果[^5]。 ### 总结 综上所述,通过引入自定义的对象映射器、适配器以及其他必要的组件,完全可以满足关于日期解析精度控制及复杂数据结构呈现的需求。与此同时也要兼顾第三方服务接口调用效率等因素综合考量最佳实践方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值