1. 程式人生 > 實用技巧 >Spring Boot專案開發(五)——整合swagger2自動生成介面文件

Spring Boot專案開發(五)——整合swagger2自動生成介面文件

一、新增swagger2相關依賴

<!--新增swagger2依賴,自動生成介面文件-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>

二、開啟swagger2

啟動類新增@EnableSwagger2註解,開啟swagger2

package com.learn.mall;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @MapperScan(basePackages = "com.learn.mall.model.dao") @EnableSwagger2 public class MallApplication { public static void main(String[] args) { SpringApplication.run(MallApplication.
class, args); } }

三、編寫相關配置檔案

package com.learn.mall.config;

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.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

//訪問http://localhost:8080/swagger-ui.html可以看到API文件
@Configuration
public class SpringFoxConfig {
    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("SpringBoot學習專案")
                .description("")
                .termsOfServiceUrl("")
                .build();
    }
}
package com.learn.mall.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
 * 配置地址對映
 */
@Configuration
public class LearnMallWebMvcConfig implements WebMvcConfigurer {
    @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/");
    }
}

四、controller新增相關介面描述

controller層通過@ApiOperation("新增商品分類")註解可新增介面描述

package com.learn.mall.controller;

import com.learn.mall.common.ApiRestResponse;
import com.learn.mall.common.Constant;
import com.learn.mall.exception.LearnMallExceptionEnum;
import com.learn.mall.model.pojo.User;
import com.learn.mall.model.request.AddCategoryRequest;
import com.learn.mall.service.CategoryService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 商品分類管理
 */
@Controller
public class CategoryController {

    @Autowired
    CategoryService categoryService;
    /**
     * 新增商品分類
     *
     * @param session
     * @return
     */
    @ApiOperation("新增商品分類")
    @PostMapping("admin/category/add")
    @ResponseBody
    public ApiRestResponse addCategory(HttpSession session, @RequestBody @Validated AddCategoryRequest categoryRequest) {
        //判斷使用者是否登入
        User user = (User) session.getAttribute(Constant.USER);
        if(user == null){
            return ApiRestResponse.error(LearnMallExceptionEnum.NEED_LOGIN);
        }
        //判斷使用者是否是超級管理員
        if(user.getRole().equals(1)){
            return ApiRestResponse.error(LearnMallExceptionEnum.NEED_ADMIN);
        }else{
            //執行新增操作
            categoryService.addCategory(categoryRequest);
            return ApiRestResponse.success();
        }
    }
}

五、訪問http://localhost:8080/swagger-ui.html即可