Swagger是一个方便我们更好编写API文档的框架,而且Swagger可以模拟http请求调用。
Swagger官网:Springfox Reference Documentation
一、pom.xml添加依赖
io.springfox
springfox-boot-starter
3.0.0
二、Swagger配置类
需要注意的是里面配置了api文件也就是controller包的路径,不然生成的文档扫描不到接口。
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex("/.*"))// 对根下所有路径进行监控
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("对外开放接口API 文档")
.description("HTTP对外开放接口")
.version("1.0.0")
.termsOfServiceUrl("http://xxx.xxx.com")
.license("LICENSE")
.licenseUrl("http://xxx.xxx.com")
.build();
}
}
用@Configuration注解该类,等价于XML中配置beans;用@Bean标注方法等价于XML中配置bean。
全局配置 header 请求参数设置 globalRequestParameters 参数信息开启header请求参数
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.globalRequestParameters(getGlobalOperationParameters())
.select()
.apis(RequestHandlerSelectors.basePackage("com.demo.hello.interfaces.facade"))
.build();
}
private List getGlobalOperationParameters() {
List parameters = new ArrayList();
parameters.add(new RequestParameterBuilder()
.name("token")
.description("认证token")
.in(ParameterType.HEADER)
.required(false)
.build());
return parameters;
}
}
Application.java 加上注解@EnableSwagger2 表示开启Swagger
@SpringBootApplication
@EnableSwagger2
public class Helloworld01Application {
public static void main(String[] args) {
SpringApplication.run(Helloworld01Application.class, args);
}
}
启动SpringBoot项目,访问http://127.0.0.1:8080/swagger-ui/
对controller添加接口的swagger支持
@Api(value = "/api", tags = "测试API接口")
@RestController
@RequestMapping("/api")
public class ScoreController {
@Autowired
private ScoreService service;
@ApiOperation(value = "获取得分列表", notes = "详细描述")
@RequestMapping(value = "/getScore", method = RequestMethod.GET)
public void GetScore(@RequestParam("uid") @ApiParam(name="uid", value="用户ID") String uid){
List scorelist = service.SelScoreList(uid);
this.renderSuccess(scorelist);
}
}
Swagger注解
swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。
· @Api:修饰整个类,描述Controller的作用
· @ApiOperation:描述一个类的一个方法,或者说一个接口
· @ApiParam:单个参数描述
· @ApiModel:用对象来接收参数
· @ApiProperty:用对象接收参数时,描述对象的一个字段
· @ApiResponse:HTTP响应其中1个描述
· @ApiResponses:HTTP响应整体描述
· @ApiIgnore:使用该注解忽略这个API
· @ApiError :发生错误返回的信息
· @ApiImplicitParam:一个请求参数
· @ApiImplicitParams:多个请求参数
解决异常报错:(1)当Spring Boot 2.6.x以上版本 和 Swagger 3.0.0 整合的时候,可能会报错如下所示:
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
解决方案:
在application.properties中添加:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
(2)开启SpringSecurity后swagger-ui无法正常访问
解决方案:
修改WebSecurity配置
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
public static final String[] permitMethods=new String[]{
"/swagger-ui/**",
"/swagger-resources/**",
};
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//关闭跨站请求防护
.cors().and().csrf().disable()
//允许不登陆就可以访问的方法,多个用逗号分隔
.authorizeRequests().antMatchers(permitMethods).permitAll()
//其他的需要授权后访问
.anyRequest().authenticated()
.and()
//增加是否登陸过滤
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
// 前后端分离是无状态的,所以暫時不用session,將登陆信息保存在token中。
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}