1)导入Maven依赖
<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)配置Swagger
新建一个SwaggerConfig类
@Configuration
//开启Swagger2
@EnableSwagger2
public class SwaggerConfig {
//配置了Swagger 的Docket的bean实例
@Bean(value = "defaultApi2")
public Docket docket(Environment environment){
//设置要显示的Swagger环境
Profiles profiles = Profiles.of("dev");
//通过environment.acceptsProfiles(profiles)
boolean flag=environment.acceptsProfiles(profiles);
System.out.println(flag);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("pxb") //配置组
.enable(flag) //enable 是否启动Swagger,False,Swagger不以能在浏览器中访问
.select()
//RequestHandlerSelectors 配置要扫描接口的方式
//basePackage:指定要扫描的包
//any:扫描全部
//none():不扫描
//withClassAnnotation:扫描类上的注解,参数是一个注解的反射对象
//withMethodAnnotation: 扫描方法上的注解
.apis(RequestHandlerSelectors.basePackage("com.pxb.controller"))
//过滤什么路径
//.paths(PathSelectors.ant("pxb/**"))
.build();
}
//配置Swagger 信息 =apiInfo
private ApiInfo apiInfo(){
return new ApiInfo(
"SwaggerAPI文档",
"即使再小的帆也能远航",
"1.0",
"urn:tos",
new Contact("", "", ""),//作者信息
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
3)给要扫描的类加注解
@Api(tags = "xx模块")
@RestController
public class AsyncContrller {
@Autowired
AsyncService asyncService;
@ApiOperation("Hello")
@ApiImplicitParam(name = "username",value = "用户名",required = true)
@GetMapping("/hello")
public String hello(String username){
return "ok";
}
}
4)使用
访问页面:http://localhost:8080/swagger-ui.html,会得到这样一个页面