Spring Boot入门教程(三):HelloWorld

1. 在http://start.spring.io/中生成一个空的项目, 并使用IDEA 打开Open

在这里插入图片描述

在这里插入图片描述

2. 添加SpringMVC依赖

pom.xml中只有spring-boot-starter(核心模块,包括自动配置支持、日志和YAML)和spring-boot-starter-test(测试模块,包括JUnit、Hamcrest、Mockito)两个依赖, 现在添加spring-boot-starter-web来集成SpringMVC功能

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

3. HelloWorldController

@RestController
public class HelloWorldController {

    @RequestMapping("/hello")
    public String index() {
        return "Spring Boot Hello World!";
    }
}

4. 运行main方法并访问http://localhost:8080/index

注意:Spring Boot在启动时会加载groupId.artifactId包下的所有组件,这里由于在创建项目时没有添加web依赖,生成的项目在resources下没有static、templates两个目录

5.单元测试:DemoApplicationTests

package com.example.demo;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


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

    private MockMvc mvc;

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

    @Test
    public void testHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().string(equalTo("Spring Boot Hello World!")));
    }
}

6. Spring MVC 的几个示例

public class User {
    private Long id;
    private String name;
    private Integer age;

    // Getter & Setter
}    
@RestController
@RequestMapping("/users")
public class HelloWorldController {
    // 创建一个线程安全的Map集合
    static Map<Long, User> userMap = Collections.synchronizedMap(new HashMap<>());

    @RequestMapping("/hello")
    public String index() {
        return "Spring Boot Hello World!";
    }


    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String addUser(@ModelAttribute User user){
        System.out.println(user.toString());
        userMap.put(user.getId(), user);

        return "success";
    }


    // http://localhost:8080/users/?page=1&size=10
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<User> getUserList(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer size){
        System.out.println("page=" + page + " ,size=" + size);
        List<User> users = new ArrayList<>(userMap.values());
        return users;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        return userMap.get(id);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String updateUser(@PathVariable Long id, @ModelAttribute User user){
        User user1 = userMap.get(id);
        user1.setName(user.getName());
        user1.setAge(user.getAge());

        userMap.put(id, user1);
        return "success";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        userMap.remove(id);

        return "success";
    }
}

DemoApplicationTests

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


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

    private MockMvc mvc;

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

    @Test
    public void testHello() throws Exception {
        mvc.perform(get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Spring Boot Hello World!")));
    }

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

        // get 获取所有用户列表
        request = get("/users/");
        mvc.perform(request).andExpect(status().isOk())
                .andExpect(content().string(equalTo("[]")));

        // post 添加用户
        request = post("/users/")
            .param("id", "1")
            .param("name", "mengday")
            .param("age", "20");
        mvc.perform(request).andExpect(content().string(equalTo("success")));

        // get get all users
        request = get("/users/");
        mvc.perform(request).andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"mengday\",\"age\":20}]")));


        // put 更新用户
        request = put("/users/1")
                .param("name", "mengday")
                .param("age", "28");
        mvc.perform(request).andExpect(content().string(equalTo("success")));

        // 查看某个用户的信息
        request = get("/users/1");
        mvc.perform(request).andExpect(content().string(equalTo("{\\\"id\\\":1,\\\"name\\\":\\\"mengday\\\",\\\"age\\\":28}")));

        // 删除用户信息
        request = delete("/users/1");
        mvc.perform(request).andExpect(content().string(equalTo("success")));

        request = get("/users/");
        mvc.perform(request).andExpect(status().isOk()).andExpect(content().string(equalTo("[]")));
    }
}

7. 注意

在Application中有一个注解:@SpringBootApplication,在ApplicationTest中有一个注解:@SpringBootTest

单元个测试在测试数据库的时候如果不想造成垃圾数据,可以开启事物功能,可以在方法或者类头部添加@Transactional注解即可。
这样测试完数据就会回滚了,不会造成垃圾数据。如果你想关闭回滚,只要加上@Rollback(false)注解即可。@Rollback表示事务执行完回滚,支持传入一个参数value,默认true即回滚,false不回滚。

如果你使用的数据库是Mysql,有时候会发现加了注解@Transactional 也不会回滚,那么你就要查看一下你的默认引擎是不是InnoDB,如果不是就要改成InnoDB。

ALTER TABLE user ENGINE=INNODB;

原文链接:https://blog.csdn.net/vbirdbest/article/details/79604139

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章