SpringBoot整合Swagger

1.引入依赖(PS:这里注意Springboot和Swagger的版本不一致会报错,浪费半天时间)

[查看当前项目SpringBoot版本号方法连接](https://www.jianshu.com/p/90fde9e34c6a

)

        
            io.springfox
            springfox-swagger2
            2.9.2
        

        
            io.springfox
            springfox-swagger-ui
            2.9.2
        

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";
    }

}

5.浏览器打开链接 http://localhost:8080/swagger-ui.html

可以看见Swagger中usercontroller中也是对应两个接口

image.png

6.展开POST接口并测试-点击 try it out >Example ValueModel 中填你的测试数据>点击Execute按钮执行,可以看见返回add success

image.png

image.png

image.png

你可能感兴趣的:(SpringBoot整合Swagger)