如何在Spring XML文件中声明Java 8方法引用? [英] how to declare a Java 8 method reference in a Spring XML file?

查看:292
本文介绍了如何在Spring XML文件中声明Java 8方法引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Java 8方法引用声明为Spring bean。在Spring XML文件中执行此操作的最简单方法是什么?

I would like to declare a Java 8 method reference as a Spring bean. What is the easiest way of doing this in a Spring XML file?

例如,假设我有:

class Foo {
    Foo(ToLongFunction<Bar> fn) { ... }
}

class Bar {
    long getSize() { ... }
}

...我想要创建一个 Foo ,它将方法引用 Bar :: getSize 作为构造函数参数。

... and I want to create a Foo that takes the method reference Bar::getSize as the constructor argument.

如何在Spring bean XML文件中声明 Foo 实例?

How do I declare the Foo instance in a Spring bean XML file?

推荐答案

我提出的解决方案可能不是最好的想法,但我发现这个问题很有意思,并决定试一试。这是我能想到的最好的。

My proposed solution below is probably not the best idea, but I found the question interesting and decided to try to give it a shot. This is the best I could come up with.

我不知道在这一刻是否有办法直接这样做(除了定义某种工厂bean),但你也可以使用动态语言支持,例如使用Groovy。

I don't know if there is a way to do this directly in this moment (aside from defining some kind of factory bean), but alternatively you could do it using dynamic language support, for instance with Groovy.

以下示例使用最新版本的Spring运行(截至今天) 4.1.6)

The following example ran for me using the latest version of Spring (as of today 4.1.6)

假设这样的bean

public class Foo {

    private Function<String, String> task;

    @Autowired
    public Foo(Function<String, String> task){
        this.task = task;
    }

    public void print(String message) {
        System.out.println(task.apply(message));    
    }

}

然后我可以定义XML配置喜欢:

Then I could define an XML configuration like:

<lang:groovy id="func">
    <lang:inline-script>
        <![CDATA[
                import java.util.function.Function
                { text -> "Hello " + text } as Function
        ]]>
    </lang:inline-script>
</lang:groovy>

<bean id="foo" class="demo.services.Foo">
    <constructor-arg name="task" ref="func"/>
</bean>

当然,lambda的语法取决于您选择的语言。我不知道Groovy是否有类似方法引用的东西,但任何方法引用都可以用lambda / closure表示,就像我上面所做的那样。

Of course, the syntax of your lambda will depend on the language you choose. I have no idea if Groovy has something like method reference, but any method reference could be expressed with a lambda/closure as I did above.

这篇关于如何在Spring XML文件中声明Java 8方法引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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