问题描述
我目前正在使用Spring Boot(包括Spring Security)开发Web应用程序。目前,我正尝试将对默认语言俄语的国际化支持作为开始。 这是一个配置文件,如果用户输入了错误的数据或其他信息,但我返回了英语
,我便在其中写入以俄语获取消息import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
@Configuration
public class ConfigForAuth {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(new Locale("ru"));
return slr;
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource rs = new ReloadableResourceBundleMessageSource();
rs.addBasenames("classpath:i18n/messages");
rs.addBasenames("classpath:/org/springframework/security/messages_ru.properties:1");
rs.setDefaultEncoding("UTF-8");
rs.setUseCodeAsDefaultMessage(true);
return rs;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("locale");
return localeChangeInterceptor;
}
}
但是,如果我将在应用程序文件中写入相同的代码,则此代码可以正常工作并在RU中返回给我 申请文件:
@SpringBootApplication
@ComponentScan("--.--.--")//conf
@EnableCaching
@PropertySources({
@PropertySource("classpath:application.properties"),@PropertySource("classpath:clients.properties")
})
public class OneBpmAuthApiApplication {
public static void main(String[] args) {
SpringApplication.run(OneBpmAuthApiApplication.class,args);
}
解决方法
尝试从WebMvcConfigurerAdapter
扩展并添加拦截器。
@Configuration
public class ConfigForAuth extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
,
我认为以前的建议或多或少是正确的,只是需要将ParamName设置为“ lang”,如下所示:
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new
LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
还请记住要扩展WebMvcConfigurer。