解决Spring Boot中的国际化与本地化问题
    		       		warning:
    		            这篇文章距离上次修改已过416天,其中的内容可能已经有所变动。
    		        
        		                
                
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
 
import java.util.Locale;
 
@Configuration
public class I18nConfig implements WebMvcConfigurer {
 
    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
 
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        return localeChangeInterceptor;
    }
 
    @Bean
    public SessionLocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        localeResolver.setDefaultLocale(Locale.US);
        return localeResolver;
    }
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}这段代码定义了一个配置类I18nConfig,它提供了ResourceBundleMessageSource的Bean,这是Spring用来解析国际化消息的。同时,它还提供了一个LocaleChangeInterceptor的Bean,这个拦截器可以根据请求中的参数改变会话的区域设置。最后,它覆盖了addInterceptors方法,将localeChangeInterceptor添加到拦截器注册表中。这样就可以根据请求参数动态改变应用的国际化设置。
评论已关闭