代码之家  ›  专栏  ›  技术社区  ›  Stéphane GRILLON

Spring boot 2:ConverterNotFoundException:找不到能够从类型转换的转换器[java.ZonedTime时间]键入[日期类型]

  •  0
  • Stéphane GRILLON  · 技术社区  · 6 年前

    @SpringBootTest ),我使用 org.springframework.test.web.servlet.MockMvc

    @Test
    @WithMockUser(roles = {"ADMIN"})
    public void testGetSearchByFoodIdWithAdmin() throws Exception {
        final ResultActions resultActions = mockMvc.perform(get(RESOURCE_URL + "/search/findByFooId?fooId=123"))
                    .andExpect(status().isOk());
    }
    

    我有一个转换器:

    public class ZonedDateTimeToDateConverter implements Converter<ZonedDateTime, Date> {
        @Override
        public Date convert(final ZonedDateTime source) {
            return source == null ? null : Date.from(source.toInstant());
        }
    }
    

    public class DateToZonedDateTimeConverter implements Converter<Date, ZonedDateTime> {
        @Override
        public ZonedDateTime convert(final Date source) {
            return source == null ? null : ofInstant(source.toInstant(), systemDefault());
        }
    }
    

    @Configuration
    @EnableMongoAuditing(dateTimeProviderRef = "dateTimeProvider")
    public class MongoConfiguration {
    
        @Autowired
        MongoDbFactory mongoDbFactory;
    
        @Bean
        public MongoCustomConversions customConversions() {
            List<Converter<?, ?>> converters = new ArrayList<>();
            converters.add(new DateToZonedDateTimeConverter());
            converters.add(new ZonedDateTimeToDateConverter());
            return new MongoCustomConversions(converters);
        }
    
        @Bean
        public MongoTemplate mongoTemplate() throws Exception {
            MappingMongoConverter converter = getDefaultMongoConverter();
            //converter.afterPropertiesSet();
            MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter);
            return mongoTemplate;
        }
    
        @Bean
        public MappingMongoConverter getDefaultMongoConverter() throws Exception {
            MappingMongoConverter converter = new MappingMongoConverter(
                    new DefaultDbRefResolver(mongoDbFactory), new MongoMappingContext());
            converter.setCustomConversions(customConversions());
            return converter;
        }
    
    }
    

    我有另一种弹簧配置:

    @Component
    public class MyWebMvcConfigurer extends WebMvcConfigurerAdapter {
    
        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.addConverter(new DateToZonedDateTimeConverter());
            registry.addConverter(new ZonedDateTimeToDateConverter());
        }
    
    }
    

    我有个错误:

    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.time.ZonedDateTime] to type [java.util.Date]
    

    我使用Spring数据Rest

    @RepositoryRestResource(collectionResourceRel = "foo", path = "foo")
    public interface FooRepository extends MongoRepository<Foo, String> {
    
        Foo findByFooId(@Param("fooId") String fooId);
    
    }
    

    我的 Foo 班级:

    @Document
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    @Data
    public class Foo {
    
        @Id
        private String keyid;
    
        @NotNull
        private String fooId;
    
        @CreatedDate
        @JsonProperty(access = JsonProperty.Access.READ_ONLY)
        private ZonedDateTime creationDate;
    
        @LastModifiedDate
        @JsonProperty(access = JsonProperty.Access.READ_ONLY)
        private ZonedDateTime updateDate;
    }
    

    CustomizedRestMvcConfiguration 实现了RepositoryRestConfigurer`但并不是我唯一的问题:

    @Configuration
    @EnableWebMvc
    public class CustomizedRestMvcConfiguration implements RepositoryRestConfigurer {
    
        @Bean
        public DateToZonedDateTimeConverter dateToZonedDateTimeConverter() {
            return new DateToZonedDateTimeConverter();
        }
    
        @Bean
        public ZonedDateTimeToDateConverter zonedDateTimeToDateConverter() {
            return new ZonedDateTimeToDateConverter();
        }
    
        @Override
        public void configureConversionService(ConfigurableConversionService conversionService) {
            conversionService.addConverter(dateToZonedDateTimeConverter());
            conversionService.addConverter(zonedDateTimeToDateConverter());
        }
    
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Stéphane GRILLON    6 年前

    MyWebMvcConfigurer 延伸 WebMvcConfigurerAdapter 已弃用 WebMvcConfigurer 接口:

    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
    
        @Override
        public void addFormatters(FormatterRegistry registry) {
            // ...
        }
    }
    

    看到了吗 Type Conversion 还要注意不同的注释!

        2
  •  0
  •   Kai    5 年前

    是的,sgrillon答案不起作用,因为问题不在Spring转换中,而是在MongoDB的Jackson-JSON转换器中。

    @文档注释+ZonedDateTime是个问题。解决方案正如sgrillion建议的那样:“converter”而不是Spring converter/handler映射。你需要把它添加到MongoTemplate。

    ZonedDateTime with MongoDB