1.添加swagger依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger2.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger2.version}</version> //2.8.0 </dependency>
2.swagger配置文件
package com.yypawn.lean.springbootactivemq.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ParameterBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.schema.ModelRef; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Parameter; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import java.util.ArrayList; import java.util.List; @Configuration public class SwaggerConfig { @Bean public Docket createRestApi() {// 创建API基本信息 List<Parameter> pars = new ArrayList<Parameter>(); ParameterBuilder ticketPar = new ParameterBuilder(); ticketPar.name("token").description("user token") .modelRef(new ModelRef("string")).parameterType("header") .required(false).build(); //header中的token参数非必填,传空也可以 pars.add(ticketPar.build()); //根据每个方法名也知道当前方法在设置 // ticketPar = new ParameterBuilder(); ticketPar.name("source").description("user source ") .modelRef(new ModelRef("string")).parameterType("header") .required(false).build(); //header中的source参数非必填,传空也可以 pars.add(ticketPar.build()); //根据每个方法名也知道当前方法在设置 return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.yypawn.lean.springbootactivemq.controller"))// 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外 .paths(PathSelectors.any()) .build().globalOperationParameters(pars); } private ApiInfo apiInfo() {// 创建API的基本信息,这些信息会在Swagger UI中进行显示 return new ApiInfoBuilder() .title("AD RESTful APIs")// API 标题 .description("www.yypawn.lean")// API描述 .contact("yy")// 联系人 .version("2.0")// 版本号 .build(); } }
3.启动类添加@EnableSwagger2,添加包扫描@ComponentScan("com.**")--包的路径
4.启动项目,访问localhost:port/swagger-ui.html#
如果配置了项目地址,localhost:port/url/swagger-ui.html#