出现以上错误提示的原因是没有启用swagger2,也就是没有使用@EnableSwagger2
,很多文章中说在启动类加上@EnableSwagger2即可,虽然添加后能够正常访问http://localhost:8080/swagger-ui.html页面,但是并不能识别到添加swagger相关注解的controller,正确的使用方式是,添加swagger配置类并指定扫描路径:
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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;
/**
* @author bab
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig{
@Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 指定路径
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("没有说明")
.version("1.0.0")
.build();
}
}
添加以上配置类并重新启动项目即可正常访问http://localhost:8080/swagger-ui.html了。
注意:如果配置类所属的包不是启动类的同级或子级则需要在启动累上自己指定需要扫描对应路径,例如:
@ComponentScan("com.example.demo.config")