Thursday, October 24, 2019

[Spring Boot] My first Spring Boot Project for demo

Recently, the term "Microservices" is very hot in the cloud service/architecture and it gets my attention. So, I want to learn more about what it is. Furthermore, I also notice Spring Cloud is a very popular microservice framework based on Spring Boot and it provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state)


Here I will show my first Spring Boot Project for demo purpose.

0. Install sdk
https://sdkman.io/install
$ curl -s "https://get.sdkman.io" | bash
$ source "$HOME/.sdkman/bin/sdkman-init.sh"
$ sdk version

1. Install Maven and Gradle ( you can choose one of them to install )
$ sudo apt-get install maven
$ sdk install gradle 5.6.3 # use sdk
2. Insall Spring Boot
$ sdk install springboot
$ spring --version

3. Go to https://start.spring.io/ web site to generate the demo project as follows:


4. Unzip the demo.zip and modify the DemoApplication.java
$ cd demo
$ tree
.
├── HELP.md
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── example
    │   │           └── simple_proj
    │   │               └── demo
    │   │                   └── DemoApplication.java
    │   └── resources
    │       ├── application.properties
    │       ├── static
    │       └── templates
    └── test
        └── java
            └── com
                └── example
                    └── simple_proj
                        └── demo
                            └── DemoApplicationTests.java
vi src/main/java/com/example/simple_proj/demo/DemoApplication.java
package com.example.simple_proj.demo;

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;


@RestController
@EnableAutoConfiguration
@SpringBootApplication
public class DemoApplication {


    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

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

}
5. Run the spring boot demo project and check: http://localhost:8080
$ mvn spring-boot:run

# Open a new terminal
$ curl http://localhost:8080
Hello World!
Now, we can go further to deal with Restful API in Spring Boot.
Fortunately, there is a good example of using Swagger2 with Spring Boot as follows in
GitHub so that I don't need to do it from scratch.
https://github.com/ganchaoyang/spring-tutorial/tree/master/sb-swagger

And the explination of this example is here ( Chinese )
https://itweknow.cn/blog-site/posts/2111459879.html

After running this example, I can get Swagger UI in the following picture:











No comments: