1、在项目下新增个资源文件
2、文件内容:
3、在配置文件application.yml上加上资源路径
messages:
# 定义国际化文件的文件地址,读取的原则是顺序读取如果存在同名的则读取第一个
basename: i18n/supplier
encoding: UTF-8
4、添加两个Java工具类(放在当前文件下),全局读取前端传来的选择的语言
类名为(SpringUtils ,I18nUtil)
package com.xxx.xxx.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
/**
* Spring容器
*
* @author: modelsetget
* @create: 2019-11-12 10:56
*/
@Service
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext context = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (context == null) {
context = applicationContext;
}
}
/**
* 获取容器
*
* @return 容器
*/
public static ApplicationContext getContext() {
return context;
}
}
package com.xxx.xxx.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.NoSuchMessageException;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
/**
* @author: xxx
* @create: 2019-11-12 10:56
**/
@Component
@Slf4j
public class I18nUtil {
@Autowired
private HttpServletRequest request;
/**
* 获取消息 也可以使用下面的方式:
*
* @param code k
* @return v
*/
public String getMessage(String code) {
try {
return SpringUtils.getContext().getMessage(code, null, Locale.forLanguageTag(request.getHeader("language")));
} catch (NoSuchMessageException e) {
log.error("获取国际化资源{}失败" + e.getMessage(), code, e);
return "获取国际化资源失败";
}
}
}
5、实现类引用工具类使用
@Autowired
private I18nUtil i18nUtil;
// 调用
i18nUtil.getMessage("add_failed")