spring整合Swagger

Spring整合Swagger

1.我这里使用的spring版本是4.1.2.RELEASE

2.导入Swagger的maven依赖

<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger2artifactId>
    <version>2.6.1version>
dependency>
<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger-uiartifactId>
    <version>2.6.1version>
dependency>

3.配置Swagger

@EnableWebMvc
@EnableSwagger2
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //扫描包,如果配置错误swagger页面会出现No operations defined in spec!
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("标题")//大标题
                .description("描述")//小标题
                .contact(new Contact("姓名","主页","邮箱"))
                .version("1.1.0")
                .build();
    }
}

4.配置spring-servlet.xml(就是mvc的配置文件)

<mvc:resources mapping="/swagger/**" location="/WEB-INF/swagger/" cache-period="31556926"/>
  • /swagger/** 拦截路径
  • /WEB-INF/swagger/ 映射路径,该路径在第五步创建

5.下载Swagger

  1. 下载swaggerswagger下载地址

  2. 解压下载好的swagger,并将dist目录内容放到/WEB-INF/swagger/路径,如果没有则创建该路径

  3. 修改swagger的index.html页面

     <script>
        window.onload = function() {
          // Begin Swagger UI call region
          const ui = SwaggerUIBundle({
            // url: "https://petstore.swagger.io/v2/swagger.json",
            url: "http://127.0.0.1:8888/项目名称/v2/api-docs.do",//项目名称看自己配置我配置的是/
            dom_id: '#swagger-ui',
            deepLinking: true,
            presets: [
              SwaggerUIBundle.presets.apis,
              SwaggerUIStandalonePreset
            ],
            plugins: [
              SwaggerUIBundle.plugins.DownloadUrl
            ],
            layout: "StandaloneLayout"
          })
          // End Swagger UI call region
    
          window.ui = ui
        }
      </script>
    

6.写具体的controller(此类在网上找的)

@Controller
@RequestMapping("/userController")
@Api(tags = "二:用户信息") //swagger分类标题注解
public class UserController {

    @RequestMapping(value = "/listCompound", method = RequestMethod.GET)
    @ResponseBody
    @ApiResponses(value = {
            @ApiResponse(code = 500, message = "系统错误"),
            @ApiResponse(code = 200, message = "0 成功,其它为错误,返回格式:{code:0,data[{}]},data中的属性参照下方Model", response = String.class)})
    @ApiOperation(httpMethod = "GET", value = "个人信息")//swagger 当前接口注解
    public String listCompound(
            @ApiParam(required = true, name = "start", value = "start") int start,
            int limit,
            @ApiParam(required = false, name = "userName", value = "名称模糊查询") String userName) {

        return "hello";
    }
}

7.访问swagger

http://127.0.0.1:8888/swagger/index.html 

你可能感兴趣的:(后端,第三方框架)