在springboot项目中搭建Swagger ui

maven中找jar包位置:https://mvnrepository.com/search?q=swagger

第一步,在pom.xml中引入swagger

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

第二步,配置springboot启动器

创建spring启动器:
@SpringBootApplication
public class SpringBootShopSwaggerApplication {
    public static void main(String[] args) {
		SpringApplication.run(SpringBootShopSwaggerApplication.class, args);
    }

}

第三步,创建controller类进行测试,springboot项目能否正常运行

其中包
@RestController
@Configuration
public class ToSwaggerController {

    @GetMapping("/toswagger")
    public Object toswagger(){
        return "hello swagger!!!!";
    }
}

若第二步正常运行,且能在浏览器下看到hello swagger!!!!,则再进行下一步

(修改参考:提高或降低springboot版本,提高或降低swagger ui版本,尽量不要离官方发布最新版本太近(不稳定))

第四步,创建config文件夹,并创建SwaggerConfig类,并复制下方代码,包需自己一个个引入

@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {

    @Bean
    public Docket docketCS(){    //有需可添加此出 22(下方apiInfoCs())
        return new Docket(DocumentationType.SWAGGER_2)
                ·.apiInfo(apiInfoCs())
                .groupName("XXXX")      //分组的名称,可用于团队合作
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.lz.shop.controller.Cs"))
                .build();
    }

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("AAAA")     //分组的名称,可用于团队合作
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.lz.shop.controller"))   //设置swagger扫描的接口位置
                .build();
    }

    public ApiInfo apiInfo(){
        Contact contact = new Contact("", "", "");
       return new ApiInfo(
               "",  //有需可以进行填写
               "",  //有需可以进行填写
               "1.0",  //有需可以进行填写
               "",  //有需可以进行填写
               contact,
               "",  //有需可以进行填写
               "",   //有需可以进行填写
               new ArrayList());
    }

    private ApiInfo apiInfoCs(){     //有需可添加此出 22(与上方docketCS()连用)
        Contact contact = new Contact("", "", "");
        return new ApiInfo(
                "",  //有需可以进行填写
                "",  //有需可以进行填写
                "1.0",
                "",  //有需可以进行填写
                contact,
                "",  //有需可以进行填写
                "",  //有需可以进行填写
                new ArrayList());
    }
    }

常见错误:尝试再appliaction.propertion中添加 spring.mvc.pathmatch.matching-strategy=ant_path_matcher

posted @ 2022-09-26 10:00  小白的豪豪  阅读(297)  评论(0)    收藏  举报