Categories
Uncategorized

Spring Boot (a): Quick Start

Spring Boot (a): Quick Start

This series of articles is designed to use minimal dependence, the most simple configuration to help beginners to quickly master the Spring Boot the components used to achieve the purpose of quick start. All articles that are synchronized with the sample code repository Github and Gitee warehouse.

1. Spring Boot What is that?

Spring Boot is a new framework provided by Pivotal team, which is designed to simplify the development process as well as the initial build new Spring applications. The framework uses a particular manner be configured so that the developer is no longer necessary to define the configuration of the template.

Speak plainly Spring Boot is not a new framework, it’s just a lot to achieve integration and default configuration framework.

2. What are the benefits?

The greatest advantage is simple, fast, convenient, before the Spring Boot, if we are to build a framework for what to do?

    Configuring web.xml, loading Spring and Spring MVC, load a variety of filters, interceptors

    In the configuration file application.xml configuration database, configure the cache, configure the connection pool, etc.

    Configuring Log Files

    Read a variety of configuration profiles

    Configuration context, the timing task configuration

  • Wide variety of configurations

I happen to have on hand before the project is a long time, was still used Spring3.x, I can give you a look at the time a project profile number:

And if I need to create a new project, there is a lot of configuration files should copy the past, and re-commissioning, very inconvenient and a waste of time, when the Spring Boot turned out, the nightmare was over.

Boot Spring advantage of:

    Faster entry for all Spring developers

    Out of the box, the default configuration provides a variety of configuration to simplify project

    Embedded Web container to simplify project

    And requires no redundant code generating XML configuration

3. Getting Started

Target setting: Construction of a RESTful API simple unit test and implement corresponding

3.1 engineered way

Spring Boot offers two ways to build the project:

About creating springcloud project, there are two relatively easy to program, the core is the same, we choose their own user-friendly.

method one:

Official Links open in spring:

https://start.spring.io/

Fill in your own organization in the Group, in general, to fill out the company’s domain name to write, for example com.jd or com
    .baidu, here I write directly com.springboot

Fill in the name of the project in Artifact, where I write directly spring-boot-quick-start.

package selection jar, java select 11 (the latest LTS version), so far, the foundation has selected all the election finished, to start next Spring Boot select components we use the.

Found in the Dependencies in Spring Web, select Spring Web, results as shown below:

Finally, click the button below the green bar Generate the project for download, waiting for the download is complete, unpack the archive directly import our idea of ​​editing tools can be.

Second way:

Based on the idea to create, open idea, first of all file-> new-> project, select Spring Initializr, then you can see on the right side let us choose a url service initialization, the default is the top official links, https: // start. spring.io/

Click next Next, fill in and above the same Group, Artifact, java version, package information, etc, continue to the next step next, choose to rely on, and the same way in front of, found in the Dependencies in Spring Web, select Spring Web, click next , select the project name and storage path, click finish, quietly wait a minute, the first project spring-boot-quick-start is fresh ~ ~ ~

I usually choose the first way to create Spring Boot project, this approach does not rely IDE tools.

3.2 Project Structure Analysis

First look at engineering structures we created, as shown below:

    pom.xml: maven project configuration file, mainly to configure some basic information about current projects, including components, versions, and other information that we currently use.

    Program src / main / java at inlet: Chapter1Application.

    Configuration files in src / main / resources: application.properties.

    Test inlet src / test / in: Chapter1ApplicationTests.

3.3 pom.xml

Here we focus on the tag, here we introduce the stated components


    
        org.springframework.boot
        spring-boot-starter-web
    

    
        org.springframework.boot
        spring-boot-starter-test
        test
    

    spring-boot-starter-web: Web module

    spring-boot-starter-test: a test module comprising JUnit, Hamcrest, Mockito

3.4 Spring MVC RESTful API to implement a set of User objects

RESTful API design is as follows:

Request type

Features

Query User List

Create a User

Obtain user information in accordance with the url id

Updated information based on user id

According to id delete user information

URL
GET /
POST /
GET /{id}
PUT /{id}
DELETE /{id}

Note: RESTful interfaces should be designed in accordance with standard methods and semantics, which include considerations such as security and idempotent, such as GET and HEAD requests are safe and will not change the server state no matter how many times the request is made. The GET, HEAD, PUT, and DELETE requests are idempotent, and the result will always be the same regardless of how many operations to the resource, and the subsequent requests will not have more impact than the first.

Typical usage of GET, DELETE, PUT, and POST is listed below:

GET

    Safe and idempotent

    Get the representation

    Gets a (cache) when changing

POST

    Unsafe not idempotent

    Examples of the use of server-side management (automatically generated) No. creating a resource

    Create a child resource

    Some updates Resources

    If it has not been modified, but the updated resource (optimistic locking)

