【问题标题】:Spring custom formatter in an external jar外部 jar 中的 Spring 自定义格式化程序
【发布时间】: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


【解决方案1】:

我可以通过这种方式注册自定义格式化程序:

FormattingConversionService conversionService = new FormattingConversionService();
conversionService.addFormatterForFieldAnnotation(new ZonedDateTimeAnnotationFormatterFactory());
this.mockMvc = MockMvcBuilders.standaloneSetup(indexResource).setConversionService(conversionService).build();

即使格式化程序已经在配置中注册,我也不知道为什么要为我的测试执行此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2017-08-03
    • 2016-11-30
    相关资源
    最近更新 更多