springMVC swagger2
阿新 • • 發佈:2018-09-14
extc ces doc opera .com tde 需要 .get 配置文件
參考地址:https://www.cnblogs.com/exmyth/p/7183753.html
1. maven 依賴
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</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>
springMVC swagger2