【问题标题】:Spring Boot useTestClasspath throws CannotLoadBeanClassException and ClassNotFoundExceptionSpring Boot useTestClasspath 抛出 CannotLoadBeanClassException 和 ClassNotFoundException
【发布时间】:2016-10-17 19:44:07
【问题描述】:

我有一个 Maven 项目,其测试类位于 src/test/java/MyDevClass,仅用于开发/测试目的。我想在使用命令行mvn spring-boot:run 启动spring-boot-maven-plugin 时使用它。

所以,我的pom.xml 包含:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <!-- TODO: Will create a maven profile and have useTestClasspath only for development/testing -->
                <useTestClasspath>true</useTestClasspath>
            </configuration>
        </plugin>
    </plugins>
</build>

但是,我收到以下错误:

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [MyDevClass]
Caused by: java.lang.ClassNotFoundException: MyDevClass

有趣的是,我有另一个使用tomcat7-maven-plugin 的项目,它工作正常:

        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.0</version>
            <configuration>
                <useTestClasspath>true</useTestClasspath>
            </configuration>
        </plugin>

我错过了什么?

【问题讨论】:

  • 我不明白。当它是测试类时,为什么要在生产环境中注册它?没有意义。
  • 嗨@luboskrnac。正确,我不希望它在生产中。我将为此创建一个 Maven 配置文件。
  • 嗨斯蒂芬尼科尔,没问题。为了简单起见,我保留了默认包。

标签: spring-boot maven-plugin


【解决方案1】:

即使 useTestClasspath 设置为 true,Spring-boot maven 插件也不会将当前模块的测试源(和资源)包含到类路径中。

我使用详细日志记录(-X 标记 Maven)运行分叉执行,插件列出了分叉的 JVM 类路径。不包括测试类。

如果您查看插件sources(撰写本文时版本为1.5.3),useTestClasspath 标志仅用于addDependencies 方法。

我认为有两种解决方法

  1. target/test-classes 目录添加到运行类路径:

    <directories>
      <directory>${project.build.testOutputDirectory}</directory>
    </directories>
    

    对于旧插件版本使用:

    <folders>
      <folder>${project.build.testOutputDirectory}</folder>
    </folders>
    

    这里的问题是文件夹被添加到类路径的开头,而测试文件最好放在它的末尾。

  2. 使用测试类和资源创建另一个 Maven 模块,并将其添加为 &lt;scope&gt;test&lt;/scope&gt; 依赖项。

【讨论】:

  • 我最终做了类似于你的建议 #2 的事情
猜你喜欢
  • 2021-12-30
  • 2018-08-18
  • 2016-04-10
  • 2019-05-29
  • 2015-03-28
  • 2017-08-01
  • 2021-03-10
  • 2018-08-15
  • 1970-01-01
相关资源
最近更新 更多