我目前正在尝试使用 EclipseLink Moxy 作为我的 JAXB 实现。我正在尝试这个,因为 JDK 中包含的默认实现似乎具有 UTF-8 编码的硬编码缩进级别 8。
我的问题是,我似乎必须将 jaxb.properties 文件放入每个包含 JAXB POJO 的包中。我的 JAXB POJO 由 xjc 生成,特别是由“jaxb2-maven-plugin”生成。 POJO 生成为许多包。是否可以以某种方式设置所使用的实现,而无需在这些包中创建冗余的 jaxb.properties 文件?
最佳答案
I am trying this, because the default implementation included in the JDK seems to have a hard coded indentation level of eight with UTF-8 encoding.
JAXB 引用实现确实有一个扩展属性,允许您控制缩进:
至jaxb.properties
,当使用单个 JAXBContext
处理多个包时只有其中一个包需要包含 jaxb.properties
文件。
可以采取一些不同的措施来让您更轻松地使用 MOXy:
使用 MOXy 的 XJC 包装器
MOXy 提供了一个包装 XJC 的脚本,该脚本将添加 jaxb.properties
文件放在适当的位置。
<ECLIPSELINK_HOME>/bind/jaxb-compiler.sh
使 MOXy 成为您环境中的默认 JAXB 提供程序
您还可以利用 META-INF/services
将 MOXy 指定为默认 JAXB 提供程序的机制:
- 创建一个 JAR,其中包含名为
javax.xml.bind.JAXBContext
的文件在目录META-INF/services
javax.xml.bind.JAXBContext
的内容文件必须是org.eclipse.persistence.jaxb.JAXBContextFactory
- 将该 jar 添加到您的类路径中。
使用 native MOXy API
import java.io.File;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContextFactory.createContext("com.example.pkg1:org.example.pkg2", null, null);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("input.xml");
Object object = unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(object, System.out);
}
}
关于maven - 使用 Moxy 作为 JAXB 实现并使用多个 POJO 包设置 jaxb.properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26403145/