1.引入依赖(PS:这里注意Springboot和Swagger的版本不一致会报错,浪费半天时间)
[查看当前项目SpringBoot版本号方法连接](https://www.jianshu.com/p/90fde9e34c6a
)
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2.添加配置类-basePakage("添加你的controller包地址")
@Configuration
@EnableSwagger2
public class Swagger {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zhangzihao.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restfun风格,http://blog.csdn.net/saytime")
.termsOfServiceUrl("http://blog.csdn.net/saytime")
.version("1.0")
.build();
}
}
3.启动类添加注解
@SpringBootApplication
@ComponentScan({"com.zhangzihao.controller","com.zhangzihao.config"})
@EnableSwagger2
public class CatApplication {
public static void main(String[] args) {
SpringApplication.run(CatApplication.class, args);
}
}
4.在controller类添加注解,然后启动程序(添加了个POST和GET方法)
@RestController
public class UserController {
@ApiOperation(value = "登录操作", notes = "判断用户是否封登录成功")
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login1(int id) {
System.out.println(id);
return "login success";
}
@ApiOperation(value = "用户新增", notes = "添加一个用户")
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@RequestBody User user) {
System.out.println(user);
return "add success";
}
}