How to declare a reference to a Java 8 method in a Spring XML file?

I would like to declare a reference to the Java 8 method as a Spring bean. What is the easiest way to do 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 references the argument of the Bar::getSize as a constructor argument.

How to declare a Foo instance in an XML bean XML file?

+7
java spring lambda java-8
source share
1 answer

My proposed solution below is probably not the best idea, but I found the question interesting and decided to try to give it a chance. This is the best I could think of.

I don’t know if there is a way to do this directly at this moment (besides defining some kind of factory bean), but as an alternative, you can do this using dynamic language support, for example, using Groovy.

In the following example, the latest version of Spring was used for me (today 4.1.6)

Suppose 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 the XML configuration, for example:

 <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 a method reference, but any method reference can be expressed using lambda / closure, as I did above.

+1
source share

All Articles