springboot使用简介

2018-12-20 22:50:00
admin
原创 1439
摘要:springboot使用简介

一、springboot使用简介

创建项目

https://start.spring.io/


项目结构

1、Application.java建议放到根目录下面,主要用于做一些框架配置;
2、domain目录主要用于实体(Entity)与数据访问层(DAO);
3、service主要是业务类代码;
4、controller负责页面访问控制;

5、commons负责一些工具类;


特殊文件

maven wapper:保证没有maven的时自动下载maven,或者版本不对下载正确版本maven,有wapper时要使用mvnw;

mvnw:maven wapper的linux脚本;

mvnw.cmd:maven wapper的windows脚本;

.mvn:maven wapper的jar文件和配置文件;


增加web支持

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


增加热部署支持

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>


不执行测试代码

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>

1、surefire用于单元测试,执行*Test.java代码;

2、failsafe用于集成测试,执行*IT.java代码;

3、skip开关同时禁止编译和运行代码,skip禁止编译貌似不生效,skipTests开关用于禁止运行测试代码


spring-boot插件常用目标:

mvn spring-boot:help

mvn spring-boot:run,启动spring-boot应用,和eclipse的run行为一样,不能再执行其它goal;

mvn spring-boot:start,启动spring-boot应用,和eclipse的run行为一样,可以再执行其它goal;

mvn spring-boot:stop


controller示例

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


测试用例示例

import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.*;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.*;
import org.springframework.test.web.servlet.*;
import org.springframework.test.web.servlet.setup.*;
import org.springframework.test.web.servlet.request.*;
import org.springframework.test.web.servlet.result.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleControllerTests {
private MockMvc mvc;

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

@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
}

发表评论
评论通过审核之后才会显示。