springboot 集成 swagger详解,实测成功。

swagger的好处我就不多说了,大家可以自行了解,用于文档管理应该是不二之选。

好了,步入正题,目前我用的springboot版本是1.4.0.RELEASE,然后需要引入两个包,

springfox-swagger2和springfox-swagger-ui,版本是2.8.0,至于是用gradle还是maven大家可以自行选择。

然后加上swagger的配置类,如下:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by : chenfei
 * Date : 2018/7/18
 */
@Configuration
@EnableSwagger2
public class SwaggerConf {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.qkhc.chedai.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger构建api文档")
                .description("简单优雅的restfun风格,https://blog.csdn.net/chenfei110722/article/details/81103231")
                .termsOfServiceUrl("https://blog.csdn.net/chenfei110722/article/details/81103231")
                .version("1.0")
                .build();
    }
}

PS:  com.qkhc.chedai.controller 是我的包,大家自行修改为自己的项目包。

swagger的页面在swagger-ui这个包下面,相关的静态文件也在这里面,所有想要直接访问swagger的页面需要映射这个路径,添加代码如下:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;



/**
 * Created by : chenfei
 * Date : 2018/7/18
 */
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }


    /**
     * 配置servlet处理
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

好了,然后在启动类上加上注解@EnableWebMvc,到这儿,就完成了,正常启动项目,localhost:9023/swagger-ui.html,就可以看到swagger的页面了。

PS:如果大家还是会出现问题,可以看下spring配置是否关闭了静态访问,或者拦截器拦截了。欢迎一起讨论。

猜你喜欢

转载自blog.csdn.net/chenfei110722/article/details/81103231
今日推荐