2016-08-10 7 views
0

Web MVCを使用してREST APIを開発するSpringブートアプリケーション。すべて正常に動作します。 ZonedDateTimeに文字列を変換するには外部JarのSpringカスタムフォーマッタ

は、私はこの注釈を作成しました:ここ

@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はカスタムコンバータを登録しません!なぜか分からない。 あなたの助けに感謝します。

+0

私はgithubでコードを見ることができますか? –

+0

できません。 –

+0

ok男、幸運 –

答えて

0

私は、カスタムフォーマッタをこのように登録することができました:

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

フォーマッタがすでに設定に登録されている場合でも、私は私のテストのためにこれを行う必要があり、なぜ私にはわかりません。

関連する問題