没具体到 Get、Post,直接写 @RequestMapping,swagger-ui 就会全部显示
Swagger 配置扫描接口:
SwaggerConfig 配置类:
RequestHandlerSelectors:配置要扫描接口的方式
RequestHandlerSelectors.basePackage():指定要扫描的包
RequestHandlerSelectors.any():扫描全部
RequestHandlerSelectors.none():不扫描
RequestHandlerSelectors.withClassAnnotation(RestController.class):扫描类上的注解
RequestHandlerSelectors.withMethodAnnotation(GetMapping.class):扫描方法上的注解
package com.demo.swagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import static springfox.documentation.service.ApiInfo.DEFAULT_CONTACT;
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
//配置Swagger的Docket的bean实例
@Bean
public Docket docket(Environment environment){
//设置要显示的Swagger环境
Profiles profiles = Profiles.of("dev", "test");
//通过判断是否处于设定的环境中
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//.enable(false) //enable决定是否启动Swagger,如果为false,则Swagger不能在浏览器中访问
.enable(flag)
.select()
/*
RequestHandlerSelectors:配置要扫描接口的方式
basePackage:指定要扫描的包
RequestHandlerSelectors.any():扫描全部
RequestHandlerSelectors.none():不扫描
RequestHandlerSelectors.withClassAnnotation(RestController.class):扫描类上的注解
RequestHandlerSelectors.withMethodAnnotation(GetMapping.class):扫描方法上的注解
*/
.apis(RequestHandlerSelectors.basePackage("com.demo.swagger.controller"))
.paths(PathSelectors.ant("/demo/**")) //paths:过滤的路径
.build();
}
//配置Swagger信息apiInfo
private ApiInfo apiInfo(){
//作者信息
//Contact contact = new Contact("name","url","email");
return new ApiInfo("Api Documentation",
"Api Documentation",
"1.0",
"urn:tos",
DEFAULT_CONTACT, //contact
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
); //从ApiInfo源码获取,可以任意修改,展示的前端页面就会显示修改后的页面
}
}
因为设置了环境,所以需要在 application.properties 添加一行
spring.profiles.active=dev
同理,可以设置其他 properties 文件,真实环境和测试环境换不同的端口号