枚举国际化

SpringBoot枚举国际化:

public enum ResultCode {
    SUCCESS(0, ""),
    DATA_RESULT_NONE(2001, "DataNotExist"),
    DATA_ALREADY_EXISTED(2002, "DataAlreadyExist"),
    DATA_SAVE_FAIL(2003, "DataSaveFailed"),
    
    private Integer code;
    private String message;
    private static MessageSource messageSource;

    ResultCode(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public static void setMessageSource(MessageSource messageSource) {
        ResultCode.messageSource = messageSource;
    }

    public static void setI18nUtil(I18nUtil i18nUtil) {
        ResultCode.i18nUtil = i18nUtil;
    }

    //通过静态内部类的方式注入bean,并赋值到枚举中
    @Component
    public static class ReportTypeServiceInjector {

        private final MessageSource messageSource;

        public ReportTypeServiceInjector(MessageSource messageSource) {
            this.messageSource = messageSource;
        }
	    // 依赖注入完成后被自动调用
        @PostConstruct
        public void postConstruct() {
            ResultCode.setMessageSource(messageSource);
        }
    }
    
    // 获取信息时,获取国际化文本
    public String getMessage() {
        return messageSource.getMessage(message, null, LocaleContextHolder.getLocale());
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
}
posted @ 2019-11-20 17:30  Hayson  阅读(1188)  评论(0编辑  收藏  举报