我应该为每个新请求创建一个unmarshaller吗?

时间:2017-03-15 07:59:19

标签: jaxb

我正在开发一个使用XML的jax-rs Web服务。由于业务需求,我需要XML和unmarshalled java对象。因此,我不是将java类型添加为方法参数,而是使用String作为类型并将XML流注入到字符串中。

private static JAXBContext context;
public StudentFacade() throws JAXBException {
    if(context == null) {
        context = JAXBContext.newInstance(Student.class);
    }
}

@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response sendSms(final String xml) throws JAXBException {
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new ByteArrayInputStream(xml.getBytes()));
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.unmarshal(xsr);
    ....
}

我的问题是,我应该始终创建一个新的XMLInputFactory和Unmarshaller吗?

如果我将XMLInputFactory和Unmarshaller移动到构造函数并且只像JAXBContext一样初始化它们,则以下代码是否有效

private static  Unmarshaller unmarshaller;
private static XMLInputFactory xif;
    public StudentFacade() throws JAXBException {
        if(unmarshaller == null) {
            JAXBContext context = JAXBContext.newInstance(Student.class);
            unmarshaller = context.createUnmarshaller();
            xif = XMLInputFactory.newFactory();
        }
    }

@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response sendSms(final String xml) throws JAXBException {

    XMLStreamReader xsr = xif.createXMLStreamReader(new ByteArrayInputStream(xml.getBytes()));

    unmarshaller.unmarshal(xsr);
    ....
}

0 个答案:

没有答案
相关问题