SpingBoot集成Swagger2+swagger-bootstrap-ui

  • A+
所属分类:Java 技术杂谈

第一步,导入依赖:

<!-- 引入swagger相关的jar -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

 

第二步,配置swagger:

@EnableWebMvc
    @Configuration
    public class SwaggerConfig {

        private static final String VERSION = "1.0.0";

        @Bean
        public Docket createRestApi() {
            ApiInfo apiInfo = new ApiInfoBuilder()
                    .title("默认项目名称") //网站标题
                    .description("项目名称swagger RESTFUL APIs......") //网站描述
                    .version(VERSION) //版本
                    .contact(new Contact("张先生博客", "https://www.zhangfayuan.cn/", "xxx@163.com")) //联系人
                    .license("The Apache License") //协议
                    .licenseUrl("http://www.baidu.com") //协议url
                    .build();

            return new Docket(DocumentationType.SWAGGER_2) //swagger版本
                    .pathMapping("/")
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.jeffrey.basis_build.controller"))
                    .paths(PathSelectors.any())
                    .build()
                    .apiInfo(apiInfo);
        }

    }

 

 

第三步:运行项目,访问 http://localhost:port/swagger-ui/index.html,但是这和时候是不能够访问/doc.html的

SpingBoot集成Swagger2+swagger-bootstrap-ui

第四步:导入依赖 swagger-bootstrap-ui

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.6</version>
</dependency>

 

导入之后依旧不能访问http://localhost:port/doc.html,接下来再写一个配置类:

@Configuration
    public class MyWebConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOriginPatterns("*").allowedHeaders("*").allowCredentials(true).allowedMethods("*");
        }

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

 

重启项目,OK,http://localhost:port/doc.html 美化后的地址

SpingBoot集成Swagger2+swagger-bootstrap-ui

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: