Summary of what I learned about Spring Boot

Introduction

I will keep a memorandum of what I learned when I first touched Spring Boot from November to December last year.

Target audience

For those who want to touch Spring Boot from now on. I think that it will be known to those who have used it.

What I made

A simple external public API that just returns information based on the received input value.

Various things used

Configuration of the application implemented this time

クラス構成.png

Overview of various classes

name of the class Overview
RestController class A class that implements the interface part of the API.
Form class A class that holds information about the content of requests from clients and the response returned.
RestControllerAdvice class RestController A class that implements common processing.
Service class A class that implements business logic.
Repository class Class for DB access.
Entity class A class that holds the data acquired from the DB and the data to be input to the DB.

Descriptions and samples of various classes

Main class

Add @SpringBootApplication.

Annotation Overview
@EnableAutoConfiguration Spring Boot automatic setting is turned on, and various settings are automatically made according to the defined dependencies.
@ComponentScan A component scan is performed and in the package to be scanned@ComponentThe class with is automatically loaded and managed by the DI container. The components scanned are@AutowiredCan be set to a variable by. * Refer to the sample code below.
@Configuration By assigning it, beans can be registered individually and setting classes can be read.

Various classes are read and set by @ComponentScan and @EnableAutoConfiguration, and the application is executed.

SampleApplication.java


@SpringBootApplication
public class SampleApplication {

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

    @Override
    protected SpringApplicationBuilder configure (final SpringApplicationBuilder builder) {
        return builder.sources (SampleApplication .class);
    }
}

RestController class

SampleController.java


/**
 *Sample controller.
 */
@RestController
@Validated
public class SampleController {

    @Autowired
    private SampleService service; //Associate the Service class to be used.

    @PostMapping (path = "/sample", //Specify the path to map to the method.
        consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, //Specify the Media Type of the request to be received.
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE) //Specify the Media Type of the response to be returned.
    @CrossOrigin
    public ResponseEntity<SampleForm> sampleMethod (
        @RequestHeader (value = "sample_key") //Define the key value of the value received from the header.
        @NotEmpty (message = "sample_key is empty.") //If you want to scrutinize without using Form, define the scrutiny content here.
        @Valid String sampleKey, //Define a variable to store the value received from the header.
        @RequestBody
        @Valid SampleForm form //Define the Form class that stores the value received from the body and the variable that stores it.
    ) {
        return new ResponseEntity<> (service.sampleMethod (form.getSampleUserId), HttpStatus.OK);
    }
}

Form class

SampleForm.java


@Data
@ToString
public class SampleForm implements Serializable {

    private static final long serialVersionUID = 1L;

    @JsonProperty ("sample_user_id") //Define the key value on JSON.
    @NotEmpty (message = "sampleUserId is empty") //Define the content of the scrutiny.
    private String sampleUserId;
    
}

RestControllerAdvice class

SampleExceptionHandler.java


@RestControllerAdvice
public class SampleExceptionHandler {

    @ExceptionHandler (Exception.class) //Define the exception to catch.
    @ResponseStatus (HttpStatus.INTERNAL_SERVER_ERROR) //Define the HTTP status code of the response returned when the above exception occurs.
    protected ErrorForm handleInternalServerError (Exception e) {
        logger.error (e);
        return new ErrorForm ("Internal Server Error");
    }

    @RequiredArgsConstructor
    private class ErrorForm implements Serializable {
        private static final long serialVersionUID = 1L;
        private final String message;
    }
}

Service class

SampleService.java


@Service
@Transactional //Automatically roll back when an exception occurs.
public class SampleService {

    @Autowired
    private SampleUserRepository sampleUserRepository; //Associate the Repository class to be used.

    public SampleForm returnSampleForm (String sampleUserId) {
        return convertToSampleForm(sampleUserRepository.findBySampleUserId(sampleUserId));
    }
}

Repository class

SampleUserRepository.java


@Repository
public interface SampleUserRepository extends JpaRepository<SampleUser, String> { //Define the access destination table and primary key type.
    SampleUser findBySampleUserId (String sampleUserId); //Define method names and arguments according to the naming convention.
}

Entity class

SampleUser.java


@Entity
@Table (name = "sample_user") //Define the table name to be linked.
@Data
public class SampleUser implements Serializable {

    private static final long serialVersionUID = 1L;

    /**Sample user ID*/
    @Id //Give to the item of the primary key.
    @GeneratedValue (strategy = GenerationType.IDENTITY) //If you want automatic numbering, define the numbering method.
    private String sampleUserId;

    /**Sample username*/
    private String sampleUserName;
}

Reference site

Recommended Posts

Summary of what I learned about Spring Boot
Summary of what I learned in Spring Batch
What I learned about Kotlin
What i learned
About DI of Spring ①
What I learned ② ~ Mock ~
About DI of Spring ②
What I learned ① ~ DJUnit ~
Spring Boot 2.2 Document Summary
I checked asynchronous execution of queries in Spring Boot 1.5.9
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
[Spring boot] I thought about testable code by DI
I will write what I learned about docker anyway (second)
I learned about the existence of a gemspec file
I will write what I learned about docker anyway (first)
What I researched about Java 8
What I researched about Java 6
What you learned about hashes
What I researched about Java 9
What you learned about symbols
What I researched about Java 7
What I researched about Java 5
About the function of Spring Boot due to different versions
What I fixed when updating to Spring Boot 1.5.12 ・ What I was addicted to
What I learned from studying Rails
Spring Framework 5.0 Summary of major changes
Going out of message (Spring boot)
About binding of Spring AOP Annotation
What is @Autowired in Spring boot?
[Spring Boot] Role of each class
What I learned with Java Gold
I tried GraphQL with Spring Boot
I tried Flyway with Spring Boot
What I learned with Java Silver
What I researched about Java learning
Summary about the introduction of Device
What I did in the migration from Spring Boot 1.4 series to 2.0 series
Here's a summary of what I've been curious about Enums lately
What I did in the migration from Spring Boot 1.5 series to 2.0 series
I want to control the default error message of Spring Boot
What is a Spring Boot .original file?
[Spring Boot] I investigated how to implement post-processing of the received request.
What is testing? ・ About the importance of testing
Take what you've learned about Java reflection
About Spring ③
What I learned through the swift teacher
About the initial display of Spring Framework
Summary of going to JJUG CCC 2019 Spring
WebMvcConfigurer Memorandum of Understanding for Spring Boot 2.0 (Spring 5)
I tried Lazy Initialization with Spring Boot 2.2.0
What I got into @Transactional in Spring
Spring Boot, Doma2, Gradle initial setting summary
What I learned from Java monetary calculation
Summary of points I was worried about when migrating from java to kotlin
I tried to clone a web application full of bugs with Spring Boot
[Personal memo] I learned a little about modifiers
About the official start guide of Spring Framework
[FCM] Implementation of message transmission using FCM + Spring boot
[Rails] I learned about database data type types!
The story of raising Spring Boot 1.5 series to 2.1 series