I have a need to apply some pre-checks and common steps on the all the jms listeners like validating the raw message against a schema (JSON schema). Example -
@Component
public class MyService {
@JmsListener(destination = "myDestination")
public void processOrder(Order order) { ... }
}
Now, before the spring converts the Message from the queue to Order, I need to do the following -
- log the original message with headers into a custom logger.
- validate the json message (text message) against a json schema (lets assume I have only one schema here for the simplicity)
- If schema validation fail, log the error and throw exception
- If schema validation passes, continue to control to spring to do the conversion and continue with the process order method.
Does the spring JMS architecture provides any way to inject the above need? I know AOP crosses the mind, but I am not sure will it work with @JmsListener.
A rather simple technique would be to set
autoStartuptofalseon the listener container factory.Then, use the
JmsListenerEndpointRegistrybean to get the listener container.Then
getMessageListener(), wrap it in an AOP proxy andsetMessageListener().Then start the container.
There might be a more elegant way, but I think you'd have to get into the guts of the listener creation code, which is quite involved.
EDIT
Example with Spring Boot:
and
and
EDIT2
Here's how to do it via infrastructure...
Note: the BPP must be static and
@EnableJmsis required since the presence of this BPP disables boot's.EDIT3
Avoiding AOP...
EDIT4
To access other annotations on the listener method, it can be done, but reflection is needed to get a reference to the
Method...