SpringBoot2.0基礎案例(01):環境搭建和RestFul風格接口


本文源碼:GitHub·點這里 || GitEE·點這里

一、SpringBoot 框架的特點

1、SpringBoot2.0 特點

1)SpringBoot繼承了Spring優秀的基因,上手難度小
2)簡化配置,提供各種默認配置來簡化項目配置
3)內嵌式容器簡化Web項目,簡化編碼
Spring Boot 則會幫助開發着快速啟動一個 web 容器,在 Spring Boot 中,只需要在 pom 文件中添加如下一個 starter-web 依賴即可.

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

4)發展趨勢看
微服務是未來發展的趨勢,項目會從傳統架構慢慢轉向微服務架構,因為微服務可以使不同的團隊專注於更小范圍的工作職責、使用獨立的技術、更安全更頻繁地部署。

2、一張圖形容學SpringBoot的心情

img

二、搭建SpringBoot的環境

1、創建一個Maven項目

2、引入核心依賴

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

3、編寫配置文件

application.yml

# 端口
server:
  port: 8001

4、啟動文件注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class,args) ;
    }
}

絲毫沒有問題,就這樣吧啟動上面這個類,springboot的基礎環境就搭建好了。
想想之前的Spring框架的環境搭建,是不是就是這個感覺:意會一下吧。

三、SpringBoot2.0 幾個入門案例

1、創建一個Web接口

import com.boot.hello.entity.ProjectInfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * SpringBoot 2.0 第一個程序
 */
@RestController
public class HelloController {
    @RequestMapping("/getInfo")
    public ProjectInfo getInfo (){
        ProjectInfo info = new ProjectInfo() ;
        info.setTitle("SpringBoot 2.0 基礎教程");
        info.setDate("2019-06-05");
        info.setAuthor("知了一笑");
        return info ;
    }
}

@RestController 注解 等價 @Controller + @ResponseBody 返回Json格式數據。

2、參數映射

1)首先看看SpringBoot 如何區分環境

這里標識配置加載指定的配置文件。

2)參數配置
application-pro.yml

user:
  author: 知了一笑
  title: SpringBoot 2.0 程序開發
  time: 2019-07-05

3)參數內容讀取

@Component
public class ParamConfig {
    @Value("${user.author}")
    private String author ;
    @Value("${user.title}")
    private String title ;
    @Value("${user.time}")
    private String time ;
	// 省略 get 和 set 方法
}

4)調用方式

/**
 * 環境配置,參數綁定
 */
@RestController
public class ParamController {

    @Resource
    private ParamConfig paramConfig ;

    @RequestMapping("/getParam")
    public String getParam (){
        return "["+paramConfig.getAuthor()+";"+
                paramConfig.getTitle()+";"+
                paramConfig.getTime()+"]" ;
    }
}

3、RestFul 風格接口和測試

1)Rest風格接口

/**
 * Rest 風格接口測試
 */
@RestController // 等價 @Controller + @ResponseBody 返回Json格式數據
@RequestMapping("rest")
public class RestApiController {
    private static final Logger LOG = LoggerFactory.getLogger(RestApiController.class) ;
    /**
     * 保存
     */
    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public String insert (UserInfo userInfo){
        LOG.info("===>>"+userInfo);
        return "success" ;
    }
    /**
     * 查詢
     */
    @RequestMapping(value = "/select/{id}",method = RequestMethod.GET)
    public String select (@PathVariable Integer id){
        LOG.info("===>>"+id);
        return "success" ;
    }
}

2)測試代碼

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MockServletContext.class)
@WebAppConfiguration
public class TestRestApi {

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

    /**
     * 測試保存接口
     */
    @Test
    public void testInsert () throws Exception {
        RequestBuilder request = null;
        request = post("/rest/insert/")
                .param("id", "1")
                .param("name", "測試大師")
                .param("age", "20");
        mvc.perform(request)
                .andExpect(content().string(equalTo("success")));
    }

    /**
     * 測試查詢接口
     */
    @Test
    public void testSelect () throws Exception {
        RequestBuilder request = null;
        request = get("/rest/select/1");
        mvc.perform(request)
                .andExpect(content().string(equalTo("success")));
    }
}

這樣SpringBoot2.0的入門案例就結束了,簡單,優雅,有格調。

四、源代碼

GitHub·地址
https://github.com/cicadasmile/spring-boot-base
GitEE·地址
https://gitee.com/cicadasmile/spring-boot-base


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM