【发布时间】:2016-08-10 16:28:38
【问题描述】:
在使用 Web MVC 开发 REST API 的 Spring Boot 应用程序中。一切正常。
为了将 String 转换为 ZonedDateTime,我创建了这个注释:
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface DateTimeFormatter {
}
这是自定义格式化程序:
public class ZonedDateTimeFormatter implements Formatter<ZonedDateTime> {
@Override
public String print(ZonedDateTime zoneddateTime, Locale locale) {
return .....
}
@Override
public ZonedDateTime parse(String text, Locale locale) throws ParseException {
return ......
}
}
这就是我添加格式化程序的方式,
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
@Configuration
public class IndexApplication extends SpringBootServletInitializer {
...
@Configuration
public static class ApplicationFormatterRegistrar extends WebMvcConfigurerAdapter implements FeignFormatterRegistrar {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatterForFieldAnnotation(new ZonedDateTimeAnnotationFormatterFactory());
}
@Override
public void registerFormatters(FormatterRegistry registry) {
registry.addFormatter(new ZonedDateTimeFormatter());
}
}
}
这就是我测试应用程序的方式(Spring mockmvc):
this.mockMvc = MockMvcBuilders.standaloneSetup(indexResource).build();
......
@Test
public void should_accept_valid_request() throws Exception {
when(service.getSomething(id, begin, end)).thenReturn(somevalue);
mockMvc.perform(
get("/index/{id}", 1)
.param("start", "2011-12-03T10:15:30")
.param("end", "2011-12-03T10:15:30")
).andExpect(status().isOk());
}
一切正常。问题是我想将自定义注释 @DateTimeFormatter 放在所有项目的公共 jar 中,在这种情况下 Spring MVC 不注册自定义转换器!我不明白为什么。
您的帮助将不胜感激。
【问题讨论】:
-
我能在github上看到代码吗?
标签: java spring spring-mvc spring-boot