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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM