参考地址:https://www.cnblogs.com/exmyth/p/7183753.html
https://blog.csdn.net/programmer_sean/article/details/72236948
1. maven 依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.0</version> </dependency>
2. Swagger UI模板
下载地址:https://github.com/swagger-api/swagger-ui
swagger-ui-master/dist/index.html
访问配置
<mvc:resources mapping="/swagger/**" location="/swagger/" />
3. swagger 配置文件
@Configuration // 配置注解,自动在本类上下文加载一些环境变量信息 @EnableWebMvc @EnableSwagger2 // 使swagger2生效 @ComponentScan(basePackages="com.test.controller") //需要扫描的包路径 public class SpringfoxConfig extends WebMvcConfigurationSupport{ @Bean public Docket petApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors .basePackage("com.test.controller")).build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("swagger API").description("") .termsOfServiceUrl("http://localhost:8080").version("1.0") .build(); } }
4. Controller中使用注解添加API文档
@Controller @RequestMapping("/person") @Api(tags="个人业务") public class PersonController { @RequestMapping(value="/getPerson",method= RequestMethod.GET) @ApiOperation(httpMethod = "GET", value = "个人信息", produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Person getPersons() { Person person = new Person(); person.setFirstName("fname"); person.setLastName("lname"); person.setAge(37); person.setDeptName("dept"); return person; } }
5.web.xml配置说明
<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/v2/api-docs</url-pattern> </servlet-mapping> 说明:Springmvc前端控制器扫描路径增加“/v2/api-docs”,用于扫描Swagger的 /v2/api-docs,否则 /v2/api-docs无法生效。
6. 效果展示
index.html 中修改url:
<div id="swagger-ui"></div> <script src="./swagger-ui-bundle.js"> </script> <script src="./swagger-ui-standalone-preset.js"> </script> <script> window.onload = function() { // Build a system const ui = SwaggerUIBundle({ url: "/swaggerDeno/v2/api-docs.json", dom_id: '#swagger-ui', deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: "StandaloneLayout" }) window.ui = ui } </script>