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

In a Gradle Spring Boot project, how can I declare dependencies to only be used when running locally?

我有一个 Spring 使用 Gradle 构建的连接到数据库的引导应用程序。当 运行 在本地连接时,在内存数据库中 运行 通常更方便(在本例中,h2),而不是连接到数据库的真实实例。为此,应用程序声明了一个自定义 BootRun 任务,用于 运行 在本地应用程序。如何确保 h2 依赖项在本地 运行ning 时可用,但不包含在生成的 Spring 引导 jar 中?

文件:

build.gradle

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"
}

application.yml

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

test/BootApplication.java

package test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

@SpringBootApplication
public class BootApplication implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public static void main(String[] args) {
        SpringApplication.run(BootApplication.class, args);
    }

    @Override
    public void run(String... args) {
        jdbcTemplate.query("SELECT 1", row -> {});
    }
}

我目前实施的解决方案使用 custom Gradle configuration 作为 h2 依赖项。

build.gradle

configurations {
    localDatabase
}

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

    localDatabase 'com.h2database:h2'
}

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

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