6. springboot 整合 swagger
第1步: pom.xml中導入相關的jar包
<!--添加swagger2依賴的jar包-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
第2步:在入口類中增添一個注解 @EnableSwagger2
@SpringBootApplication//入口類
@EnableSwagger2
public class SpringbootSwagerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootSwagerApplication.class, args);
}
}//類的大括號
第3步:添加一個新的config包,創建一個類SwaggerConfig
@Configuration //表明當前是一個配置類
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("測試接口文檔")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xk.springboot.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger構建api文檔")
.description("簡單優雅的restful風格,http://blog.csdn.net/saytime")
.termsOfServiceUrl("http://blog.csdn.net/saytime")
.version("1.0")
.build();
}
}
第4步,創建一個controller包,現在一個test類 先進行測試
@RestController
@ResponseBody
@Api(value = "test模塊")
@RequestMapping("/test")
public class SwaggerTest {
@GetMapping("/demo")
@ApiOperation(value = "測試get的方法")
public Object demo(){
return "測試get成功~~";
}
@PostMapping("/demo")
@ApiOperation(value = "測試post的方法")
public Object demo2(@RequestBody Book book){
return "測試post成功~~";
}
@PutMapping("/demo")
@ApiOperation(value = "測試put的方法")
public Object demo3(){
return "測試put成功~~";
}
@DeleteMapping("/demo")
@ApiOperation(value = "測試delete的方法")
public Object demo4(){
return "測試delete成功~~";
}
}
第5步,在controller包下,開始寫一個BookTest類
@RestController
@ResponseBody
@Api(value = "book模塊")
@RequestMapping("/book")
public class BookTest {
@Autowired
private BookService bookService;
//添加新的數據
@PutMapping(value="/addBook")
@ApiOperation(value = "添加新的數據的方法")
public void addBook(@RequestBody Book book) {
bookService.addBook(book);
}
//更新數據
@PutMapping(value="/updateBook")
@ApiOperation(value = "更新數據的方法")
public void updateBook(@RequestBody Book book) {
bookService.updateBook(book);
}
//刪除數據
@DeleteMapping(value="/deleteBook")
@ApiOperation(value = "刪除數據的方法")
public void deleteBook(int id) {
bookService.deleteBook(id);
}
//根據id查詢
@PostMapping(value="/queryById")
@ApiOperation(value = "根據id查詢數據的方法")
public Book queryById(int id) {
return bookService.queryById(id);
}
//查詢所有的方法
@GetMapping(value="/queryAll")
@ApiOperation(value = "查詢所有的方法")
public Object queryAll(){
return bookService.queryAll();
}
}//類的大括號