1. 程式人生 > >springmvc 與 springfox-swagger2整合

springmvc 與 springfox-swagger2整合

一、pom.xml引入基於maven的swagger依賴

     <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> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.7</version> </dependency>

二、編寫SwaggerConfig配置類

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan(basePackages 
= {"com.foriseland.fsoa.pay.controller"}) public class SwaggerConfig { @Bean public Docket customDocket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { Contact contact = new Contact("支付組", "", ""); return new ApiInfoBuilder() .title("支付API介面") .description("支付API介面") .contact(contact) .version("1.1.0") .build(); } }

三、在spring mvc配置xml裡面加入Swagger配置

  <!-- swagger -->
   <bean class="com.foriseland.fsoa.pay.swagger.SwaggerConfig"></bean>
   <mvc:default-servlet-handler/>
   <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
   <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

四、controller層的編寫例子

@Controller
@CrossOrigin
@Api(tags="賬戶資訊控制類")
@RequestMapping("account")
public class AccountController{

    @ApiOperation(value = "獲取盈豆數量", notes = "獲取盈豆數量", httpMethod = "POST")
    @RequestMapping(value="getBeansNumber", method=RequestMethod.POST)
    @ResponseBody
    public void getBeansNumber(@RequestBody BeansCountDto info, HttpServletResponse response) {
 
    }
}

五、啟動專案

http://127.0.0.1:8080/{projectName}/swagger-ui.html

 

參考:https://blog.csdn.net/lovelichao12/article/details/79387569