文章目的:使用SpringBoot 2.*(其实就是Spring MVC 5) 加 Thymeleaf 实现国际化。
其实很简单的问题,但由于网上SpringBoot 教程大多在 1.5.3.RELEASE ,没有实际能解决的。
看Thymeleaf官方 、SpringBoot 官方、Spring MVC 5 官方文档。所以解决这个问题用了我2天...我还是太菜了。
进入主题:
首先是pom.xml依赖加上Thymeleaf。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
然后创建一个配置类:
@Configuration
@ComponentScan
public class MyConfiguration implements WebMvcConfigurer {
/* @Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("classpath:i18n/messages");//设置默认的国际化资源文件路径
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}*/
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:i18n/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new LocaleChangeInterceptor());
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
return slr;
}
然后创建国际化资源文件(properties):
我的工程目录结构: