Say I have this class:
public class FooToBarTransformer { public Bar transform(Foo foo) {
And I want to use it as Function in some other class:
public class Thing { public Thing(Function<Foo, Bar> f) { this.converter = f; } }
Now, if I create Thing through Java, I would do it using Java8 Lambdas as follows:
FooToBarTransformer transformer = new FooToBarTransformer(); new Thing((foo) -> transformer.transform(foo)); // or new Thing(transformer::transform);
My problem is that I need to create Thing though spring .
<bean id="fooToBarTransformer" class="com.mypackage.FooToBarTransformer"/> <bean id="theThing" class="com.mypackage.Thing"> <constructor-arg index="0" ????????? /> </bean>
Now there are several possible workarounds that I decided to make easier:
- If
FooToBarTransformer implemented by Function , then it will just be ref="fooToBarTransformer" - I could create another interface that
FooToBarTransformer implements and modifies Thing to take an instance of this interface instead of Function . For the purposes of this question, none of them is a parameter.
Based on some other methods that I saw when executing executions in spring xml, I tried value="#{(foo) -> fooToBarTransformer.transform(foo)}" and value="#{fooToBarTransformer::transform}" , but spring rustled on this.
The best option I came with is to provide a translation function in code:
public Function<Foo, Bar> toFunction() { return transformer::transform; }
and refer to it in spring at value="#{fooToBarTransformer.toFunction()}" , but that seems pretty hokey.
Is there a better way to do this?
source share