In spring boot project I create JAXBContext bean:
@Configuration
public class MarshallerConfig {
@Bean
JAXBContext jaxbContext() throws JAXBException {
return JAXBContext.newInstance(my packages);
}
}
And I create Wrapper for use this context:
@Component
public class MarshallerImpl implements Marshaler {
private final JAXBContext jaxbContext;
public MarshallerImpl(JAXBContext jaxbContext) {
this.jaxbContext = jaxbContext;
}
//murshall and unmarshal methosds imlementation
}
When I create JAXBContext
like bean - I know that this JAXBContext
will be singleton. But Now I need implement marhall method for marshall element without @XMLRootElement
annotation. I Implement it like in this 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());
}
}
I create JAXBContext
into method JAXBContext jc = JAXBContext.newInstance(clazz);
.
How correct is it? every time create an object using newInstance
?
I looked a little inside this method and did not see that it was a singleton.