[JAVA] Implement Spring Boot application in Gradle

Steps to build and run Spring Boot with Gradle.

procedure

  1. Added to build.gradle
  2. Create Spring Boot execution class
  3. Create a class for API
  4. Launch Spring Boot with Gradle
  5. Check the API execution result

Added to build.gradle

build.gradle


def applicationVersion = project.properties['release.version']

// ~~~

// Spring Boot
buildscript {
    def springBootVersion = '2.0.3.RELEASE'
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:' + springBootVersion
    }
}

apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

def springBootApplicationName = 'hello-world-spring-boot'
bootJar {
    baseName = springBootApplicationName
    version = applicationVersion
}

bootWar {
    baseName = springBootApplicationName
    version = applicationVersion
}

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-devtools'
    testCompile 'org.springframework.boot:spring-boot-starter-test'
}

entire build.gradle

build.gradle


//Release version gradle.Get from properties and set
def applicationVersion = project.properties['release.version']
version = applicationVersion

//Java version
apply plugin: 'java'
def javaVersion = JavaVersion.VERSION_1_10
sourceCompatibility = javaVersion
targetCompatibility = javaVersion

//Output war file
apply plugin: 'war'

//Dependent library version
def junitVersion = '5.2.0'
def jacocoVersion = '0.8.1'
def checkstyleVersion = '8.10.1'

//Dependent library acquisition destination
repositories {
    //Use Maven Central
    mavenCentral()
}

//Dependent libraries
dependencies {
    // JUnit
    testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: junitVersion
    testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: junitVersion
    testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: junitVersion
}

test {
    //Use JUnit5 when building gradle
    useJUnitPlatform()
    //Number of parallel execution threads for the test
    maxParallelForks = 4
}

//Gradle plug-in settings that output various IDE configuration files
apply plugin: 'eclipse'
apply plugin: 'idea'

//Use Jacoco for test coverage
apply plugin: 'jacoco'
jacoco {
    toolVersion = jacocoVersion
}

jacocoTestReport {
    reports {
        xml.enabled = true
        html.enabled = true
    }
}

build.dependsOn jacocoTestReport

//Static code analysis with Checkstyle
apply plugin: 'checkstyle'
checkstyle {
    toolVersion = checkstyleVersion
    //By default/src/main/Under resources, but refer to the XML file directly under the repository
    configFile = file('checkstyle.xml')
    //Make sure to interrupt the build if there is an error when running Checkstyle
    ignoreFailures = false
}

// Spring Boot
buildscript {
    def springBootVersion = '2.0.3.RELEASE'
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:' + springBootVersion
    }
}

apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

def springBootApplicationName = 'hello-world-spring-boot'
bootJar {
    baseName = springBootApplicationName
    version = applicationVersion
}

bootWar {
    baseName = springBootApplicationName
    version = applicationVersion
}

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-devtools'
    testCompile 'org.springframework.boot:spring-boot-starter-test'
}

Create Spring Boot execution class

Product code

Application.java


package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

}

Test code

ApplicationTest.java


package hello;

import org.junit.jupiter.api.Test;

class ApplicationTest {

  @Test
  void main() {
    Application.main(new String[0]);
  }

}

I get a warning that Spring Boot is automatically terminated, but there is no problem. Please advise if there is any better solution.

Create a class for API

Product code

HelloWorldController.java


package hello;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
class HelloWorldController {

  static final String HELLO_WORLD = "Hello, world.";
  private static final int BUFFER_SIZE = 1024;

  @RequestMapping(value = "/string", method = RequestMethod.GET)
  String byString() {
    return HELLO_WORLD;
  }

  @RequestMapping(value = "/byte", method = RequestMethod.GET)
  byte[] byBytes() {
    return HELLO_WORLD.getBytes();
  }

  @RequestMapping(value = "/stream", method = RequestMethod.GET)
  ResponseEntity<InputStreamResource> byStream() {
    final InputStreamResource inputStreamResource = new InputStreamResource(
        new BufferedInputStream(new ByteArrayInputStream(HELLO_WORLD.getBytes()), BUFFER_SIZE)
    );

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentLength(HELLO_WORLD.getBytes().length);

    return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
  }

}

Test code

HelloControllerTest.java


package hello;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

class HelloControllerTest {

  @Test
  void byString() {
    final HelloWorldController helloController = new HelloWorldController();
    Assertions.assertAll(
        () -> Assertions.assertEquals(helloController.byString(), HelloWorldController.HELLO_WORLD)
    );
  }

