我可以用代码替换 jaxb.properties 吗? [英] Can I replace jaxb.properties with code?

查看:68
本文介绍了我可以用代码替换 jaxb.properties 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些非-standard extensions 来自 EclipseLink 的 JAXB 实现,为了启用该实现,我必须使用 jaxb.properties 配置它.效果很好.

I am using some non-standard extensions from EclipseLink's implementation of JAXB, and to enable that implementation, I have to configure it using jaxb.properties. Works well.

然而,由于构建错误,properties文件没有包含在适当的位置,导致使用默认的JAXB,没有任何错误只是继续解析XML文件,忽略非标准扩展名,离开我有一个非工作 bean.

However, due to a build error, the properties file was not included in the proper place, resulting in the default JAXB being used, which without any errors just continued to parse the XML file, ignoring the non-standard extension, leaving me with a non-working bean.

为了使它更健壮,我想摆脱属性文件并在代码中指定上下文配置.由于它们的注释,我已经对 EclipseLink 产生了编译时依赖,而且我不需要在部署时对这部分进行配置(实际上,看看会出现什么问题,我不想对其进行配置).

To make this more robust, I'd like to get rid off the properties file and specify the context configuration in code. I already have a compile-time dependency on EclipseLink because of their annotations, and I do not need this part configurable at deploy time (in fact, seeing what can go wrong, I do not want it configurable).

推荐答案

您可以执行以下操作以获得 EclipseLink JAXB (MOXy) JAXBContext 而无需 jaxb.properties文件:

You could do the following to get an EclipseLink JAXB (MOXy) JAXBContext without a jaxb.properties file:

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.eclipse.persistence.jaxb.JAXBContextFactory;

public class Demo {

    public static void main(String[] args) throws Exception {
        //JAXBContext jc = JAXBContext.newInstance(Animals.class);
        JAXBContext jc = JAXBContextFactory.createContext(new Class[] {Animals.class}, null);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum6871469/input.xml");
        Animals animals = (Animals) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(animals, System.out);
    }

}

这篇关于我可以用代码替换 jaxb.properties 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