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;
@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 ==> 高