国际化
编写国际化配置文件
@Configuration
@ConditionalOnMissingBean(value = MessageSource.class, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
private static final Resource[] NO_RESOURCES = {};
@Bean
@ConfigurationProperties(prefix = "spring.messages")
public MessageSourceProperties messageSourceProperties() {
return new MessageSourceProperties();
}
---------------------------------------------------------------------
public class MessageSourceProperties {
/**
* Comma-separated list of basenames (essentially a fully-qualified classpath
* location), each following the ResourceBundle convention with relaxed support for
* slash based locations. If it doesn't contain a package qualifier (such as
* "org.mypackage"), it will be resolved from the classpath root.
*/
private String basename = "messages";
所以在application.yml中配置
spring:
#国际化资源文件
messages:
#我们的配置文件可以直接放在类路径下叫messages.properties(默认)
basename: i18n.i18n
重点内容
配置SessionLocaleResolver
、LocaleChangeInterceptor
@Configuration
public class MyMvcConfig implements WebMvcConfigurer{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 等价于<mvc:view-controller path="/success" view-name="success"/>
registry.addViewController("/i18n").setViewName("i18n");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor()
registry.addInterceptor(new LocaleChangeInterceptor()).addPathPatterns("/**");
}
@Bean
public SessionLocaleResolver localeResolver(){
return new SessionLocaleResolver();
}
}
页面切换中英文 : 添加locale属性值即可
<a class="btn btn-sm" th:href="@{/i18n(locale='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/i18n(locale='en_US')}">English</a>