无法在spring boot中覆盖LocaleResolver bean

时间:2017-08-03 18:39:21

标签: spring-boot internationalization

我有一个纯REST spring启动应用程序,我正在尝试注入我自己的AcceptHeaderLocaleResolver类实现:

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,因此使用了默认的stragety。

可能缺少什么?

谢谢,

1 个答案:

答案 0 :(得分:0)

LocaleResolver bean移到WebMvcConfigurer bean之外。

    @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的 locale (原谅双关语)将不会被组件扫描拾取。