在Gradle Spring Boot项目中,如何声明仅在本地运行时使用的依赖项?

时间:2018-12-17 21:44:15

标签: java spring spring-boot gradle spring-jdbc

我有一个用Gradle构建的Spring Boot应用程序,该应用程序连接到数据库。在本地运行时,通常更方便的是在内存数据库(在这种情况下为h2)中运行,而不是连接到数据库的实际实例。为此,应用程序声明了一个自定义sudo update-alternatives --config java 任务,用于在本地运行该应用程序。如何在本地运行时确保h2依赖关系可用,但不包含在生成的Spring Boot jar中?

文件:

build.gradle

./logstash -f ../your-logstash-file.conf

application.yml

BootRun

test / BootApplication.java

import org.springframework.boot.gradle.tasks.run.BootRun

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.5.RELEASE")
    }
}

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.1.1.RELEASE'
    id "io.spring.dependency-management" version "1.0.6.RELEASE"
}

group 'test'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile "org.springframework.boot:spring-boot-starter-web"
    compile "org.springframework.boot:spring-boot-starter-jdbc"

    // compile "..." // Dependency for the real, non-in memory, database goes here

    compile "com.h2database:h2" // How can I make sure this isn't included in the resulting jar?
}

task bootRunLocal(type: BootRun, group: ApplicationPlugin.APPLICATION_GROUP, dependsOn: classes) {
    main = 'test.BootApplication'
    classpath = sourceSets.main.runtimeClasspath

    systemProperty "spring.profiles.active", "local-db-h2"
}

1 个答案:

答案 0 :(得分:1)

我当前实现的解决方案将custom Gradle configuration用于h2依赖项。

build.gradle

spring:
  datasource:
    # Default and non-in-memory datasource configuration goes here
---
spring:
  profiles: local-db-h2
  datasource.url: jdbc:h2:mem:testdb;MODE=Oracle
  datasource.platform: h2_local