  @Test
  void byBytes() {
    final HelloWorldController helloController = new HelloWorldController();
    Assertions.assertAll(
        () -> Assertions.assertEquals(Arrays.toString(helloController.byBytes()),
            Arrays.toString(HelloWorldController.HELLO_WORLD.getBytes()))
    );
  }

  @Test
  void byStream() {
    final HelloWorldController helloController = new HelloWorldController();
    final ResponseEntity<InputStreamResource> response = helloController.byStream();
    try (final InputStream input = response.getBody().getInputStream()) {
      final byte[] body = input.readAllBytes();
      Assertions.assertAll(
          () -> Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK),
          () -> Assertions.assertEquals(Arrays.toString(body),
              Arrays.toString(HelloWorldController.HELLO_WORLD.getBytes()))
      );
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

Launch Spring Boot in Gradle

Command execution

gradle bootRun

Or

gradlew bootRun

Check the API execution result

In both cases, Hello, world. Is returned in the response body (it appears in the browser in words).

bonus

In the response of the type that returns InputStream, I checked whether InputStream was properly closed.


  @RequestMapping(value = "/stream", method = RequestMethod.GET)
  ResponseEntity<InputStreamResource> byStream() {
    final InputStreamResource inputStreamResource = new InputStreamResource(
        new BufferedInputStreamCustom(new ByteArrayInputStream(HELLO_WORLD.getBytes()), BUFFER_SIZE)
    );

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentLength(HELLO_WORLD.getBytes().length);

    return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
  }

  private static class BufferedInputStreamCustom extends BufferedInputStream {

    public BufferedInputStreamCustom(InputStream in, int size) {
      super(in, size);
    }

    @Override
    public void close() throws IOException {
      System.out.println("closed");
      super.close();
    }

  }

Every time I ran the API, I got a closed output on the console, and found that the InputStream I passed was closed properly.

Recommended Posts

Implement Spring Boot application in Gradle
Spring Boot 2 multi-project in Gradle
Spring Boot application development in Eclipse
Implement REST API in Spring Boot
Build Spring Boot + Docker image in Gradle
Spring Boot 2.3 Application Availability
Java tips-Create a Spring Boot project in Gradle
View the Gradle task in the Spring Boot project
Implement application function in Rails
Set context-param in Spring Boot
Implement GraphQL with Spring Boot
[Spring Boot] Web application creation
CICS-Run Java application-(4) Spring Boot application
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Spring Boot application code review points
◆ Spring Boot + gradle environment construction memo
Write test code in Spring Boot
Implement REST API with Spring Boot and JPA (Application Layer)
Inquiry application creation with Spring Boot
Implement reCAPTCHA v3 in Java / Spring
Sample web application that handles multiple databases in Spring Boot 1.5
What is @Autowired in Spring boot?
Thymeleaf usage notes in Spring Boot
Spring Boot gradle build with Docker
Processing at application startup with Spring Boot
Static file access priority in Spring boot
Output Spring Boot log in json format
Local file download memorandum in Spring Boot
Create Java Spring Boot project in IntelliJ
Loosen Thymeleaf syntax checking in Spring Boot
Start web application development with Spring Boot
[Practice! ] Display Hello World in Spring Boot
Launch Nginx + Spring Boot application with docker-compose
Use DynamoDB query method in Spring Boot
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Spring Boot, Doma2, Gradle initial setting summary
Implement paging function with Spring Boot + Thymeleaf
DI SessionScope Bean in Spring Boot 2 Filter
(IntelliJ + gradle) Hello World with Spring Boot
Add spring boot and gradle to eclipse
Change session timeout time in Spring Boot
Run WEB application with Spring Boot + Thymeleaf
Challenge Spring Boot
Automatically deploy a web application developed in Java using Jenkins [Spring Boot application]
Spring Boot Form
Spring Boot Memorandum
gae + spring boot
Create a website with Spring Boot + Gradle (jdk1.8.x)
SameSite cookie in Spring Boot (Spring Web MVC + Tomcat)
Configure Spring Boot application with maven multi module
Run a Spring Boot project in VS Code
Output request and response log in Spring Boot
Create a Spring Boot application using IntelliJ IDEA
Try to implement login function with Spring Boot
Use Servlet filter in Spring Boot [Spring Boot 1.x, 2.x compatible]
How to add a classpath in Spring Boot
Build Spring Boot project by environment with Gradle
How to bind to property file in Spring Boot
I wanted to gradle spring boot with multi-project
Deploy a Spring Boot application on Elastic Beanstalk