作用
swagger是为了方便进行测试后台的restful形式的接口,实现动态的更新,当我们在后台的接口修改了后,swagger可以实现自动的更新,而不需要人为的维护这个接口进行测试。
步骤
先添加pom配置
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
配置config类,保证启动类能扫描到
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author XM
* @date 2019-04-17
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
// 选择那些路径和api会生成document
.select()
// 对哪些api进行监控
.apis(RequestHandlerSelectors.basePackage("com.xm.demo"))
// 对所有路径进行监控
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("spring boot 测试 Swagger构建RESTful API")
//版本号
.version("1.0")
//描述
.description("描述")
.build();
}
}
此时可能会报404,要添加静态资源
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
此时访问 http:// ip:端口 /swagger-ui.html 就可看到页面
添加测试controller类
@Api(description = "用户接口")
@Controller
@RequestMapping(value = "demoUser")
public class DemoUserController {
@Resource
private DemoUserService demoUserService;
/**
* 查看数据
*
* @return
*/
@ApiOperation(value = "查看接口")
@GetMapping(value = "/page")
@ResponseBody
public List<DemoUserDO> data(@ModelAttribute UserQuery userQuery) {
List<DemoUserDO> datas = demoUserService.backQuery(userQuery);
return results;
}
/**
* 新增记录
*
* @param demoUserDO
*/
@ApiOperation(value = "新增接口")
@PostMapping(value = "/create")
@ResponseBody
public String create(@ModelAttribute DemoUserDO demoUserDO) {
demoUserService.insert(demoUserDO);
return "SUCCESS";
}
/**
* 删除记录
*
* @param id
*/
@ApiOperation(value = "删除接口")
@DeleteMapping(value = "/{id}")
@ResponseBody
public String delete(@PathVariable(value = "id") int id) {
demoUserService.delete(id);
return "SUCCESS";
}
/**
* 更新记录
*
* @param demoUserDO
*/
@ApiOperation(value = "更新接口")
@PostMapping(value = "/update")
@ResponseBody
public String update(@ModelAttribute DemoUserDO demoUserDO) {
demoUserService.update(demoUserDO);
return "SUCCESS";
}
}
页面如下,之后就可以进行各种操作了