1. 程式人生 > >spring boot 語言國際化操作

spring boot 語言國際化操作

        最近在學習spring boot的技術,這裡整理一下spring boot中的國際化,方便以後使用國際化時,可以直接呼叫或者加以參考,縮短開發時間。

        首先是編寫國際化的資原始檔,通常將其放在i18n資料夾下,然後定義一個properties檔案,使用國際化時,遵守相關的約定,IDEA工具以及spring boot會自動幫我們識別這個國際化資原始檔。其約定是:檔名.properties(這個為預設的國際化檔案),然後是 檔名_語言程式碼_國家程式碼.properties(例:messages_zh_CN.properties)。下圖是IDEA工具識別到為國際化資原始檔後,提供的一個便捷操作:

        這裡國際化資源我的命名是lang,如果這裡進行了命名,就要在application.properties中修改spring.messages.basename的值,我的是放在i18n資料夾下並命名為lang的,故spring.messages.basename=i18n.lang,如果不在配置檔案中進行修改,那麼就識別不到該國際化資原始檔,原因如下:

public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
            String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages");
            ConditionOutcome outcome = (ConditionOutcome)cache.get(basename);
            if(outcome == null) {
                outcome = this.getMatchOutcomeForBasename(context, basename);
                cache.put(basename, outcome);
            }

            return outcome;
        }

        在MessageSourceAutoConfiguration類中,資原始檔名就是從配置檔案中讀取的,配置檔案若對basename沒有命名,就預設為messages,若命名了,則改為所命名的。

        debug操作如圖:

        因此,如果不想修改配置檔案,那麼就將國際化的相關資原始檔的字首統一命名為messags即可。

        要實現國際化效果,需要實現LocaleResolver這個介面,只需要重寫resolverLocale這個方法即可,在前臺定義請求引數,設定好中英文,程式碼中使用了thymeleaf語法,等同於a標籤的超連結傳參

<a class="btn btn-sm" th:href="@{/index.html(lang='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(lang='en_US')}">English</a>

        後臺處理這個引數,通過引數的值來選擇語言。

public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String lang = request.getParameter("lang");
        Locale locale = Locale.getDefault();
        if(lang!=null&&lang.length()==5){
            String[] split = lang.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    }
}

        後臺就已經完成了處理,前臺只需要對語言資原始檔進行引用就可以了,下方程式碼是thymeleaf引用國際化資源。

<h1 th:text="#{lang.tip}">Please sign in</h1>

        當然,可以選擇自己的方式進行前後臺的邏輯處理。

        最後,記得將這個自定義的國際化的類加入到容器中,在自己定義的MvcConfig中,新增

    @Bean
    public LocaleResolver localeResolver(){

        return new MyLocaleResolver();
    }

        使得spring boot可以將其註冊到容器中。