Java: Spring Boot

From RHS Wiki
Jump to navigation Jump to search

Create microservices

import java.util.Arrays;
import java.util.List;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;

public class Course {
    private long id;
    private String name;
    private String author;

    public Course(long id, String name, String author){
        super();
        this.id = id;
        this.name = name;
        this.author = author;
    }

    public String toString() {
        return "Course [id=" + id + ", name= " + name + ", author=" + author + " ]";
    }

    public long getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public String getAuthor() {
        return author;
    }
}


@RestController
public class CourseController {
    @GetMapping("/courses")
    public List<Course> getAllCourses(){
    return Arrays.asList(new Course(1, "Learn microservices", "in28minutes"));
    }
}

Spring Boot Starter Projects

Found at Spring Initializr Under dependencies

Web Application: Spring Boot Starter Web

REST API: Spring Boot Starter Web

Talk to database using JPA: Spring Boot Starter Data JPA

Talk to database using JDBC: Spring Boot Starter Data JDBC

Secure your web application or REST API: Spring Boot Starter Security

Spring Boot Actuator

Monitor and manage your application

  • beans: Complete list of Spring beans in your app
  • health: Application health information
  • metrics: Application metrics
  • mappings: Details around Requests Mappings

To enable Spring Boot actuator at pom.xml:

....
    <dependencies>
        ....
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        ....
    </dependencies>
....

http://127.0.0.1:8080/actuator http://127.0.0.1:8080/actuator/health http://127.0.0.1:8080/actuator/health/{*path} http://127.0.0.1:8080/actuator/info


Build

Make JAR not WAR (JAR contains embeded server)