在spring boot v1.3.3中将java bean转换为xml
由于创建jaxbcontext对象比较耗时,所以将该对象注入进来使用
@Bean public JAXBContext wxOrderJAXBContext() throws JAXBException { return JAXBContext.newInstance(MyBean.class); }
然后使用Marshaller将对象转为xml
Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
StringWriter writer = new StringWriter(); marshaller.marshal(myBean, writer);
原本是打算将marshaller对象注入进来的,但是网上有人说marshaller is not thread safe. 所以改为注入JAXBContext, 性能上相差无几。
在main方法中测试,每100次转换耗时在1ms左右