背景:在spring中使用@value注解来达到动态配置线上和预发环境的参数,在普通类中可以随意使用@value实现,java枚举enum无法注入,怎么解决这个问题?
public enum SpringValueEnum {
TEACHER(0, "我是老师"),
STUDENT(1, "我是学生") {
@Override
public String getDesc() {
return PeopleEnumContainer.name;
}
};
private Integer code;
private String desc;
SpringValueEnum(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Component
static class PeopleEnumContainer {
private static String name;
@Value("${people.student.desc}")
public void init(String name) {
PeopleEnumContainer.name = name;
}
}
}
如上,使用内部类注入,重写枚举属性get方法来达到动态替换的目的。