PUT

    But unsafe idempotent

    Creating a resource with the instance number of the client management

    Update the resource by way of replacement

    If not modified, the update resource (optimistic locking)

DELETE

    But unsafe idempotent

    Delete Resource

User Model class as follows:

public class UserModel {
    private Long id;
    private String name;
    private int age;
    
    // 省略 getter 和 setter
}

The REST API categories are as follows:

@RestController
public class UserController {

    // 创建线程安全的Map,用作数据存储
    static Map users = new ConcurrentHashMap<>();

    /**
     * 查询用户列表
     * @return
     */
    @GetMapping("/")
    public List getUserList() {
        List list = new ArrayList(users.values());
        return list;
    }

    /**
     * 创建User
     * @param userModel
     * @return
     */
    @PostMapping("/")
    public UserModel postUser(@ModelAttribute UserModel userModel) {
        users.put(userModel.getId(), userModel);
        return users.get(userModel.getId());
    }

    /**
     * {id} 根据 url 中的 id 获取 user 信息
     * url中的id可通过@PathVariable绑定到函数的参数中
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public UserModel getUser(@PathVariable Long id) {
        return users.get(id);
    }

    /**
     * 根据 id 更新用户信息
     * @param id
     * @param userModel
     * @return
     */
    @PutMapping("/{id}")
    public UserModel putUser(@PathVariable Long id, @ModelAttribute UserModel userModel) {
        UserModel u = users.get(id);
        u.setName(userModel.getName());
        u.setAge(userModel.getAge());
        users.put(id, u);
        return users.get(userModel.getId());
    }

    /**
     * 根据 id 删除用户信息
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }
}

    @Controller: Modified class, used to create the object handle http request

    @RestController: Spring4 annotations added after the original return @Controller the json @ResponseBody need to match, if @RestController @Controller alternative configuration do not need to directly @ResponseBody, returns json default format.

@RestController can look, you can see @RestController itself and by the @ResponseBody @Controller composed of source code as follows:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     * @since 4.0.1
     */
    @AliasFor(annotation = Controller.class)
    String value() default "";

}

Unit test classes as follows:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootQuickStartApplicationTests {

    private MockMvc mvc;

    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
    }

    @Test
    public void contextLoads() throws Exception {
        RequestBuilder request = null;

        // 1、get查一下user列表,应该为空
        request = MockMvcRequestBuilders.get("/")
                .contentType(MediaType.APPLICATION_JSON);
        mvc.perform(request)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();

        // 2、post提交一个user
        request = MockMvcRequestBuilders.post("/")
                .param("id", "1")
                .param("name", "Spring Boot")
                .param("age", "18")
                .contentType(MediaType.APPLICATION_JSON);
        mvc.perform(request)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();


        // 3、get获取user列表,应该有刚才插入的数据
        request = MockMvcRequestBuilders.get("/")
                .contentType(MediaType.APPLICATION_JSON);
        mvc.perform(request)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();

        // 4、put修改id为1的user
        request = MockMvcRequestBuilders.put("/1")
                .param("name", "Spring Boot Test")
                .contentType(MediaType.APPLICATION_JSON);

        mvc.perform(request)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();

        // 5、get一个id为1的user
        request = MockMvcRequestBuilders.get("/1")
                .contentType(MediaType.APPLICATION_JSON);

        mvc.perform(request)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();

        // 6、del删除id为1的user
        request = MockMvcRequestBuilders.delete("/1")
                .contentType(MediaType.APPLICATION_JSON);

        mvc.perform(request)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();

        // 7、get查一下user列表,应该为空

        request = MockMvcRequestBuilders.get("/")
                .contentType(MediaType.APPLICATION_JSON);

        mvc.perform(request)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();

    }

}

Start the test class, the console is printed as follows, where only the interception of a content for display:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /
       Parameters = {id=[1], name=[Spring Boot], age=[18]}
          Headers = [Content-Type:"application/json"]
             Body = 
    Session Attrs = {}

Handler:
             Type = com.springboot.springbootquickstart.controller.UserController
           Method = public com.springboot.springbootquickstart.model.UserModel com.springboot.springbootquickstart.controller.UserController.postUser(com.springboot.springbootquickstart.model.UserModel)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json;charset=UTF-8"]
     Content type = application/json;charset=UTF-8
             Body = {"id":1,"name":"Spring Boot","age":18}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

From the console, you can print a complete simulation to see the entire process requests and parameters.

Sample Code -Github
    Sample Code -Gitee

4. Reference

“Spring Boot (a): Beginners”
    “Spring Boot Construction and RESTful API unit testing”

Leave a Reply