springboot 中通过配置国际化文件( messages.properties )给枚举类( enum )赋值

1. 在 application .properties 中配置国际化文件的路径

spring.messages.basename=i18n/messages

2. 枚举类 Level.java

package com.example.d3.enums;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.EnumSet;

public enum Level {
	LOW("0", "level.LOW"),
	MEDIUM("1", "level.MEDIUM"),
	HIGH("2", "level.HIGH");

	private String value;
	private String description;

	private Level(String value, String description) {
		this.value = value;
		this.description = description;
	}

	public String getValue() {
		return this.value;
	}

	public String getDescription() {
		return messageSource.getMessage(description, null, description, null);
	}

	private MessageSource messageSource;

	public Level setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
		return this;
	}

	@Component
	public static class EnumValuesInjectionService {

		@Autowired
		private MessageSource messageSource;

		//通过静态内部类的方式注入到bean,并 赋值到枚举中。
		@PostConstruct
		public void postConstruct() {

			for (Level level : EnumSet.allOf(Level.class)) {
				level.setMessageSource(messageSource);
			}
		}
	}
}

3. 在 messages.properties 中加入测试信息

level.LOW=低
level.MEDIUM=中
level.HIGH=高

4. 编写测试类

package com.example.d3;

import com.example.d3.enums.Level;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class EnumTest {
	private static final Logger logger = LoggerFactory.getLogger(EnumTest.class);

	@Test
	public void test() {

		for (Level level : Level.values()) {
			String value = level.getValue();
			String description = level.getDescription();
			logger.info(value + " ==> " + description);
		}
	}
}

5. 运行并输出结果

2020-01-16 20:57:33.334  INFO 45386 --- [           main] com.example.d3.EnumTest                  : 0 ==> 低
2020-01-16 20:57:33.334  INFO 45386 --- [           main] com.example.d3.EnumTest                  : 1 ==> 中
2020-01-16 20:57:33.334  INFO 45386 --- [           main] com.example.d3.EnumTest                  : 2 ==> 高
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值