首页 文章

外部jar中的Spring自定义格式化程序

提问于
浏览
0

在使用Web MVC开发REST API的Spring启动应用程序中 . 一切正常 .

要将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不会理解为什么 . 非常感谢您的帮助 .

1 回答

  • 1

    我能够以这种方式注册自定义格式化程序:

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

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

相关问题