spring boot 入门
一、项目创建
1.1、文件目录说明
src/main/java:主要java代码 src/main/resources:配置文件目录 src/test:单元测试目录
二、maven配置文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns ="http://maven.apache.org/POM/4.0.0"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd" >
<modelVersion > 4.0.0</modelVersion >
<packaging > jar</packaging >
<groupId > spring-boot-01</groupId >
<artifactId > spring-boot-01</artifactId >
<version > 1.0-SNAPSHOT</version >
<name > spring-boot-01</name >
<parent >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-parent</artifactId >
<version > 1.3.7.RELEASE</version >
</parent >
<dependencies >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-web</artifactId >
</dependency >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-test</artifactId >
<scope > test</scope >
</dependency >
</dependencies >
</project >
2.1、说明
jar:spring boot中的web模块依赖嵌入了tomcat,使的jar包具备了web能力 spring-boot-starter-parent:定义了版本为1.3.7,定义了spring boot的基础依赖以及一些默认配置 spring-boot-starter-web:全栈web开发模块,内部嵌入了Tomcat,SpringMVC spring-boot-starter-test:通用测试模块,包含Junit,Hamcrest,Mockito
三、创建HelloApplication
@SpringBootApplication
public class HelloApplication {
public static void main (String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
3.1、代码说明
@SpringBootApplication:当前项目为springBoot项目
四、创建HelloController
@RestController
public class HelloController {
@RequestMapping ("/index" )
public String index () {
return "hello data" ;
}
}
4.1、代码说明
@RestController:Controller类 @RequestMapping(“/index”):接口的请求地址为基本地址+/index
4.2、测试
五、测试
@RunWith (SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration (classes = HelloApplication.class)
@WebAppConfiguration
public class HelloControllerTest {
private MockMvc mvc;
@Before
public void setUp () throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test
public void index () {
}
}
5.1、代码说明
@RunWith(SpringJUnit4ClassRunner.class):引入spring对junit4的支持 @SpringApplicationConfiguration(classes = HelloApplication.class):指定spring boot的启动类 @WebAppConfiguration 开启web用于的配置用于模拟servletContext MockMvc:用于模拟调用controller的接口发起请求 Before:junit中定义在测试用例Test内容执行前预加载的内容