开发中有很多接口的开发,接口需要配合完整的接口文档才更方便沟通、使用,Swagger是一个用于自动生成在线接口文档的框架,并可在线测试接口,可以很好的跟Spring结合,只需要添加少量的代码和注解即可,而且在接口变动的同时,即可同步修改接口文档,不用再手动维护接口文档。Swagger3是17年推出的最新版本,相比于Swagger2配置更少,使用更方便
. JDK 1.8
. SpringBoot 2.4.2
io.springfox
springfox-boot-starter
3.0.0
com.github.xiaoymin
knife4j-spring-boot-starter
3.0.3
package com.epwcloud.common.core.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.Collections;
import java.util.List;
/**
* Swagger生成api文档
* Created by 谭月浩 on 2021-11-21 11:42
*/
@EnableOpenApi
@Configuration
public class Swagger3Config {
@Value("${swagger.host:}")
private String host;
@Bean
public Docket createRestApi() {
Docket docket = new Docket(DocumentationType.SWAGGER_2);
if ((host != null && !host.trim().isEmpty())) docket.host(host);
return docket
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.epwcloud"))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API文档")
.description("")
.version("0.1")
.termsOfServiceUrl("")
.build();
}
private List securitySchemes() {
return Collections.singletonList(new ApiKey("Authorization", "Authorization", "header"));
}
private List securityContexts() {
AuthorizationScope[] scopes = {new AuthorizationScope("global", "accessEverything")};
List references = Collections.singletonList(new SecurityReference("Authorization", scopes));
return Collections.singletonList(SecurityContext.builder()
.securityReferences(references)
.forPaths(PathSelectors.any())
.build());
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.GET, "/favicon.ico", "/api/file/**", "/", "/assets/**", "/**.html")
.permitAll()
.antMatchers("/api/login", "/error", "/druid/**", "/webjars/**", "/swagger-ui.html",
"/swagger-resources/**", "/v3/api-docs","/doc.html").permitAll()
.anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().headers().frameOptions().disable()
.and().cors().and().csrf().disable();
http.exceptionHandling().accessDeniedHandler(jwtExceptionHandler()).authenticationEntryPoint(jwtExceptionHandler());
http.logout().logoutUrl("/logout").logoutSuccessHandler(jwtLogoutSuccessHandler());
http.addFilterBefore(jwtLoginFilter(), UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(jwtRequestFilter(), UsernamePasswordAuthenticationFilter.class);
}
示例如下:
@Api(tags = "操作接口")
@RestController
@RequestMapping("hs")
public class HsApi {
@Resource
private HsService hsService;
@Resource
private HsTypeService hsTypeService;
@ApiOperation("添加")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "名字", dataType = "String", required = true),
@ApiImplicitParam(name = "typeId", value = "类型ID", dataType = "Long", required = true)
})
@PutMapping("add")
public JSONObject add(String name, Long typeId){
HsType hsType = hsTypeService.findById(typeId);
Hs hs = new Hs();
hs.setName(name);
hs.setType(hsType);
hs.setDateCreated(new Date());
hs = hsService.save(hs);
return JSONObject.parseObject(JSONObject.toJSONString(hs));
}
@ApiOperation("获取")
@GetMapping("get")
public JSONObject get(@ApiParam(name = "id", value = "数据ID") Long id){
Hs hs = hsService.findById(id);
return JSONObject.parseObject(JSONObject.toJSONString(hs));
}
}
启动服务后,就可以查看在线文档了,本地服务的地址是http://localhost:828/doc.html