使用spring boot 实现返回信息国际化记录

来源:互联网 发布:js获取日期时间戳 编辑:程序博客网 时间:2024/05/07 21:18

一、内容

本文主要是记录spring boot 使用enum + MessageSource + *.properties 实现国际化问题

二、步骤

2.1 新建一个枚举(enum)

枚举主要是用来存放返回信息的编号和代码,如

编号 错误代码 描述 10001 ILLEGAL_PASSWORD 密码错误 ….. ……… ….

注意:这里的错误代码是.properties文件中对象的key值,描述则是相应的值,分为英文和中文,在messages_zh_CN.properties文件中为“密码错误”,在messages_en_US.properties中为“the password is illegal”。
代码如下

/** * @author lcl * @createDate 2016年11月21日上午8:25:17 * 错误返回信息枚举 */public enum ErrorStatus {    ACCOUNT_EXISTED(10001),    private int code;    private ErrorStatus(int code) {        this.code = code;    }    public int getCode() {        return code;    }}

2.2 配置MessageSource实体

该类主要是从资源文件中根据key和locale获取相应的值

@Configurationpublic class InternationalConfig {    @Value(value = "${spring.messages.basename}")    private String basename;    @Bean(name = "messageSource")    public ResourceBundleMessageSource getMessageResource() {        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();        messageSource.setBasename(basename);        return messageSource;    }}

2.3 创建相应的资源文件
2.3.1 创建不同的文件,并根据枚举中的name创建相应的信息
2.3.2 在application.properties中配置相关的message

2.4 使用messagesource获取资源文件中的信息
这一步根据自己的业务需求获取

@Componentpublic class ErrorMessageSourceHandler {    @Autowired    private  MessageSource messageSource;    /**     * 根据     * @param messageKey     * @return     */    public String getMessage(String messageKey) {        String message = messageSource.getMessage(messageKey, null, LocaleContextHolder.getLocale());        return message;    }}
0 0