参考地址:https://www.cnblogs.com/exmyth/p/7183753.html
1. maven 依赖
io.springfox springfox-swagger2 2.6.0 io.springfox springfox-swagger-ui 2.6.0
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配置说明
dispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath*:/spring-mvc.xml 1 dispatcher *.do 说明:Springmvc前端控制器扫描路径增加“/v2/api-docs”,用于扫描Swagger的 /v2/api-docs,否则 /v2/api-docs无法生效。 dispatcher /v2/api-docs
6. 效果展示
index.html 中修改url: