注意:springfox3.0 访问SwaggerUI用http://localhost:8081/swagger-ui/或http://localhost:8081/swagger-ui/index.html
<!-- 包含springfox-swagger2和springfox-swagger-ui3的依赖 --><dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version></dependency> 3.编写HelloController并测试 @RestControllerpublic class HelloController { @GetMapping(value = "/hello") public String hello(){ return "hello"; }} 4.编写配置类SwaggerConfig来配置 Swagger @Configuration@EnableOpenApipublic class SwaggerConfig { @Bean public Docket docket(){ return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) // 定义是否开启swagger,false为关闭,可以通过变量控制,默认为true .enable(false) .select() //RequestHandlerSelectors 配置要扫描接口的方式 .apis(RequestHandlerSelectors.basePackage("com.wang.controller")) //paths() 过滤什么路径 .paths(PathSelectors.ant("/wang/**")) .build(); } private ApiInfo apiInfo(){ //作者信息 Contact contact = new Contact("小满", "", ""); return new ApiInfo( "小满的 Swagger Api Documentation", "你要快快长大哦", "1.0", "urn:tos", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); }} 面试题:我只希望我的swagger在生产环境用,在开发环境不用思路:判断是不是生产环境
Profiles profiles = Profiles.of("dev","test"); boolean flag = environment.acceptsProfiles(profiles); @Configuration@EnableOpenApipublic class SwaggerConfig { @Bean //注意导这个包的 import org.springframework.core.env.Environment; public Docket docket(Environment environment){ Profiles profiles = Profiles.of("dev","test"); boolean flag = environment.acceptsProfiles(profiles); return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) // 定义是否开启swagger,false为关闭,可以通过变量控制,默认为true .enable(flag) .select() //RequestHandlerSelectors 配置要扫描接口的方式 .apis(RequestHandlerSelectors.basePackage("com.wang.controller")) //paths() 过滤什么路径 .paths(PathSelectors.ant("/wang/**")) .build(); } private ApiInfo apiInfo(){ //作者信息 Contact contact = new Contact("小满", "", ""); return new ApiInfo( "小满的 Swagger Api Documentation", "你要快快长大哦", "1.0", "urn:tos", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); }} 配置API文档分组 .groupName("小满") 如何配置多个分组多个Docket即可,协作开发
@Bean public Docket docket1(){ return new Docket(DocumentationType.OAS_30).groupName("A"); } @Bean public Docket docket2(){ return new Docket(DocumentationType.OAS_30).groupName("B"); } 实体配置 新建实体类 @ApiModel("用户")public class User { //如果属性是private就不会暴露出来 @ApiModelProperty("用户名") public String username; @ApiModelProperty("密码") public String password;} 只要这个实体在请求接口的返回值上(即使是泛型),都能映射到实体项中: //只要这个实体在请求接口的返回值上(即使是泛型),都能映射到实体项中: @PostMapping(value = "/user") public User user(){ return new User(); } 效果注意:关于@ApiModelProperty标签的坑,今天莫名遇到了这个,不过改了下把username改为userName再改回来又好了
@ApiModel为类添加注释@ApiModelProperty为类属性添加注释 总结 我们可以通过swagger给一些难以理解的属性接口加注解信息接口文档实时更新可以在线测试注意点:出于安全考虑,在正式发布时要关闭Swagger