为 JAXB 生成的类添加前缀 [英] Prefixing JAXB generated classes

查看:33
本文介绍了为 JAXB 生成的类添加前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 Maven任务"来使用 JAXB 从 XSD 文件生成 Java 类.

I have this Maven "task" to generate Java classes from an XSD file using JAXB.

        <!-- XML to Java classes -->
        <plugin>
            <groupId>com.sun.tools.xjc.maven2</groupId>
            <artifactId>maven-jaxb-plugin</artifactId>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <generatePackage>nl.compay.service</generatePackage>
                <schemaDirectory>src/main/webapp/compay</schemaDirectory>
            </configuration>
        </plugin>

对于 XSD 类型User",它生成一个名为User"(废话)的类.但是,我还有一个名为User"的 JPA 实体类(尽管在不同的包中).我可以更改上面的 XML 配置,让 JAXB 在生成的类前面加上XML"之类的前缀吗?

For an XSD type "User", it generates a class named "User" (duh). However, I also have a JPA entity class called "User" (though in a different package). Can I change the XML config above to let JAXB prefix the generated classes with something like "XML"?

推荐答案

这是一个常见的要求.您可以通过提供额外的 JAXB 绑定文件来自定义 JAXB 如何将 Schema 类型名称转换为 Java 类名称.

This is a common requirement. You can do that by providing an additional JAXB binding file to customize how JAXB translates the Schema type names into Java class names.

这些文件通常以扩展名.xjb"结尾.您需要为您的架构创建一个,例如:

These files normally end in extension ".xjb". You need to create one for your schema, for example:

<jxb:bindings version="1.0" 
  xmlns:jxb="http://java.sun.com/xml/ns/jaxb" 
  xmlns:xs="http://www.w3.org/2001/XMLSchema" 
  xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" 
  jxb:extensionBindingPrefixes="xjc">

    <jxb:bindings schemaLocation="nl.company.service.xsd" node="/xs:schema">
        <jxb:schemaBindings>
            <jxb:nameXmlTransform>
                <jxb:typeName prefix="XML"/>
                <jxb:anonymousTypeName prefix="XML"/>
            </jxb:nameXmlTransform>
        </jxb:schemaBindings>
    </jxb:bindings>

</jxb:bindings>

完成后,将 xjb 文件放在构建目录中的某个位置,并告诉 Maven 在翻译期间使用它:

After you've done that, drop the xjb file somewhere in your build directory and tell Maven to make use of it during translation:

<includeBindings>
    <includeBinding>mybindings.xjb</includeBinding>
</includeBindings>

这里有一个提示:如果你在一个包含空格的路径中(例如文档和设置\用户\项目"),那么 JAXB 会因为奇怪的错误而失败.

And here's a hint for the road: if you are in a path that contains spaces (e.g. "Documents and Settings\user\project") then JAXB will fall over with strange errors.

这篇关于为 JAXB 生成的类添加前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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