spring 继承 swagger2配置

依赖配置

  • pom.xml配置
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>
  • 创建同springboot启动类— Application同目录的SwaggerConfig类
@EnableWebMvc
@EnableSwagger2
@Configuration
public class SwaggerConfig {
 
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.z*.b*.c*.controller")) // 注意修改此处的包名
                .paths(PathSelectors.any())
                .build();
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("接口列表 v1.1.0") // 任意,请稍微规范点
                .description("接口测试") // 任意,请稍微规范点
                .termsOfServiceUrl("http://url/swagger-ui.html") // 将“url”换成自己的ip:port
                .contact("laowu") // 无所谓(这里是作者的别称)
                .version("1.1.0")
                .build();
    }
}

springboot启动类配置swagger

@SpringBootApplication(exclude = {WebApiAutoConfiguration.class})
@EnableCaching(proxyTargetClass = true)
@EnableFeignClients
@EnableConfigurationProperties
@EnableSwagger2
@EnableDubbo // 消费端不需要配置扫描路径,会识别所有被 @Reference 注解的服务
@MapperScan(basePackages = "com.wacai.stanlee.bullseye.webapi.mapper")
public class BullseyeWebapiApplication extends WebMvcConfigurationSupport {
  public static void main(String[] args) {
    SpringApplication.run(BullseyeWebapiApplication.class, args);
  }
}

接口方法添加注解

  • 在类和方法添加注解
类:
@Api(value = "类描述", description = “类描述")
public class ScriptController {

方法:
  @ApiOperation(value = "方法描述", notes = "方法描述)
  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public WebApiResponse<String> save(

登录测试

  • http://ip:port/swagger-ui.html

问题解决

无法显示 swagger页面

  • 原因:可能是无法加载swagger静态资源
  • 解决,配置WebMvcConfig,创建同SwaggerConfig同目录的WebMvcConfig类;spring boot 启动类使用 @EnableSwagger2 注解
/**
 * @author yishou
 * @date 2021/5/12
 * @description 注册资源管理器
 */
@Configuration
public class WebMvcConfig 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);
  }
}
上一篇:记录下一个C++初始化的方式(很少有人这么用,但是却是一个使代码更加简洁的方式)


下一篇:springboot+springcloud+maven相关父子项目创建