![](/img/trans.png)
[英]Adding XMLAdapter causes NullPointerException in JAXBContext.newInstance method
[英]how much is it right to create JAXBContext using newInstance() with each method call?
在春季启动项目中,我创建了JAXBContext bean:
@Configuration
public class MarshallerConfig {
@Bean
JAXBContext jaxbContext() throws JAXBException {
return JAXBContext.newInstance(my packages);
}
}
我创建了Wrapper来使用此上下文:
@Component
public class MarshallerImpl implements Marshaler {
private final JAXBContext jaxbContext;
public MarshallerImpl(JAXBContext jaxbContext) {
this.jaxbContext = jaxbContext;
}
//murshall and unmarshal methosds imlementation
}
当我像bean创建JAXBContext
-我知道这个JAXBContext
将是单例的。 但是现在我需要在没有@XMLRootElement
批注的情况下为marshall元素实现marhall方法。 我像本文一样实现
@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
创建为方法JAXBContext jc = JAXBContext.newInstance(clazz);
。
有多正确? 每次使用newInstance
创建对象吗?
我在此方法中稍稍看了一眼,没有看到它是一个单例。
由于创建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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.