Jaxb封送相同的XML消息

时间:2019-10-20 04:23:17

标签: java xml jaxb

我正在使用Jaxb来编组和解组对象。这是我的自定义类的代码。

import test.org.swt.SwitchMsg;
import test.org.swt.TrxMsg;
import org.springframework.context.annotation.Configuration;
import org.springframework.xml.transform.StringSource;

import javax.annotation.PostConstruct;
import javax.xml.bind.*;
import java.io.StringWriter;

@Configuration
public class JaxbConfig {

    private JAXBContext jaxbContext;

    @PostConstruct
    private void init(){
        try {
            jaxbContext = JAXBContext.newInstance(
                    SwitchMsg.class,
                    TrxMsg.class,
            );

        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    public <T> T unmarshal(String xmlString, Class<T> clazz) {
        try {
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            JAXBElement<T> element = unmarshaller.unmarshal(new StringSource(xmlString), clazz);

            return element.getValue();

        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    public String marshal(Object object) {
        try {
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

            StringWriter stringWriter = new StringWriter();
            marshaller.marshal(object, stringWriter);
            return stringWriter.toString();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}

这是我用于解组和编组的代码。如您所见,我使用unmarshall()方法创建TrxMsg对象,然后使用数据调用另一个返回TrxMsg对象的方法。但是,当我再次将其编组时,我又将旧物件取回。不是新的。我希望我的代码注释可以阐明更多。我需要知道为什么会这样以及如何解决。预先感谢。

private void processTransaction(ChannelHandlerContext ctx, String payload){

        String logMsg = payload;

        log.debug("Request received: \n{}", logMsg);

        //(1) 
        //I get a TrxMsg object by unmarshalling - Works perfectly fine
        TrxMsg trxMsg = jaxbConfig.unmarshal(payload, TrxMsg.class);
        Request request = new Request();

        SwitchMsg switchMsg = trxMsg.getMsg();

        request.setMessageId(switchMsg.getMessageId());
        request.setMessage(switchMsg);

        Response response = routerService.send(request);

        //response.getResponse() also returns a TrxMsg object but I get the same object 
        //I got in (1).
       //This TrxMsg object has different values. I tested in Logs
        String res = jaxbConfig.marshal(response.getResponse());

        log.info("Sending response: \n{}", res);
        final ByteBuf responseBuf = Unpooled.wrappedBuffer(res.getBytes(StandardCharsets.UTF_8));

        ChannelFuture future = ctx.writeAndFlush(responseBuf);
        future.addListener(ChannelFutureListener.CLOSE);
    }

0 个答案:

没有答案
相关问题