springMVC中集成swagger2 仅需2步

 swagger是一个管理接口的框架,通过注解的方式、网页的形式自动帮我们生成接口相关的信息,相比以前文档的方式撰写的接口,swagger更加便捷、高效,省力。

现在开始介绍集成的步骤:

 

1.添加swagger2的依赖包

        <!-- Swagger2 -->
        <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>

  因为swagger2中已经将ui文件 打包进来了,所以无需像swagger1那样,单独去官网下载ui文件。

       就是上面引入的springfox-swagger-ui这个jar包, 看下图:

        

 

2.创建swagger2的配置文件 

@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
    
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.ever.flyl.api"))
                .paths(PathSelectors.any())
                .build();
    }
    
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger2")
                .description("swagger2")
                .termsOfServiceUrl("http://192.168.3.100:8080/")
                .version("1.0")
                .build();
    }

    
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        
    }
 
}

 然后在spring-servlet中引入swagger2的配置:

<!-- 加入swagger配置 -->
    <bean class="com.ever.flyl.config.SwaggerConfig"/>

   

     以上就完成了整个swagger2的配置

    注意:

    浏览器中直接访问: 项目地址+swagger-ui.html 

   项目地址:ip+端口+项目名

   如果是spring boot项目 默认是无需项目名的

 

swagger的使用

   swagger也是用注解的方式,下面给个案例,一个是类级别的注解 ,一个是方法级别的注解,大家一看便会明白 :

 

(邮箱:514529013@qq.com)

posted @ 2017-03-07 18:01  晴天很嗨  阅读(12586)  评论(3编辑  收藏  举报