[JAVA] Build Spring Boot project by environment with Gradle

There are several ways to run a build by environment in Gradle, This time, I will introduce how to output the war file after rewriting the settings of application.properties of Spring Boot.

The development tool used is STS, and it is assumed that Gradle Buildship works.

Finally, the part surrounded by the red frame is added to Gradle Tasks, By executing it, you will be able to output a war file for each environment. スクリーンショット 2019-10-07 22.02.48.png

Preparation

Spring Initializr To create a project template. Select Gradle Project in Project, select Packaging and press the Generate button to download. This time, we will move it on the assumption that war will be output.

After downloading, unzip the zip file Let's import it into STS as a Gradle project.

Directory structure

demo
│  build.gradle                     //Add build script here
│  application_template.properties  //Create a new
│
├─.gradle
├─.settings
├─bin
├─gradle
└─src
    ├─main
    │  ├─java
    │  │  └─com
    │  │      └─example
    │  │          └─demo
    │  │                DemoApplication.java  //To fix
    │  │
    │  └─resources
    │          application-dev.properties     //Create a new
    │          application-product.properties //Create a new
    │          application.properties         //To fix
    │
    └─test

setting file

In Spring Boot, prepare a file called application-environment name.properties You can apply the settings for each environment by setting the environment name in application.properties. So, please prepare the following three files under resources.

application.properties


spring.profiles.active=dev

application-dev.properties


sample_data=Development Environment

application-product.properties


sample_data=Production Environment

Sample application

This time, I will run a very simple application that displays the contents of the setting file for each environment. Let's rewrite Application.java as follows.

DemoApplication.java


package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class DemoApplication {
	
	@Value("${sample_data}")
	private String data;  //This value is the sample of the configuration file_Read from the value of data

	public static void main(String[] args) {
		ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
		DemoApplication demo = ctx.getBean(DemoApplication.class);
		demo.run();
	}
	
	private void run() {
		System.out.println(data);
	}
}

When executed, the file set in application.properties should be read and the value corresponding to the environment should be displayed.

Execution result (Spring log omitted)


Development Environment

Write a build script

This time, execute the task for each environment from the Gradle Tasks view of STS and output the war. First, execute the process of replacing application.properties with the one for which the environment to be built is set. Let's create the following application.properties template file.

application_template.properties


spring.profiles.active=${buildEnv}

Next, write a task to overwrite application.properties with a file that replaces the $ {buildEnv} part of the template file. Let's add it to build.gradle. Also, since we will be using the war command this time, don't forget to write the settings for the war command.

build.gradle


plugins {
	// (Omission)
}
//Added war command settings
war {
	enabled = true
	archiveName 'sample.war'
}

// (Omission)

//Each file name
def templateFile = 'application_template.properties'
def configFile = 'application.properties'
//Target environment name (substitute a value later)
def targetEnv = ''

task replaceConfig {
	description 'Replace application.properties environment.'

	doLast {
		println '    start replacing :' + targetEnv
		//Copy execution part
		copy {
			// from:Specify the directory containing the files to copy
			from '.'
			// include:This time, the file name to be copied is specified.
			include templateFile
			// into:Copy destination directory
			into 'src/main/resources'
			// application.Rename to properties
			rename(templateFile, configFile)
			
			// ${buildEnv}Replace
			expand([
				buildEnv: targetEnv
			])
			println "    replacing finished"
		}
	}
	//When the replacement task is completed, war is output with the war command (if it is a jar file, make it a jar)
	finalizedBy {
		war
	}
}

The war task is now executed after the copy process is executed. However, with this alone, the value of targetEnv is still an empty string, so describe the part to be set. I will add more.

build.gradle



//(Omitted)

def templateFile = 'application_template.properties'
def configFile = 'application.properties'
def targetEnv = ''

task replaceConfig {
	// (Omission)
}

task warProduct {
	//By setting group, it will be displayed in build of Gradle Tasks view
	group = 'build'
	description 'Create war file for product environment.'

	doLast {
		//Set targetEnv
		targetEnv = 'product'
	}
	//After setting targetEnv, execute the replaceConfig task
	finalizedBy {
		replaceConfig
	}
}

//dev is the same as Product
task warDev {
	group = 'build'
	description 'Create war file for dev environment.'
	
	doLast {
		targetEnv = 'dev'
	}
	finalizedBy {
		replaceConfig
	}

}

