1- mvn 配置
<!-- 接口文档 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
2- javaConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.gm.ds.api"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Simple APIs")
.description("simple apis")
.termsOfServiceUrl("http://www.gm.com")
.contact(new Contact("suliyea", "http://xxx", "suliyea@qq.com"))
.version("1.0")
.build();
}
}
3- 编写测试 Controller
@RequestMapping("/api/user")
@Api(value = "用户接口", description = "")
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@RequestMapping(value = "login", method = RequestMethod.GET)
@ResponseBody
public ApiData login(@RequestParam(value = "username", defaultValue = "") String username,
@RequestParam(value = "password", defaultValue = "") String password) {
//TODO....
return new ApiData().setMessage("用户帐号不存在!").setStatus(ApiData.ERROR);
}
}
4- 按常规, 现在访问http://localhost:8090/swagger-ui.html 应该能看到效果了, 可是访问页面出现这样提示
5- 处理方法
在 GitHub 上下载 SwaggerUI 项目(https://github.com/swagger-api/swagger-ui
),将dist下所有内容拷贝到本地项目resource/static/swagger下面, 并修改 index.html
//url = "http://petstore.swagger.io/v2/swagger.json";
url = "http://localhost:8090/v2/api-docs";
然后访问http://localhost:8090/swagger/index.html