業務規範(整合swagger2)
###業務規範之springboot整合swagger2
###業務規範之統一驗證
###業務規範之統一返回體
###業務規範之統一異常處理和統一響應
二、整合swagger2
這裏用到swagger2:
導入jar包:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
swagger2配置:
//@Profile({"dev", "test"})// 設置 dev test 環境開啓 prod 環境就關閉了
@Configuration
@EnableSwagger2
public class Swagger2Config {
//api接口包掃描路徑
public static final String SWAGGER_SCAN_BASE_PACKAGE = "cn.mesmile.demo.model";
public static final String VERSION = "1.0.0";
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.host("127.0.0.1:8080")
.apiInfo(apiInfo())
// 是否開啓swagger
.enable(true)
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
// 可以根據url路徑設置哪些請求加入文檔,忽略哪些請求
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("練習demo")
.description("單詞計數服務 API 接口文檔") // 設置文檔的描述
.version(VERSION)
.termsOfServiceUrl("http://www.mesmile.cn")
.build();
}
}
前後端跨越以及swagger映射配置:
@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {
/**
* 解決跨越的問題
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
//允許跨域的域名,可以用*表示允許任何域名使用
.allowedOrigins("*")
//允許任何方法(post、get等)
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
//帶上cookie信息
.allowCredentials(true)
//允許任何請求頭
.allowedHeaders("*")
//maxAge(3600)表明在3600秒內,不需要再發送預檢驗請求,可以緩存該結果
.maxAge(3600);
}
/**
* swagger 資源映射
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
//解決中文亂碼問題
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
return converter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
converters.add(responseBodyConverter());
}
}