使用spring将枚举的值注入属性 [英] Inject the value of an enum into a property using spring

查看:1554
本文介绍了使用spring将枚举的值注入属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似下面的枚举

public enum MyEnum {
ABC("some string"), 
DEF("some string"), 
GHI("another string");

String value;

private MyEnum(String value) {
    this.value = value;
}

public String value() {
    return this.value;
}}

我想制作一个util:map使用的值枚举作为关键而不是枚举本身。所以地图看起来像这样:

And I would like to make a util:map using the value of the enum as the key not the enum itself. So the map would look like this:

"some string" -> "mapped output 1"
"another string" -> "mapped output 2"

我知道我可以使用util:constant来获取枚举但是我需要枚举代​​表的值。

I know I can use util:constant to get the enum but i need the value the enum represents.

所以我的配置文件在这一刻看起来像这样:

So my config file at the minute looks like this:

<util:constant id="firstKey" static-field="package.MyEnum.ABC"/>
<util:constant id="secondKey" static-field="package.MyEnum.GHI" />


<util:map id="myMap">
    <entry key-ref="firstKey" value="mapped output 1" />
    <entry key-ref="secondKey" value="mapped output 2" /></util:map>

有没有办法可以获得.value()甚至可以访问value属性来使用它作为密钥?

Is there a way I can get .value() or even get access to the value property to use it as the key?

我试图将密钥类型声明为字符串,希望Spring可以解决这个问题,但它似乎忽略了这一点。

I tried declaring the key type to be string in the hope spring would work it out but it seems to have just ignored this.

使用spring 2.5.1并且我无法修改枚举

Using spring 2.5.1 and I cannot modify the enum

推荐答案

如果您无法访问表达式语言,则必须回退到显式 MethodInvokingFactoryBean

If you don't have access to the expression language you'll have to fall back to an explicit MethodInvokingFactoryBean

<bean id="firstKey" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
  <property name="targetObject"><util:constant static-field="package.MyEnum.ABC"/></property>
  <property name="targetMethod" value="value" />
</bean>

您可以使用抽象父bean定义缩短重复XML。

You could shorten the repetitive XML a bit with an abstract parent bean definition.

<bean name="enumValue" abstract="true"
      class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
  <property name="targetMethod" value="value" />
</bean>

<bean id="firstKey" parent="enumValue">
  <property name="targetObject"><util:constant static-field="package.MyEnum.ABC"/></property>
</bean>

你也可以跳过 MethodInvokingFactoryBean 而且只是使用

You could also skip the MethodInvokingFactoryBean and just use

<util:constant id="MyEnum_ABC" static-field="package.MyEnum.ABC" />
<bean id="firstKey" factory-bean="MyEnum_ABC" factory-method="value" />

但这意味着为每个枚举常量和它们的<$ c声明单独的顶级bean $ c> value(),而使用MIFB可以使用匿名内部bean。

but that means declaring separate top-level beans for each enum constant as well as for their value(), whereas using MIFB allows you to use anonymous inner beans.

这篇关于使用spring将枚举的值注入属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