how to declare a Java 8 method reference in a Spri

2019-03-27 10:48发布

问题:

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?

For example, suppose I have:

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

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

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

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

回答1:

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.

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.

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

Supposing a bean like this

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));    
    }

}

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>

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.