Springboot+swagger2.7集成開發

Springboot+swagger2.7集成開發

本篇文章是介紹最新的springboot和swagger2.7集成開發和2.0稍微有一些出入:html

  1. Springboot集成環境配置
  2. Swagger2.7集成
  3. 集成測試

Springboot集成環境配置

Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員再也不須要定義樣板化的配置。經過這種方式,Boot致力於在蓬勃發展的快速應用開發領域(rapid application development)成爲領導者。 —— [ INFO深刻學習]java

代碼塊

開發Spring Boot應用,例如:web

@RestController
class App {
  @RequestMapping("/")
  String home() {
    "hello"
  }
}

 

引入SpringBoot的JAR文件.spring

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.7.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

 

編制Main.java

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RestController;  

@RestController  
@EnableAutoConfiguration  
public class Example {  

    @RequestMapping("/")  
    String index() {  
        return "Hello World!";  
    }  

    @RequestMapping("/index/{sayHello}")  
    String index(@PathVariable String sayHello) {  
        return "Hello "+sayHello+"!!!";  
    }  
}  

 

編寫application.properties
application.hellowmsg=Hello World
server.port=8081 #端口
logging.level.=INFO

 

 

編制Application.javaapache

@EnableScheduling
@EnableTransactionManagement
@SpringBootApplication
public class App extends WebMvcConfigurerAdapter {
    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setWebEnvironment(true);
        app.setShowBanner(false);
        Set<Object> set = new HashSet<Object>();
        // set.add("classpath:applicationContext.xml");
        app.setSources(set);
        app.run(args);
    }

 

 

運行Application.java 
看到json

2017-11-15 16:14:08.391  INFO 12524 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2017-11-15 16:14:08.607  INFO 12524 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8081 (http)

 

並無出錯,表示成功,直接訪問http://localhost:8081/,輸出Hello World!api

Swagger2.7集成

加入maven的倉庫文件瀏覽器

<!--swagger2 integration -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.7.0</version>
    </dependency>

 

建立SwaggerConfig的配置文件springboot

import static com.google.common.collect.Lists.newArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.classmate.TypeResolver;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@ConfigurationProperties
public class SwaggerConfig {

    @Value("${swagger.version}")
    private String version;
    @Autowired
    private TypeResolver typeResolver;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("com.hp.ctrl"))
                .paths(PathSelectors.any()).build().apiInfo(apiInfo());
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("構建RESTful APIs").description("更多請關注:http://my.csdn.net/elvishehai")
                .license("The Apache License, Version 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html").termsOfServiceUrl("http://my.csdn.net/elvishehai")
                .version(version).build();
    }
}

 

下一步寫REST的COTR數據結構

@Api(value = "API - SMSController") @RestController public class SmsController { @ApiOperation(value = "測試服務", notes = "測試服務") @ApiImplicitParam(name = "smsRequestBean", value = "用戶詳細實體SmsRequestBean", required = true, dataType = "SmsRequestBean") @RequestMapping(value = "/post", method = RequestMethod.POST) public String post(@RequestBody SmsRequestBean smsRequestBean) { return "服務測試成功,你輸入的參數爲:" + smsRequestBean.getApplicationId(); } @ApiOperation(value = "測試服務", notes = "測試服務", consumes = "application/json", produces = "application/json") @RequestMapping(value = "/test/{input}", method = RequestMethod.GET) @ResponseBody public String getUser(@PathVariable("input") String input) { return "服務測試成功,你輸入的參數爲:" + input; } }

 

  1. swagger經過註解代表該接口會生成文檔,包括接口名、請求方法、參數、返回信息的等等。 
  2. @Api:修飾整個類,描述Controller的做用 
  3. @ApiOperation:描述一個類的一個方法,或者說一個接口 
  4. @ApiParam:單個參數描述 
  5. @ApiModel:用對象來接收參數 
  6. @ApiProperty:用對象接收參數時,描述對象的一個字段 
  7. @ApiResponse:HTTP響應其中1個描述 
  8. @ApiResponses:HTTP響應總體描述 
  9. @ApiIgnore:使用該註解忽略這個API 
  10. @ApiError :發生錯誤返回的信息 
  11. @ApiParamImplicitL:一個請求參數 
  12. @ApiParamsImplicit 多個請求參數 

運行application.java 
在瀏覽器上輸入http://localhost:8081/swagger-ui.html
這裏寫圖片描述
這裏寫圖片描述
能夠看到上面,測試就成功。 
在上圖請求的頁面中,咱們看到user的Value是個輸入框?是的,Swagger除了查看接口功能外,還提供了調試測試功能,咱們能夠點擊上圖中右側的Model Schema(黃色區域:它指明瞭User的數據結構),此時Value中就有了user對象的模板,咱們只須要稍適修改,點擊下方「Try it out!」按鈕,便可完成了一次請求調用! 
此時,你也能夠經過幾個GET請求來驗證以前的POST請求是否正確。 
相比爲這些接口編寫文檔的工做,咱們增長的配置內容是很是少並且精簡的,對於原有代碼的侵入也在忍受範圍以內。所以,在構建RESTful API的同時,加入swagger來對API文檔進行管理,是個不錯的選擇。

+參考信息 
http://swagger.io/ Swagger官方網站

相關文章
相關標籤/搜索