前言
本篇文章主要介紹的是springboot整合swagger2。
swagger2是一個規範和完整的框架,用於生成、描述、調用和可視化Restful風格的web服務,這裏介紹兩種方式實現,第一種是在yml中添加配置,第二種是添加配置類。
GitHub源碼鏈接位於文章底部。
工程結構
首先來看一下工程結構
引入依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- swagger Restful API -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
swagger Restful API的兩個依賴可以由下面這個依賴代替,使用這兩種依賴的swagger-ui界面會有一些不同,但使用方法是一樣的,此外,類上的@Api中的值,上面這種爲value,下面這種爲tags:
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>
第一種方式:在yml中添加swagger中配置,然後在啓動類上添加@EnableSwagger2Doc
這種方式只能使用swagger-spring-boot-starter依賴,因爲只有它纔有@EnableSwagger2Doc。
####swagger相關配置
swagger:
base-package: com.lxg.controller
title: Spring Boot中使用Swagger2構建RESTful APIs
description: swagger2-文檔構建利器
version: 1.7
terms-of-service-url: www.lxgblog.com
contact:
name: LXG
email: [email protected]
第二種方式:定義swagger配置類
springboot使用Swagger很簡單,只需要使用@Configuration配合@Bean將一些配置注入到spring容器,比如編輯Swagger UI界面的信息,指定Swagger負責掃描的package等等,然後在該配置類上添加@EnableSwagger2開啓即可。
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//定義掃描接口的包
.apis(RequestHandlerSelectors.basePackage("com.lxg.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//定義界面標題
.title("Spring Boot中使用Swagger2構建RESTful APIs")
//定義界面描述
.description("swagger2-文檔構建利器")
.termsOfServiceUrl("https://www.lxgblog.com/")
//作者
.contact("李先國")
//版本
.version("1.0")
.build();
}
}
因爲這裏只做測試用,所以就不連接數據庫,寫到控制層即可。
實體類
@Data
public class User {
private Long id;
/** 姓名 */
private String name;
/** 年齡 */
private Integer age;
public User() {
}
public User(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
}
Controller 控制層
因爲swagger作用於接口,它通過註解來實現配置,所以我們在控制層添加一些方法,就能將對應接口顯示到swagger-ui上。
@RestController
@RequestMapping(value = "/api")
@Api(value="用戶操作接口")
public class UserController {
/**
* @ApiOperation來給API增加說明、通過@ApiParam來給參數增加說明。
* value 是標題,notes是詳細說明
* @param user
* @return
*/
@ApiOperation(value="創建用戶", notes="根據User對象創建用戶")
@PostMapping("/user")
public Map<String, Object> insert(@ApiParam(value = "用戶詳細實體user", required = true)@RequestBody User user) {
Map<String, Object> map = new HashMap<>(16);
map.put("respMsg", "新增成功");
map.put("respData", user);
map.put("respCode", 200);
return map;
}
@ApiOperation(value="更新用戶", notes="根據User對象更新用戶")
@PutMapping("/user")
public Map<String, Object> update(@ApiParam(value = "用戶詳細實體user", required = true)@RequestBody User user) {
Map<String, Object> map = new HashMap<>(16);
map.put("respMsg", "更新成功");
map.put("respData", user);
map.put("respCode", 200);
return map;
}
@ApiOperation(value="刪除用戶", notes="根據id刪除用戶")
@DeleteMapping("/user/{id}")
public Map<String, Object> delete(@ApiParam(value = "用戶id", required = true) @PathVariable Integer id) {
Map<String, Object> map = new HashMap<>(16);
map.put("respMsg", "刪除成功");
map.put("respCode", 200);
map.put("id", id);
return map;
}
@ApiOperation(value="獲取用戶列表", notes="根據User對象查詢用戶信息")
@GetMapping("/user")
public List<User> findByUser() {
List<User> list = new ArrayList<>();
list.add(new User(1L,"張三",18));
list.add(new User(2L,"李四",20));
return list;
}
}
@Api:作用於類上,作用是對該類進行說明,說明的信息由value的值決定。
@ApiOperation: 作用於方法上作用是對該接口進行說明,value是接口名稱,notes是說明。
@ApiParam:作用於參數,對方法參數進行說明。
application.yml配置文件
server:
port: 8080
啓動類
@SpringBootApplication
public class SwaggerApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerApplication.class, args);
}
}
測試
啓動程序後,訪問http://localhost:8080/swagger-ui.html 即可查看頁面
可以看到代碼裏通過註解寫的說明都在頁面上體現出來了。
接下來看http請求測試,將在圖中進行說明:
get請求
post請求
delete請求,url帶動態id
跨域問題
跨域是什麼?瀏覽器從一個域名的網頁去請求另一個域名的資源時,域名、端口、協議任一不同,都是跨域 。我們是採用前後端分離開發的,也是前後端分離部署的,必然會存在跨域問題。怎麼解決跨域?
這裏介紹兩種方式,
1.只需要在 controller 類上添加@CrossOrigin即可!這個註解其實是 CORS 的實現。
2.添加配置類:
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer{
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
/*是否允許請求帶有驗證信息*/
corsConfiguration.setAllowCredentials(true);
/*允許訪問的客戶端域名*/
corsConfiguration.addAllowedOrigin("*");
/*允許服務端訪問的客戶端請求頭*/
corsConfiguration.addAllowedHeader("*");
/*允許訪問的方法名,GET POST等*/
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
本文GitHub源碼:https://github.com/lixianguo5097/springboot/tree/master/springboot-swagger
CSDN:https://blog.csdn.net/qq_27682773
簡書:https://www.jianshu.com/u/e99381e6886e
博客園:https://www.cnblogs.com/lixianguo
個人博客:https://www.lxgblog.com