使用Spring初始化枚举成员
我有和枚举如下 公共枚举髓鞘{使用Spring初始化枚举成员,spring,enums,initialization,Spring,Enums,Initialization,我有和枚举如下 公共枚举髓鞘{ ENUM1("ENUM1Code", "ENUM1 Desc"), ENUM2("ENUM2Code", "ENUM2"), ENUM3("ENUM3Code", "ENUM3"); private String code; private String description; private MyEnum(String code, String description) { this.code = code; this.description
ENUM1("ENUM1Code", "ENUM1 Desc"), ENUM2("ENUM2Code", "ENUM2"), ENUM3("ENUM3Code", "ENUM3");
private String code;
private String description;
private MyEnum(String code, String description) {
this.code = code;
this.description = description;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
}
有人能建议我如何从这个枚举中删除初始化并在Spring中执行吗
提前谢谢
Dileep您不能,因为枚举是静态对象。
您可以将代码/描述外部化并手动管理它们 编辑:
我看不出有必要用Spring来做这种工作;您可以使用easy代码实现相同的目标(使用了一点Spring,即
PropertiesLoaderUtils
utility类)。创建一个属性文件,用于存储每个枚举的代码和描述,并编写实用程序代码来读取数据;自定义代码的结果是这样的UDT:
class EnumWithData implements Serializable {
MyEnum enumValue;
String code;
String description;
// Write properties get/set
// Equals check for enumValue only
boolean equals(Object other) {
EnumWithData b = (EnumWithData)other;
return b.enumValue == this.enumValue;
}
}
abstract class EnumWithDataUtility {
private static Properties definition = PropertiesLoaderUtils.loadProperties("path/to/resource");
public final static EnumWithData getEnumWithData(MyEnum enumValue) {
EnumWithData udt = new EnumWithData();
udt.enumValue = enumValue;
...
return udt;
}
}
您好,谢谢您的回复,您能澄清一下外部化是什么意思吗?使用spring我们怎么能做到这一点呢?非常感谢@Luca Basso Ricci,我会试试这个