springboot+swagger整合
为什么用swagger
为什么要用swagger,要从现在我们项目中遇到的痛点出发,目前都是前后端分离,后端同学提供api给前端同学调用,但是代码改动后api文档更新不及时,文档也可能出现错误,所以希望有个工具可以在后端写好api后自动生成api文档,swagger就是这样的工具。
pom中加入依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
添加swaggerconfig
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Created by Andy.W.Zhang on 2019/3/6.
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket swaggerSpringMvcPlugin() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();
}
}
controller中增加注解
import com.andy.framdemo.entity.User;
import com.andy.framdemo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by Andy.W.Zhang on 2019/3/6.
*/
@Api(description = "用户接口")
@Controller
@RequestMapping(value = "/api/v1/users")
public class UserController {
@Autowired
private UserService userService;
@ApiOperation(value = "新增用户" , notes="新增用户")
@RequestMapping(value = "",method = RequestMethod.POST)
@ResponseBody
public int adduser(@RequestBody User user){
return userService.addUser(user);
}
}
项目启动后查看api
浏览器 http://localhost:8080/swagger-ui.html
![swaggerAPI查看页](https://img-blog.csdnimg.cn/20190307095633834.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwNTAyOTk=,size_16,color_FFFFFF,t_70)