1

Trying to get Unit Tests to work when using Spring RestTemplate and I18N. Everything in the setup works fine for all the other test cases.

Based upon what I read, this is what I put into the Java Config:

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    return new LocaleChangeInterceptor();
}

@Bean
public DefaultAnnotationHandlerMapping handlerMapping() {
    DefaultAnnotationHandlerMapping mapping = new DefaultAnnotationHandlerMapping();
    Object[] interceptors = new Object[1];
    interceptors[0] = new LocaleChangeInterceptor();
    mapping.setInterceptors(interceptors);
    return mapping;
}

@Bean
public AnnotationMethodHandlerAdapter handlerAdapter() {
    return new AnnotationMethodHandlerAdapter();
}

Then in my usage with RestTemplate I have:

    public MyEntity createMyEntity(MyEntity bean) {
    Locale locale = LocaleContextHolder.getLocale();
    String localeString = "";
    if (locale != Locale.getDefault()) {
        localeString = "?locale=" + locale.getLanguage();
    }
    HttpEntity<MyEntity> req = new HttpEntity<MyEntity>(bean);
    ResponseEntity<MyEntity> response = restTemplate.exchange(restEndpoint + "/url_path" + localeString, HttpMethod.POST, req, MyEntity.class);
    return response.getBody();
}

While this could be cleaned up a bit, it should work - but the LocalChangeInterceptor never gets invoked. I am debugging this now and will post again as soon as I figure it out - but in the hope this is a race condition that I lose - does anyone know why?

4

1 回答 1

1

很幸运,偶然发现了这个线程。其中一个笔记让我找到了正确的方向。您不需要 Java Config 中的所有这些 bean。但是,如果您像我一样使用@EnableWebMvc,但我不知道它是否重要到足以提及,那么您在 Java Config 中需要做的就是:

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    return new LocaleChangeInterceptor();
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LocaleChangeInterceptor());
    super.addInterceptors(registry);
}

为拦截器添加一个 bean,然后覆盖添加拦截器的方法。这里我的配置类(用@Configuration和@EnableWebMvc注解)也扩展了WebMvcConfigurerAdapter,应该是常用的。

至少,这对我有用。希望它可以帮助别人。

于 2012-10-10T18:45:38.357 回答