Marc Tarin
Marc Tarin

Reputation: 3169

Spring Integration DSL: handle vs enrichHeaders

I have an integration flow where I use a handler to add a few headers to my message:

...
.handle(this, "enrichTaskHeaders")
...

public Message<?> enrichTaskHeaders(Map<String, String> payload) {
    var id = payload.get("id");
    var t = service.findById(id);

    return MessageBuilder.withPayload(payload).setHeader("a", t.getA())
                                              .setHeader("b", t.getB())
                                              .setHeader(...)
                         .build();
}

It works perfectly, but since it's about enriching headers, I was wondering if I could use a enrichHeaders method to do the same thing. The closest I could get to is this:

.enrichHeaders(consumer -> consumer.headerFunction("a",
        (Message<Map<String, String>> m) -> {
            var id = m.getPayload().get("id");
            var t = service.findById(id);
            return t.getA();})
                                   .headerFunction("b",
        (Message<Map<String, String>> m) -> {
            var id = m.getPayload().get("id");
            var t = service.findById(i));
            return t.getB();})

        ...
)

It works as intended, but it is obviously underefficient since I duplicate a service call for each header I add. Is there a way to rewrite it efficiently or should I just go with the handler?

Upvotes: 0

Views: 418

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121542

See enrich(Consumer<EnricherSpec> enricherConfigurer) instead. It has an option like requestPayload() to have that your service call only once. And then you use a .headerFunction() for your purposes.

            .enrich(e -> e
                        .<Map<String, String>>requestPayload(m -> "v")
                        .headerFunction("a", m -> m.getPayload().getA())
                        .headerFunction("b", m -> m.getPayload().getB()))

See more in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/message-transformation.html#payload-enricher

Upvotes: 1

Related Questions