---
title: "现有web系统替换成Spring Boot2框架 之14 I18n国际化实现"
author: "sanry"
date: "2019-02-26T11:06:10Z"
tags: []
categories: ["编程语言"]
slug: "web-spring-boot2-14-i18n"
draft: false
lastmod: "2019-02-20T16:09:40Z"
id: 2437842
url: "https://sanry.iteye.com/blog/2437842"
---

## **此步骤是修改自己代码没有公共性**

## **16.1 国际化文件处理**

将原来的国际化文件重命名如下，放到/src/resources目录下

## 16.2 **初始化国际化类**

最终需要使用MessageSource 实现国际化。将国际化类的加载放到启动加载项中InitializedThreadPool.java 启动系统时将国际化类初始化方便后续使用。

@Autowired

**private** MessageSource messageSource;

//中英文转换类

I18nBean.*getInstance*().*setMessageSource*(messageSource);

## 16.3 **修改国际化类**

1. 增加MessageSource 属性初始化时注入

2. 将getString()方法改成使用MessageSource 获取值

**private** **static** MessageSource *messageSource*;

 

**private** I18nBean(){}

 

**private** **static** I18nBean *i18nBean* = **null**;

 

**private** **static** ResourceBundle *resourcesBundle\_ch* = **null**;

 

**private** **static** ResourceBundle *resourcesBundle\_en* = **null**;

**public** **static** I18nBean getInstance(){

 

**if**(*i18nBean* == **null**){

*i18nBean* = **new** I18nBean();

}

 

**return** *i18nBean*;

}

 

 **public** **static** **void** setMessageSource(MessageSource ms) {

*messageSource* = ms;

}

 

**public** **static** String getI18NStringByKey(String key, HttpServletRequest request) {

 **return** *messageSource*.getMessage(key, **null**, *getLocale*());

    }

 

 /\**

  * 供页面中英文转换使用

  * **@param** request

  * **@return**

  \*/

 **public** **static** ResourceBundle getResourceBundle(HttpServletRequest request) {

 **public** **static** MessageSource getMessageSource() {

**return** *messageSource*;

 }

 **public** **static** Locale getLocale() {

**return** LocaleContextHolder.*getLocale*();

 }

 **public** **static** String getString(String code) {

 **return** *messageSource*.getMessage(code, **null**, *getLocale*());

 }

## **16.4 统一修改jsp国际化使用的方法**

taglibs.jsp修改：

&lt;%

I18nBean rb = I18nBean.getInstance();

%&gt;

 

以上步骤完成之后jsp页面通过rb.getString();就可以获取国际化数据，就不需要每个jsp页面都修改了