春季启动2:ConverterNotFoundException:未找到能够从类型[java.time.ZonedDateTime]转换为类型[java.util.Date]的转换器

时间:2018-10-19 08:50:58

标签: java spring date spring-boot zoneddatetime

我使用spring-boot 2。

我是Junit测试(@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());
}

我有这个Converter:

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());
    }
}

我有这个Spring配置:

@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;
    }

}

我还有其他Spring配置:

@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]

为什么对于MongoDB来说,WebMvc部分没有考虑我的转换器?

编辑:

我使用Spring Data 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;
}

修改n°2:

我尝试使用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 个答案:

答案 0 :(得分:0)

MyWebMvcConfigurer扩展了WebMvcConfigurerAdapter,该版本自Spring 5.0起已被弃用。相反,您应该实现WebMvcConfigurer接口:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // ...
    }
}

有关更多信息,请参见Type Conversion文档。 还要注意不同的注释!

答案 1 :(得分:0)

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

@Document批注+ ZonedDateTime是问题所在。该解决方案如建议的那样:一个“转换器”,而不是一个Spring Converter / HandlerMapping。您需要将其添加到MongoTemplate。

在此处检查以供参考。有很多-只是谷歌为:MongoDB ZonedDateTime。

ZonedDateTime with MongoDB