2017-08-03 27 views
0

我有一个纯粹的REST春天启动应用程序,我想注入我自己实现的AcceptHeaderLocaleResolver类:无法覆盖春天启动的LocaleResolver豆

public class SmartLocaleResolver extends AcceptHeaderLocaleResolver implements InitializingBean { 
@Override 
    public Locale resolveLocale(HttpServletRequest request) { 
     // Some code... 
    } 
} 

而我像注射豆所以:

@EnableTransactionManagement()    
@SpringBootApplication(scanBasePackages = { "app.core.i18n" }) 
public class Application extends SpringBootServletInitializer { 

    private static Class<Application> applicationClass = Application.class; 

    @Autowired 
    private FhngHibernateInterceptor interceptor; 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 

    @Bean 
    public WebMvcConfigurer corsConfigurer() { 
     return new WebMvcConfigurerAdapter() { 

      @Override 
      public void addCorsMappings(CorsRegistry registry) { 
       registry.addMapping("/**") 
       .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") 
       .allowedOrigins("*") 
       ; 
      } 

      @Bean 
      public LocaleResolver localeResolver() { 
       SmartLocaleResolver slr = new SmartLocaleResolver(); 
       slr.setDefaultLocale(Locale.forLanguageTag("en")); 
       return slr; 
      } 
     }; 
    } 
} 

但是,无论我做什么,我自己resolveLocale()方法是从未调用。我设置的DispatcherServlet :: initLocaleResolver中的断点()来确认这一点:

private void initLocaleResolver(ApplicationContext context) { 
    try { 
     // This always throww the NoSuchBeanException 
     this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class); 

     } 
    } 
    catch (NoSuchBeanDefinitionException ex) { 
     // We need to use the default. 
     this.localeResolver = getDefaultStrategy(context, LocaleResolver.class); 

    } 

的bean是从来没有发现这么使用默认的战略前导。

什么可能会丢失?

谢谢

回答

0

移动你的LocaleResolver豆你WebMvcConfigurer豆之外。

@Bean 
    public WebMvcConfigurer corsConfigurer() { 
     return new WebMvcConfigurerAdapter() { 

      @Override 
      public void addCorsMappings(CorsRegistry registry) { 
       registry.addMapping("/**") 
         .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") 
         .allowedOrigins("*"); 
      } 
     }; 
    } 

    @Bean 
    public LocaleResolver localeResolver() { 
     SmartLocaleResolver slr = new SmartLocaleResolver(); 
     slr.setDefaultLocale(Locale.forLanguageTag("en")); 
     return slr; 
    } 

你的bean的区域(原谅双关语)不会被组件扫描,如果你把它定义有被拾起。