1

我使用消息转换器将 XML 消息从队列转换为 Java 对象,它工作正常。

由于我的 JMSMessageListener 直接获取 POJO,我想知道有什么方法可以访问最初放在队列中的原始 XML。

作为消息跟踪的一部分,我需要维护原始 xml 消息的副本。

spring jms 中是否有任何回调可用,以便我可以在将 xml 消息转换为 POJO 之前对其进行保留?

我的应用程序是 spring boot,我在下面的代码中配置消息转换器

@Configuration
@EnableJms
public class JMSConfig {

    @Bean
    public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory,
            DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        // This provides all boot's default to this factory, including the message
        // converter
        configurer.configure(factory, connectionFactory);
        // You could still override some of Boot's default if necessary.
        return factory;
    }

    @Bean
    public MarshallingMessageConverter createMarshallingMessageConverter(final Jaxb2Marshaller jaxb2Marshaller) {
        return new MarshallingMessageConverter(jaxb2Marshaller);
    }

    @Bean
    public Jaxb2Marshaller createJaxb2Marshaller() {
        Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();

        jaxb2Marshaller.setPackagesToScan("com.mypackage.messageconsumer.dto");

        Map<String, Object> properties = new HashMap<>();
        properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxb2Marshaller.setMarshallerProperties(properties);

        return jaxb2Marshaller;
    }
}

这是监听器代码

@Component
public class NotificationReader {

    @JmsListener(destination = "myAppQ")
    public void receiveMessage(NotificationMessage notificationMessage) {
        System.out.println("Received <" + notificationMessage.getStaffNumber() + ">");
        // how to get access to the raw xml recieved by sender ? 
        persistNotification(notificationMessage);
    }
4

1 回答 1

3

像这样的东西应该工作......

@Bean
public MarshallingMessageConverter createMarshallingMessageConverter(final Jaxb2Marshaller jaxb2Marshaller) {
    return new MarshallingMessageConverter(jaxb2Marshaller) {

        @Override
        public Object fromMessage(Message message) throws JMSException, MessageConversionException {
            Object object = super.fromMessage(message);
            ((MyObject) object).setSourceXML(((TextMessage) message).getText());
            return object;
        }

    }
}

...但是您应该添加更多检查(例如,在转换之前验证类型)。

于 2018-01-01T15:11:59.100 回答