国际化多语言配置
如中文的:messages_zh_CN.properties
property1=属性1property2=属性2
英文的:
property1=property oneproperty2=property two
配置国际化:
@Configurationpublic class I18Interceptor extends WebMvcConfigurationSupport {
//属性文件中未读取到则设置默认目录i18n
@Value(value = "${spring.messages.baseFolder:i18n}")
private String basename;
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename(basename);
return messageSource;
}
/**
* 继承了WebMvcConfigurationSupport会导致自动配置失效访问不了static下的静态资源,这里需要手动配置下
*
* @param
* @return
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
/**
* 添加拦截器
*
* @param
* @return
*/
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
/**
* 构造一个国际化拦截器实例
*
* @param
* @return
*/
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");//设置代表本地的请求参数字段,默认为local
return localeChangeInterceptor;
}
/**
* 构造一个session区域使用local的解析策略
*
* @param
* @return
*/
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
return localeResolver;
}
}
获取相应语言版本内容:
@Autowiredprivate MessageSource messageSource;
public String getMessage(String attrName) {
return messageSource.getMessage(attrName, null, "", LocaleContextHolder.getLocale());
}
注意:在springboot2.0之后,配置类继承WebMvcConfigurerAdapter类已经过时,然后就改为继承WebMvcConfigurationSupport,但是继承该类后会导致自动配置失效访问不到静态目录下的资源,需要手动再配置一下静态资源路径
以上是 国际化多语言配置 的全部内容, 来源链接: utcz.com/z/516130.html