SpringBoot之国际化配置

国际化

编写国际化配置文件

@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

国际化资源文件

重点内容
配置SessionLocaleResolverLocaleChangeInterceptor

@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>

   转载规则


《SpringBoot之国际化配置》 yywzt 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
SpringBoot自定义Start SpringBoot自定义Start
自定义starterstarter: ​ 1、这个场景需要使用到的依赖是什么? ​ 2、如何编写自动配置 @Configuration //指定这个类是一个配置类 @ConditionalOnXXX //在指定条件成立的情况
2018-07-09
下一篇 
SimpleDateFormat线程安全问题 SimpleDateFormat线程安全问题
1.SimpleDateFormat 是线程非安全的 * Date formats are not synchronized. * It is recommended to create separate format instances
2018-06-27
  目录