Spring Integration DSL routing based on message header in Kotlin

30 Views Asked by At

My message contains String and I want route messages based on header, likes bellow:

            .route<Message<String?>, String> {
                when (it.headers["routing_header"] as Int) {
                    1 -> "channel_1"
                    2 -> "channel_2"
                    else -> "nullChannel"
                }
            }

In this case I have error in cast String

Caused by: java.lang.ClassCastException: class java.lang.String cannot be cast to class org.springframework.messaging.Message

What is wrong in my routing?

1

There are 1 best solutions below

1
Artem Bilan On

You have to look into dedicated Spring Integration Kotlin DSL: https://docs.spring.io/spring-integration/reference/kotlin-dsl.html

That route could be configured like this:

                route<Message<String?>> {
                    when (it.headers["routing_header"] as Int?) {
                        1 -> "channel_1"
                        2 -> "channel_2"
                        else -> "nullChannel"
                    }
                }

Pay attention to the fix for Int? since your header might be missed and will be returned as null.

If you are still suck with combination of Java DSL in Kotlin, then probably the fix is like this:

                        .route(Message::class.java) {
                            when (it.headers["routing_header"] as Int?) {
                                1 -> "channel_1"
                                2 -> "channel_2"
                                else -> "nullChannel"
                            }
                        }

Java does generics erasure, so we don't know that Message type expectation at runtime. Therefore Java variant wants from us that type explicitly, while Kotlin one does reified typing.