【发布时间】:2014-04-22 23:55:27
【问题描述】:
我正在使用 Spring 4,并且我有一个声明为...的枚举...
public static enum MY_ENUMS {
A(1, "enum1"),
B(2, "enum2");
private final int key;
private final String name;
MY_ENUMS(int key, String name) {
this.key = key;
this.name = name;
}
public String getName() {
return this.name;
}
public int getIndex() {
return this.key;
}
}
然后,在我的组件中,我正在尝试做类似...
// @Named is the equivalent of @Component for this use case
// Making name public and trying this also does not work:
// @Named(MY_ENUMS.A.name)
@Named(MY_ENUMS.A.getName())
public class ServiceImplA implements IService {
@Override
public Object interfaceMethod() {
// Some code specific to ServiceImplA here....
}
}
这不成立,我知道为什么这不成立。基本上,MY_ENUMS.A.getName() 在编译器看来并不是恒定的,这意味着它不能在这里使用。但枚举的重点在于,它们允许您以一种有用的方式声明常量。那么,话虽如此,有没有一种方法可以通过引用枚举中的值来指定组件的名称?
鉴于枚举是常量值的特殊情况/实现,我觉得这应该是可能的,但我想不出一种方法来解决 Spring(或者可能是 Java)对注释值是直线上升的期望常数。
【问题讨论】:
标签: java spring dependency-injection enums