Spring JMS - 在消息转换之前访问原始消息

问题描述 投票:1回答:1

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

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

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

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

我的应用程序是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);
    }
spring spring-jms spring-oxm
1个回答
1
投票

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

@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;
        }

    }
}

...但您应该添加更多检查(例如,在投射前验证类型)。

© www.soinside.com 2019 - 2024. All rights reserved.