Spring Boot国际化i18n配置指南
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;
@Configuration
public class I18nConfig {
@Bean
public WebMvcConfigurer localeInterceptor() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
localeInterceptor.setParamName("lang");
registry.addInterceptor(localeInterceptor);
}
};
}
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Bean
public SessionLocaleResolver localeResolver() {
return new SessionLocaleResolver();
}
}
这段代码定义了一个配置类I18nConfig
,其中包含了国际化功能的三个核心组件:LocaleChangeInterceptor
、ResourceBundleMessageSource
和SessionLocaleResolver
。通过addInterceptors
方法,我们可以根据请求中的参数改变会话的区域设置,从而实现语言的切换。ResourceBundleMessageSource
则用于查找国际化消息,而SessionLocaleResolver
则用于在会话中解析区域设置信息。这个配置类可以直接用于Spring Boot项目中,简化了国际化的配置流程。
评论已关闭