【问题标题】:Is it possible to map Spring components through annotations using enums?是否可以使用枚举通过注解映射 Spring 组件?
【发布时间】: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


    【解决方案1】:

    有没有一种方法可以通过引用来指定我的组件的名称 枚举中的值?

    不,没有。如果注释属性需要enum,则可以只使用enum。但是调用方法不会解析为常量表达式。您可能认为可以将字段设为public 并直接访问它

    @Named(MY_ENUMS.A.name)
    

    但这也行不通,因为MY_ENUMS.A.name 也不是常量表达式。

    theat 不是常量表达式的实际原因是枚举常量基本上是一个变量。有一个常量变量这样的东西,它是一个常量表达式。要使变量成为常量变量,它需要为final 并使用常量表达式进行初始化。 enum 常量为 final,但未使用常量表达式进行初始化。基本上 enum 常量被编译为

    public static final YourEnum constant = new YourEnum();
    

    new YourEnum() 表达式不是常量表达式。因此常量不是常量变量,不能用于解析可能是常量变量的String 变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多