Spring和Scala - Function1构造函数-arg

时间:2016-03-29 15:27:19

标签: spring scala

我正在努力使用Twitter Scala类创建bean。它的构造函数参数不是简单类型,而是Scala Function1类型。我该怎么做呢?

<bean id="permissivePolicy" class="com.twitter.finagle.http.filter.Cors.Policy">
</bean>

这个类的构造函数参数是:

case class Policy(
  allowsOrigin: String => Option[String],
  allowsMethods: String => Option[Seq[String]],
  allowsHeaders: Seq[String] => Option[Seq[String]],
  exposedHeaders: Seq[String] = Nil,
  supportsCredentials: Boolean = false,
  maxAge: Option[Duration] = None
)

这意味着,在Spring bean中,我需要传递类型的构造函数args:

1. allowsOrigin - Function1<String, Option<String>>
2. allowsMethods - Function1<String, Option<Seq<String>>>
3. allowsHeaders - Function1<Seq<String>, Option<Seq<String>>>
4. exposedHeaders - Seq<String>
5. supportsCredentials - boolean
6. maxAge - Option<Duration>

我不熟悉Scala,所以我不确定如何创建这个bean。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

最后整理出来。我首先必须将scala-util添加到application.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:scala-util="http://www.springframework.org/schema/scala/util"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/scala/util 
            http://www.springframework.org/schema/scala/util/scala-util.xsd">

我还需要创建Function1特征的Scala实现(基本上只是一个接口):

    package com.test.util

    class Function1Impl extends Function1[String, Option[String]] {
      override def apply(v1: String): Option[String] = Some("")
    }

现在,回到application.xml,我创建了必要的Beans以匹配构造函数args,并创建了引用它们的permissivePolicy bean:

      <bean id="scalaOptionBean" class="scala.Some">
        <constructor-arg value="" />
      </bean>
      <bean id="function1Bean" class="com.test.util.Function1Impl" />
      <scala-util:seq id="scalaSeqBean" />

      <bean id="permissivePolicy" class="com.twitter.finagle.http.filter.Cors.Policy">
        <constructor-arg ref="function1Bean" />
        <constructor-arg ref="function1Bean" />
        <constructor-arg ref="function1Bean" />
        <constructor-arg ref="scalaSeqBean" />
        <constructor-arg type="boolean" value="true" />
        <constructor-arg ref="scalaOptionBean" />
      </bean>

      <bean id="httpFilter"
            class="com.twitter.finagle.http.filter.Cors.HttpFilter">
        <constructor-arg ref="permissivePolicy" />
      </bean>

这给了我一个Policy对象,其中包含正确类型的空构造函数参数。如果我想在某些时候填充它们,只需要更改Function1Impl或调整application.xml中的值。