JAXB creating context and marshallers cost

后端 未结 8 2137
情深已故
情深已故 2020-11-28 02:00

The question is a bit theoretical, what is the cost of creating JAXB context, marshaller and unmarshaller?

I\'ve found that my code could benefit from keeping the sa

8条回答
  •  野性不改
    2020-11-28 02:30

    Creating JAXBContext within a enum and accessing it within application Thread to create Marshaller/Unmarshaller will suffice.

    public enum MyApplicationJAXBContext {
    
        REQ(Request.class), RESP(Response.class);
    
        private final JAXBContext jaxbContext;
    
        MyApplicationJAXBContext(Class contextClass) {
    
            try {
                jaxbContext = JAXBContext.newInstance(contextClass);
            } catch (JAXBException e) 
                throw new RunTimeException(e);
               // Lets caller decide what to do ?
            }
        }
    
        public JAXBContext getJaxbContext() {
            return jaxbContext;
        }
    }
    
    
    public class MyAppCallable implements Callable {
    
    private final Request req;
    public MyAppCallable(Request req) {
        this.req = req;
    }
    
    
    public Response call() {
    
    Marshaller marshaller = MyApplicationJAXBContext.REQ.getJaxbContext().createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    // Anything else you want to configure properties
    Unmarshaller unmarshaller = MyApplicationJAXBContext.RESP.getJaxbContext().createUnmarshaller();
    
    /** 
    All other logic you want to do after req/rsp usage and return Response
    **/
    
    }
    
    }
    

提交回复
热议问题