SpringBoot
一、SpringBoot项目构建
1、通过SpringBoot的官方项目生成工具自动生成
可以从http://start.spring.io/这个网站上自动生成springboot基础项目的压缩包,解压缩后导入IDE
2、手动创建maven工程
二、服务开发
1、在src/main/java下建包,编写Controller:
package com.bin.cotroller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@RequestMapping("/hello")
public String helloSrpingBoot() {
return "Hello Spring Boot";
}
}
以clean spring-boot:run启动springBoot项目,然后在浏览器中通过Url:http://localhost:8080/hello访问,页面打印出 Hello Spring Boot;
三、单元测试
Spring的配置类
package com.bin.spring.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration//这是一个Spring的配置类
@ComponentScan(basePackages="com.bin.cotroller")//包扫描
public class SpringConfig {
}
测试类:
package com.bin.demo;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
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.MockMvcBuilder;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.bin.cotroller.DemoController;
import com.bin.spring.config.SpringConfig;
@RunWith(SpringJUnit4ClassRunner.class)//引入spring对junit的支持
@SpringApplicationConfiguration(classes=SpringConfig.class)//springboot的启动类,spring的配置类
@WebAppConfiguration//开启web应用的配置@SpringBootTest
public class DemoApplicationTests {
private MockMvc mvc;
@Before
public void setUp() throws Exception{
mvc = MockMvcBuilders.standaloneSetup(new DemoController()).build();
}
@Test
public void hello() throws Exception{
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello Spring Boot")));
}
}

浙公网安备 33010602011771号