代码之家  ›  专栏  ›  技术社区  ›  ip696

对每个方法调用使用newInstance()创建jaxbcontext的正确性是多少?

  •  0
  • ip696  · 技术社区  · 6 年前

    在spring boot项目中,我创建了jaxbcontext bean:

    @Configuration
    public class MarshallerConfig {
    
        @Bean
        JAXBContext jaxbContext() throws JAXBException {
            return JAXBContext.newInstance(my packages);
        }
    }
    

    我创建了用于此上下文的包装器:

    @Component
    public class MarshallerImpl implements Marshaler {
    
        private final JAXBContext jaxbContext;
    
        public MarshallerImpl(JAXBContext jaxbContext) {
            this.jaxbContext = jaxbContext;
        }
    
         //murshall and unmarshal methosds imlementation
        }
    

    当我创造 JAXBContext 就像豆子-我知道 贾克斯文 将是辛格尔顿。但现在我需要在没有 @XMLRootElement 注释。我是这样实现的 article

    @Override
    public <T> String marshalToStringWithoutRoot(T value, Class<T> clazz) {
        try {
            StringWriter stringWriter = new StringWriter();
    
            JAXBContext jc = JAXBContext.newInstance(clazz);
            Marshaller marshaller = jc.createMarshaller();
            // format the XML output
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
    
            QName qName = new QName(value.getClass().getPackage().toString(), value.getClass().getSimpleName());
            JAXBElement<T> root = new JAXBElement<>(qName, clazz, value);
    
            marshaller.marshal(root, stringWriter);
    
            return stringWriter.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    

    我创造 贾克斯文 入法 JAXBContext jc = JAXBContext.newInstance(clazz); .

    有多正确?每次使用 newInstance ?

    我看了一下这个方法,没有发现它是一个单一的。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Thomas Fritsch    6 年前

    因为创建 JAXBContext 很费时, 你应该尽量避免。

    您可以通过将它们缓存在 Map<Class<?>, JAXBContext> .

    private static Map<Class<?>, JAXBContext> contextsByRootClass = new HashMap<>();
    
    private static JAXBContext getJAXBContextForRoot(Class<?> clazz) throws JAXBException {
        JAXBContext context = contextsByRootClass.get(clazz);
        if (context == null) {
            context = JAXBContext.newInstance(clazz);
            contextsByRootClass.put(clazz, context);
        }
        return context;
    }
    

    最后,在你的 marshalToStringWithoutRoot 可以替换的方法

    JAXBContext jc = JAXBContext.newInstance(clazz);
    

    通过

    JAXBContext jc = getJAXBContextForRoot(clazz);