学习springboot的旅程,就像蜗牛爬山,一点点的往上爬,一点点的欣赏旅途的风景
继续上一章的问题,在前后分离的情况下,前端天天找后端要数据接口api?甚至天天找后端,说你这数据接口有问题啊,用不了啊,不会用啊。。。日积月累,终于有一天,后端受不鸟了,引入了一个名叫Swagger2的东东?
Swagger2是个啥东西?
- 1-它提供了一套注解
- 2-它修饰controller对外暴露的方法
- 3-它可将修饰的方法形成可视化的api文档
- 4-它提供了可在线测试数据接口的功能
自从有了这东西后,后台腰不酸了,腿不疼,走路都带风了!!
Swagger2整合步骤
- 第一步:pom.xml
<!--添加Swagger依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--添加Swagger-UI依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
- 第二步通过代码的方式配置Swagger服务
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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;
@Configuration
@EnableSwagger2//用来开启Swagger服务
public class Swagger2Config implements WebMvcConfigurer {
//-----------------第一步:配置拦截swagger页面路由请求
/**
* 定义swagger文件的处理路由
* 显示swagger-ui.html文档展示页,还必须注入swagger资源:
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
//-----------------第二步:配置扫描Controller类及设置生成文档的条件
/**
* swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
*
* @return Docket
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//此包路径下的类,才生成接口文档
.apis(RequestHandlerSelectors.basePackage("com.example.hxzboot.Dome.Controller"))
//加了ApiOperation注解的类,才生成接口文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
//------------------第三步:配置文档生成的信息项
/**
* api文档的详细信息函数,注意这里的注解引用的是哪个
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//大标题
.title("hxzboot利用swagger构建api文档")
// 描述
.description("restful 风格接口")
// 作者
.contact("hxz")
// 版本号
.version("1.0")
.build();
}
}
- 好了,没了?真的就这两步就整合完了。
使用之前了解一下Swagger2提供的功能注解
- Swagger常用注解,swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。
- @Api:修饰整个类,描述Controller的作用
- @ApiOperation:描述一个类的一个方法,或者说一个接口
- @ApiParam:单个参数描述
- @ApiModel:用对象来接收参数
- @ApiProperty:用对象接收参数时,描述对象的一个字段
- @ApiResponse:HTTP响应其中1个描述
- @ApiResponses:HTTP响应整体描述
- @ApiIgnore:使用该注解忽略这个API
- @ApiError :发生错误返回的信息
- @ApiParamImplicitL:一个请求参数
- @ApiParamsImplicit 多个请求参数
Swagger2 使用例子
import com.example.hxzboot.Dome.Entity.User;
import com.example.hxzboot.Dome.Service.UserRepository;
import com.example.hxzboot.Dome.Service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@Api(tags="用户管理")
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@ApiOperation(value = "获取用户数据列表", notes = "获取所有用户数据列表")
@RequestMapping(value = "/alluser" , method = RequestMethod.GET)
public List<User> usersList(){
List<Map<String,Object>> ls=this.userService.queryForList("select * from aaaa");
return userService.findAll();
}
@ApiOperation(value = "更新用户", notes = "更新用户数据")
@RequestMapping(value = "/updateuser" , method = RequestMethod.POST)
public String updateUser(User user)throws Exception{
if(userService.save(user) != null){
return "修改成功";
}else{
return "修改失败";
}
}
@ApiOperation(value = "获取用户", notes = "根据用户id获取用户")
@RequestMapping(value="/getuserbyid",method = RequestMethod.POST)
public User selectUserById(String id){
return userService.findById(id);
}
@ApiOperation(value = "删除用户", notes = "根据用户id删除用户")
@RequestMapping(value="/deleteuser",method = RequestMethod.POST)
public String deleteUser(String id){
userService.deleteById(id);
return "删除成功";
}
@ApiOperation(value = "保存用户", notes = "保存用户数据")
@RequestMapping(value="/saveuser",method = RequestMethod.POST)
public String saveUser(User user)throws Exception{
System.out.println(userService);
if(userService.save(user) != null){
return "新增成功";
}else{
return "新增失败";
}
}
}
浏览器查看api
- 地址是:http://地址:端口/swagger-ui.html
好了,此刻后端程序猿耳根清净,遁入了佛门!!
现在呢?刚刚剃光头的后端程序猿又想起了一件事?持久层还没搞?连接池也没搞啊?,他马上从寺庙夺门而出!!扬长而去!!