java - 如何从 Java/Spring 创建类型化的 Tuple2?

标签 java scala spring tuples

我希望能够从 spring 配置创建一个 Tuple2 ,在其中显式声明参数的类型:

<bean class="scala.Tuple2">
      <constructor-arg index="0" value="Europe/London" type="java.util.TimeZone" />
      <constructor-arg index="1" value="America/New_York" type="java.util.TimeZone" />
</bean>

这不起作用(我在配置文件中指定了相关的属性编辑器)。在运行时我收到错误:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'scala.Tuple2#6504bc' defined in file [C:\Work\myproj\config\test\myproj.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang.Object]:
Ambiguous constructor argument types - did you specify the correct bean references as constructor arguments?

如果我不声明显式类型,错误就会消失 - 但当然我程序中的Tuple2只是一个(String, String) 这不是我想要的。

<小时/>

为那些不知道这一点的人进行编辑,Spring 使用 PropertyEditor 从字符串创建实例,如下所示:

public class TimeZoneEditor extends java.beans.PropertyEditorSupport {
    public void setAsText(String text) { setValue(TimeZone.getTimeZone(text)); }
    public String getAsText() { return ((TimeZone)getValue()).getID(); }
}

现在我只需在我的配置中声明:

<bean id="customEditorConfigurer" 
       class="org.springframework.beans.factory.config.CustomEditorConfigurer">   
    <property name="customEditors"> 
        <map>
            <entry key="java.util.TimeZone">
                <bean class="my.cleve.rutil.TimeZoneEditor"/> 
            </entry>
        </map>
    </property> 
</bean>

嘿,我可以做这样的事情:

<map key-type="java.util.TimeZone" value-type="java.lang.Integer">
    <entry key="Europe/London" value="4" />
</map>

或者 Spring 可以从您的 setter 方法中找出泛型类型参数。但它似乎不适用于我的 Tuple2!

最佳答案

您需要使用 TimeZone 类的静态方法 getTimeZone() 显式创建 TimeZone 参数:

<bean class="scala.Tuple2">
  <constructor-arg index="0">
    <bean class="java.util.TimeZone" factory-method="getTimeZone">
      <constructor-arg value="Europe/London"/>
    </bean>
  </constructor-arg>
  <constructor-arg index="1">
    <bean class="java.util.TimeZone" factory-method="getTimeZone">
      <constructor-arg value="America/New_York"/>
    </bean>
  </constructor-arg>
</bean>

关于java - 如何从 Java/Spring 创建类型化的 Tuple2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1716206/

相关文章:

java - 在 Java 中使用模式匹配

java - java8 中的 concurrentHashMap 中的 sizectl

java - 如何将外部库的源代码和 javadoc 添加到 IntelliJ 的 gradle 中?

java - Oracle ADF : SkinFactory is not working correctely in JDeveloper 12. 1.3

java - Scala UOM 库

scala - 如何在 sbt 中命令执行测试?

scala - Spark : How to union a List<RDD> to RDD

java - 更改 Spring PropertyPlaceholderConfigurer 以从另一个源读取

java - Spring Boot 中使用 3 个表进行 Hibernate 映射的问题

java - 必须只接受特定数值的 validator