Spring Boot 国际化

在SpringBoot中已经自动帮我们配置管理国际化资源的组件,所以我们只需要编写代码就可。

  

@Bean
    @ConfigurationProperties(prefix = "spring.messages")
    public MessageSourceProperties messageSourceProperties() {
        return new MessageSourceProperties();
    }

    @Bean
    public MessageSource messageSource(MessageSourceProperties properties) {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        if (StringUtils.hasText(properties.getBasename())) {
            messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
                    StringUtils.trimAllWhitespace(properties.getBasename())));  //获取基础名(login_zh_CN中的login部分)
        }
        if (properties.getEncoding() != null) {
            messageSource.setDefaultEncoding(properties.getEncoding().name());
        }
        messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
        Duration cacheDuration = properties.getCacheDuration();
        if (cacheDuration != null) {
            messageSource.setCacheMillis(cacheDuration.toMillis());
        }
        messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
        messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
        return messageSource;
    }

  1.编写代码。

    在类路径下创建一个i18n的文件夹,存放国际化配置(login.properties、login_zh_CN.properties、login_en_US.properties)分别填写对应的值即可。

    2.在页面中获取国际化信息

    在thymeleaf中获取值信息。通过#{键}获取国际化中的值。

   3.在application.properties中配置如下代码。

#指定i18n从哪里配置
spring.messages.basename=i18n.login  //位置

  

  效果:会根据浏览器系统语言自动显示对应文字

猜你喜欢

转载自www.cnblogs.com/lcaiqin/p/10422072.html