Search code examples
springspring-integrationdsl

Spring-Integration DSL transform() method using name of a bean as the transformer


When creating an IntegrationFlow that uses from() or channel() or gateway(), I can refer to a channel by simply giving the String name of the channel. However, with a transform() operation using transformers that are beans, I have to include those Autowired beans in the constructor. This can be fastidious when then are a large number of transformations in the flow.

Is there a simple way of referring to a Bean used by a transform() without autowiring the bean in the constructor?

@Component
public class DoubleIntegerValueTransformer implements GenericTransformer<Integer, Integer> {
    @Override
    public Integer transform(Integer source) {
        return source * 2;
    }
}
@Component
public class AutowiredTransformerFlows {

    // Would like to eliminate the constructor and local instance variable
    private final DoubleIntegerValueTransformer doubleIntegerValueTransformer;

    public AutowiredTransformerFlows(DoubleIntegerValueTransformer doubleIntegerValueTransformer) {
        this.doubleIntegerValueTransformer = doubleIntegerValueTransformer;
    }

    @Bean(name = "autowiredTransformerFlow")
    IntegrationFlow usesBeanAsTransformer() {
        return IntegrationFlows.from("autowiredTransformChannel")
                .filter("(payload % 2) == 1", discardReturnsCurrentMessage())
                .transform(doubleIntegerValueTransformer)
                .get();
    }
}

Solution

  • Just add a parameter to the bean factory method:

    @Bean(name = "autowiredTransformerFlow")
    IntegrationFlow usesBeanAsTransformer(DoubleIntegerValueTransformer doubleIntegerValueTransformer) {
        return IntegrationFlows.from("autowiredTransformChannel")
                .filter("(payload % 2) == 1", discardReturnsCurrentMessage())
                .transform(doubleIntegerValueTransformer)
                .get();
    }
    

    The bean should be in a @Configuration class, not a @Component class.