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.
Edwin dalorzo
source share