美文网首页
spring-boot快速入门一

spring-boot快速入门一

作者: AmeeLove | 来源:发表于2018-04-23 14:21 被阅读26次

官网

spring-boot

选择版本

image.png

pom文件 就是上面的

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.12.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
    </dependencies>

控制器

@RestController
public class HelloController {

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

ChapterApplication

@SpringBootApplication
public class ChapterApplication {

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

直接运行main方法


image.png image.png

运行

访问http://localhost:8080/hello

image.png

发现默认是没有项目名或者context-path
在resources目录下建立application.properties

server.context-path=/Chapter01
image.png
再次访问http://localhost:8080/Chapter01/hello
image.png

修改端口application.properties

server.context-path=/Chapter01
server.port=9090
image.png

测试

pom文件添加


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

测试类

package com.ghgcn.chapter01.test;

import com.ghgcn.chapter01.controller.HelloController;
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.core.IsEqual.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 Chapter01Test01 {

    private MockMvc mvc;

    @Before
    public void setup(){
        mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }


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

只需要在测试类上加上注解

@RunWith(SpringRunner.class)
@SpringBootTest

相关文章

网友评论

      本文标题:spring-boot快速入门一

      本文链接:https://www.haomeiwen.com/subject/btfllftx.html