1.导入swagger2
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox.version}</version> </dependency>
2.配置类
/** * Swagger配置 */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // 自行修改为自己的包路径 .apis(RequestHandlerSelectors.basePackage("com.xx.xx.controller")) .paths(PathSelectors.any()) .build() .globalOperationParameters(setHeaderToken()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("平台api文档") .description("restful 风格接口") //服务条款网址 //.termsOfServiceUrl("http://www.hdvon.cn/") .version("1.0") //.contact(new Contact("xxx有限公司", "url", "email")) .build(); } private List<Parameter> setHeaderToken() { ParameterBuilder tokenPar = new ParameterBuilder(); List<Parameter> pars = new ArrayList<>(); tokenPar.name("token").description("token令牌").modelRef(new ModelRef("string")).parameterType("header").required(false); pars.add(tokenPar.build()); return pars; } }
3.在controller上贴上相应注解
@Api(value="用户登录",description="用户登录") @RestController @RequestMapping("/") public class LoginController { @ApiOperation(value = "登录并获取token", notes = "登录并获取token", httpMethod = "POST") @PostMapping(value = "login") public HttpResponse login(String username, String password, boolean force) {}
4.如果你的项目是springboot项目,访问http://localhost:[端口]/swagger-ui.html,就可以看到swagger的ui页面了