在 pom.xml 文件中添加 Swagger2 相关的依赖,配置(部分)如下
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
Swagger2 配置类:SwaggerConfig.java
package com.ff.util;
import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
//.apis(RequestHandlerSelectors.any()) //显示所有类
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) //只显示添加@Api注解的类
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("开放接口API") //粗标题
.description("HTTP对外开放接口") //描述
.version("1.0.0") //api version
.termsOfServiceUrl("http://localhost:8010/swagger-ui.html")
.build();
}
}
修改spring配置文件
<!-- SwaggerConfig-->
<mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
Controller类
@Scope("prototype")
@Controller
@RequestMapping(value = "/user")
//@Validated
@Slf4j
@Api(description = "用户模块")
public class UserController {
@ApiOperation(value = "用户名的验证",httpMethod = "GET",produces = "application/json",response = String.class,notes = "测试")
@RequestMapping(value = "/testSwagger", method = RequestMethod.GET)
@ResponseBody
public String testSwagger() throws Exception {
log.info("testSwagger");
return "1str";
}
}
输入网址