I wrote to execute the replaceConfig task after setting targetEnv in each task. This should work. The following is the uncut version.

build.gradle


plugins {
	id 'org.springframework.boot' version '2.1.9.RELEASE'
	id 'io.spring.dependency-management' version '1.0.8.RELEASE'
	id 'java'
	id 'war'
}
war {
	enabled = true
	archiveName 'sample.war'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

//Each file name
def templateFile = 'application_template.properties'
def configFile = 'application.properties'
//Target environment name (substitute a value later)
def targetEnv = ''

task replaceConfig {
	description 'Replace application.properties environment.'

	doLast {
		println '    start replacing :' + targetEnv
		//Copy execution part
		copy {
			// from:Specify the directory containing the files to copy
			from '.'
			// include:This time, the file name to be copied is specified.
			include templateFile
			//Copy destination directory
			into 'src/main/resources'
			// application.Rename to properties
			rename(templateFile, configFile)
			
			// application_In the template${buildEnv}Replace
			expand([
				buildEnv: targetEnv
			])
			println "    replacing finished"
		}
	}
	//When the replacement task is completed, war is output with the war command.
	finalizedBy {
		war
	}
}

task warProduct {
	//By setting group, it will be displayed in build of Gradle Tasks view
	group = 'build'
	description 'Create war file for product environment.'

	doLast {
		//Set targetEnv
		targetEnv = 'product'
	}
	//After setting targetEnv, execute the replaceConfig task
	finalizedBy {
		replaceConfig
	}
}

//dev is the same as Product
task warDev {
	group = 'build'
	description 'Create war file for dev environment.'
	
	doLast {
		targetEnv = 'dev'
	}
	finalizedBy {
		replaceConfig
	}
}

That's all there is to it. If you execute warDev or warProduct from Gradle Tasks, a war file will be created in build / lib. If you unzip the war and check application.properties in it, it should be the setting of each environment.

Recommended Posts

Build Spring Boot project by environment with Gradle
Spring Boot gradle build with Docker
How to boot by environment with Spring Boot of Maven
Build a Java project with Gradle
◆ Spring Boot + gradle environment construction memo
Switch environment by boot argument with SpringBoot
Build Spring Boot + Docker image in Gradle
(IntelliJ + gradle) Hello World with Spring Boot
Spring Boot environment construction with Docker (January 2021 version)
Create a website with Spring Boot + Gradle (jdk1.8.x)
Run Scala applications with Spring Boot through Gradle
Personal memo Run Spring Boot + Gradle web project with Codenvy (Eclipse Che)
Spring boot development-development environment-
Java tips-Create a Spring Boot project in Gradle
I wanted to gradle spring boot with multi-project
Create Spring Boot environment with Windows + VS Code
View the Gradle task in the Spring Boot project
Download with Spring Boot
Create a Spring Boot development environment with docker
Switch environment with Spring Boot application.properties and @Profile annotation
How to build docker environment with Gradle for intelliJ
SSO with GitHub OAuth in Spring Boot 1.5.x environment
Database environment construction with Docker in Spring boot (IntellJ)
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Get started with Spring boot
Hello World with Spring Boot!
Spring Boot 2 multi-project in Gradle
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Spring Boot starting with Docker
Build docker environment with WSL
Build Ubuntu 18.04.5 with dual boot
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Docker × Spring Boot environment construction
Add module with Spring Boot
Getting Started with Spring Boot
Build Spring for Android 2.0.0 environment
Create microservices with Spring Boot
Send email with spring boot
Change the injection target for each environment with Spring Boot 2
Build a "Spring Thorough Introduction" development environment with IntelliJ IDEA
Build WebAPP development environment with Java + Spring with Visual Studio Code
[Java] Sample project for developing web applications with Spring Boot
Use Basic Authentication with Spring Boot
Build a Node.js environment with Docker
gRPC on Spring Boot with grpc-spring-boot-starter
Build a Tomcat 8.5 environment with Pleiades 4.8
Create an app with Spring Boot 2
Hot deploy with Spring Boot development
Database linkage with doma2 (Spring boot)
Build PlantUML environment with VSCode + Docker
Spring Boot: Restful API sample project
Build environment with vue.js + rails + docker
Until "Hello World" with Spring Boot
Inquiry application creation with Spring Boot
Build Rails environment with Docker Compose