In my Spring project I use a channel interceptor (registered with @GlobalChannelInterceptor annotation) to intercept messages on all channels. I want this interceptor to behave in a different way for different channels - for instance, for some channels it shoud add a header A, for some other channels it should add header B, etc. Of course, I could just use several different interceptors (one which adds header A, another which adds header B etc) registered for different channels, but in my case it's impossible. It's impossible, because I want this decision - which headers should be added for which channels - to be configurable. So now, when I write the code, I don't even know how many interceptors I would need, because this will be decided by the configuration. So I would like to have one interceptor and in its preSend method somehow check what is the channel name on which the current message is being sent, and then depending on this channel name make a decision which header should be added.
Is it possible? Is it possible for preSend method of a channel interceptor to know the channel name? Or is there any other way to achieve my goal?
CodePudding user response:
See preSend()
signature:
default Message<?> preSend(Message<?> message, MessageChannel channel)
Pay attention to that channel
arg.
Normally, when ChannelInterceptor
is used from the dependency injection Spring container, it is applied to MessageChannel
beans. And if you deal with standard Spring Integration channels, then all of them are instances of NamedComponent
.
So, you just need to cast that channel
arg to NamedComponent
and call its getBeanName()
in your preSend()
impl.
You may also double check with instanceof
before casting because in core Spring Messaging their MessageChannel
impl does not provide a hook to get bean name.
Another concern, if you apply such an interceptor to non-bean MessageChannel
, so its bean name is also null
.