SpringCloud学习点滴——Spring boot的简单入门1

因为SpringCloud是在Spring Boot 的基础上开发的,所以在学习Spring cloud之前,应该要对spring boot有一定的了解

一、首先构建一个Spring boot项目:

  1、通过官方的Spring Initializr工具产生基础项目

  2、访问http://start.spring.io/,里面有各种的配置,直接图形化配置好就行了

  

  3、这里我构建了maven project,Spring版本为了兼容,使用2.1.1,然后其他按要求填写即可

  4、点击Generate Project下载项目压缩包

  5、解压项目包,用Intellij idea来导入项目

  6、File->New->Project from Existing Sources,然后选择自己刚才解压的项目包就可以了

  7、单击Import project from external model并选择Maven,一直next下去

二、打开我们的pom文件,我们看到很多依赖并不像我们常规的那样,有组名,还有版本号,这里的sprnig-boot-starter-web和sprnig-boot-starter-test模块,在Spring Boot中被称为Starter POMS,这是一系列轻便的依赖包,开发者在使用和整合模块时,不需要去搜寻样例代码中的依赖配置来复制使用,只需要引入对应的模块包即可。这样使得木块整合变得非常青桥,已于理解和使用。最后是项目构建的build部分,引入了Spring Boot的maven插件,该插件非常实用,可以帮助我们方便的启停应用。

三、编写一个Contrller实现我们的第一个hello world

package com.example.SpringBootdemo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@RequestMapping(value = "/hello",method = RequestMethod.GET)

public String index(){
return "Hello world";
}

四、启动我们的服务

  1、可以选择运行拥有main函数的类来启动

  

  2、在maven配置中,有个spring-boot插件,可以使用它来启动,比如执行mvn spring-boot:run命令启动

  

  3、将应用打包成jar包,再通过java -jar xxx.jar来启动

  4、启动成功,端口号是默认的8080

  

 五、编写测试用例,模拟网络请求

package com.example.SpringBootdemo;

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

import java.awt.*;

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(
SpringJUnit4ClassRunner.class
)
@SpringBootTest(classes = SpringBootdemoApplication.class)
@WebAppConfiguration//开启web应用的配置,用于模拟servletContext
public class SpringBootdemoApplicationTests {
private MockMvc mockMvc;//模拟调用controller的接口发起请求

@Before//test前要预加载的内容
public void setUp() throws Exception{
mockMvc = MockMvcBuilders.standaloneSetup(new SpringBootdemoApplication()).build();
}
@Test
public void contextLoads() throws Exception {
//执行一次请求调用
mockMvc.perform(MockMvcRequestBuilders.get("/hello")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello world")));
}

}

猜你喜欢

转载自www.cnblogs.com/dudu-dubby/p/10115062.html