【问题标题】:Gradle do not aware about custom autoconfiguration library - tests fails in Gradle, but successful in IDEGradle 不知道自定义自动配置库 - 在 Gradle 中测试失败,但在 IDE 中成功
【发布时间】:2019-12-22 13:03:40
【问题描述】:

我正在创建自定义启动器并希望添加将演示自动配置并对其进行测试的示例应用程序。但是当我在控制台中运行./gradlew test 时,Gradle 似乎不知道META-INF/spring.factories

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. 

这是我的示例应用build.gradle,它是多模块项目中的模块:

plugins {
    id 'org.jetbrains.kotlin.jvm'
    id 'org.jetbrains.kotlin.plugin.spring'
    id 'org.jetbrains.kotlin.plugin.jpa'
    id 'org.springframework.boot'
    id 'io.spring.dependency-management'
}

dependencies {
    implementation project(':custom-spring-boot-starter')
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation "org.flywaydb:flyway-core:5.2.4"
    implementation 'com.h2database:h2:1.4.197'
    // Test
    testImplementation "org.springframework.boot:spring-boot-starter-test"
    testImplementation 'org.springframework.boot:spring-boot-test-autoconfigure:2.1.7.RELEASE'
    testImplementation "org.hamcrest:hamcrest:2.1"
    testImplementation "org.testng:testng:6.14.3"
    testImplementation "com.github.javafaker:javafaker:0.17.2"
    testImplementation "org.awaitility:awaitility:3.0.0"
}

test {
    useTestNG()
    jacoco {
        destinationFile = file("$rootDir/build/jacoco/test.exec")
    }
}

这是一个简单的 Spring Boot 应用程序:

@SpringBootApplication
class Application

fun main(args: Array<String>) {
    SpringApplication.run(Application::class.java, *args)
}

我为所有上下文测试配置基类,如下所示:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
abstract class ApplicationTest : AbstractTestNGSpringContextTests() {

    @Autowired
    lateinit var restTemplate: TestRestTemplate

    @LocalServerPort
    private var port: Int = 0

    fun getRequest(uri: String, responseType: Class<*>) =
        restTemplate.getForEntity("http://localhost:$port$uri", responseType)
}

那么,如何在 Gradle 命令执行下应用自定义自动配置?

【问题讨论】:

  • 看起来您是在使用自定义任务在 gradle 中自己创建可执行 jar,还是依赖于 gradle spring boot 插件?
  • @Shailendra,用于创建简单 jar 的自定义任务。如果我尝试 bootJar 任务会导致错误,因为 starter 没有主类。
  • @Autowired 可能需要@Qualifier

标签: java spring spring-boot gradle kotlin


【解决方案1】:

在官方 Spring 指南here(源代码here)中查看 Spring boot 多模块项目,他们使用了自定义 jar 任务(“库”模块)。如果您运行“gradle build”,则生成的工件位于库 module --&gt; libs 文件夹中。这是没有主类的 Spring Boot 库。另一个模块(“应用程序”)当然是使用简单自定义“bootJar”任务的主应用程序。这两个模块都包含测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    相关资源
    最近更新 更多