引用xjc生成的文件的正确方法是什么

问题描述 投票:0回答:1

我刚刚使用 jaxb xjc 自动生成一个类,这样我就可以在我的 Java 项目中编组和解组 xml 属性。我通过将以下内容添加到我的 POM 中来完成此操作

      <plugin>
        <groupId>org.jvnet.jaxb</groupId>
        <artifactId>jaxb-maven-plugin</artifactId>
        <version>4.0.6</version>
        <executions>
          <execution>
            <goals>
              <goal>generate</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <schemaDirectory>src/main/resources/XSD</schemaDirectory>
          <schemaIncludes>
              <include>*.xsd</include>
          </schemaIncludes>
        </configuration>
      </plugin>

这似乎有效,并在 target/ generated-resources/jaxb/mymainpackagepath/myschema 中生成了一个名为 Person.java 的类文件

我不确定如何实际使用它。在我的主类中,如果我尝试

import org.myname.myschema.Person
,我会收到错误:“导入 org.myname.myschema 无法解析Java(268435846)”。我确信有一种正确的方法来引用生成的资源,但我在 jaxb 文档或其他任何地方都找不到任何内容。

java maven jaxb xjc
1个回答
0
投票

您生成的源代码不在您的编译源路径中。我自己使用maven插件,并像这样配置插件,将生成的源放在

src/main/generated-java
中:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <id>xjc</id>
            <goals>
                <goal>xjc</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <xjbSources>
            <xjbSource>src/main/resources/global.xjb</xjbSource>
        </xjbSources>
        <sources>
            <source>src/main/resources/user.xsd</source>
        </sources>
        <outputDirectory>${basedir}/src/main/generated-java</outputDirectory>
        <clearOutputDir>true</clearOutputDir>
    </configuration>
</plugin>

然后,要将该路径包含在编译源路径中,另一个插件:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>3.2.0</version>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>src/main/generated-java</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

这适用于idea,因为idea会检查maven的配置来找出源路径、库等。我不知道它如何与VSCode一起工作。

另请注意:您使用的是 jaxb1,但源路径配置将是相同的。

© www.soinside.com 2019 - 2024. All rights reserved.