在springboot中整合jersey和springfox-swagger2

前言

爲了實現RESTful Webservice和接口說明,基於springboot平臺,使用jersey作爲JAX-RS的實現,採用swagger文檔在線生成工具。

提要

在實現了springboot集成jerseyswagger文檔功能,同時滿足SpringMVC 整合swagger提供RESTful文檔功能。

  • Springboot  集成swagger 通過springfox-swagger2實現SpringMVCRESTful文檔接口服務;

  • Springboot  集成 Jersey 通過swagger-jersey2-jaxrs 實現Jersey的文檔接口服務;

 

環境

Springboot  1.5.1.RELEASE

springfox-swagger 2 2.6.1

swagger  1.5.12

 

詳細配置

1、Pom文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
     < properties >
         < project.build.sourceEncoding >UTF-8</ project.build.sourceEncoding >
         < swagger.version >1.5.12</ swagger.version >
         < springfox-swagger2.version >2.6.1</ springfox-swagger2.version >
         < spring.boot.version >1.5.1.RELEASE</ spring.boot.version >
     </ properties >
 
     < repositories >
         < repository >
             < id >spring-releases</ id >
             < url >https://repo.spring.io/libs-release</ url >
         </ repository >
     </ repositories >
 
     < parent >
         < groupId >org.springframework.boot</ groupId >
         < artifactId >spring-boot-starter-parent</ artifactId >
         < version >1.5.1.RELEASE</ version >
     </ parent >
 
     < dependencies >
         < dependency >
             < groupId >org.springframework.boot</ groupId >
             < artifactId >spring-boot-starter-web</ artifactId >
         </ dependency >
         <!-- 支持自動確定版本路徑: 寫法由:link rel='stylesheet' href='/webjars/bootstrap/3.1.0/css/bootstrap.min.css' 
             變爲: link rel='stylesheet' href='/webjars/bootstrap/css/bootstrap.min.css' -->
         < dependency >
             < groupId >org.webjars</ groupId >
             < artifactId >webjars-locator</ artifactId >
             < version >0.32</ version >
             < exclusions >
                 < exclusion >
                     < groupId >org.apache.commons</ groupId >
                     < artifactId >commons-lang3</ artifactId >
                 </ exclusion >
             </ exclusions >
         </ dependency >
 
         <!-- springboot 集成 jersey 、swagger 實現 JAX-RS Restful 開始 -->
         < dependency >
             < groupId >org.springframework.boot</ groupId >
             < artifactId >spring-boot-starter-jersey</ artifactId >
         </ dependency >
         < dependency >
             < groupId >io.swagger</ groupId >
             < artifactId >swagger-jersey2-jaxrs</ artifactId >
             < version >${swagger.version}</ version >
         </ dependency >
         <!-- swagger 靜態資源 -->
         < dependency >
             < groupId >org.webjars</ groupId >
             < artifactId >swagger-ui</ artifactId >
             < version >2.2.10</ version >
         </ dependency >
         < dependency >
             < groupId >org.glassfish.hk2</ groupId >
             < artifactId >spring-bridge</ artifactId >
             < version >2.5.0-b34</ version >
         </ dependency >
         <!-- springboot 集成 jersey 、swagger 實現 JAX-RS Restful 結束 -->
 
         <!-- springboot 集成 swagger 實現SpringMVC Restful 開始 -->
         <!-- 解決 springfox-swagger 依賴swagger版本過低問題 -->
         < dependency >
             < groupId >io.swagger</ groupId >
             < artifactId >swagger-annotations</ artifactId >
             < version >${swagger.version}</ version >
         </ dependency >
         < dependency >
             < groupId >io.swagger</ groupId >
             < artifactId >swagger-models</ artifactId >
             < version >${swagger.version}</ version >
         </ dependency >
         < dependency >
             < groupId >io.springfox</ groupId >
             < artifactId >springfox-swagger2</ artifactId >
             < version >${springfox-swagger2.version}</ version >
         </ dependency >
         < dependency >
             < groupId >io.springfox</ groupId >
             < artifactId >springfox-swagger-ui</ artifactId >
             < version >${springfox-swagger2.version}</ version >
         </ dependency >
         <!-- springboot 集成 swagger 實現SpringMVC Restful 結束 -->
 
 
 
         <!-- Test -->
         < dependency >
             < groupId >org.springframework.boot</ groupId >
             < artifactId >spring-boot-starter-test</ artifactId >
             < scope >test</ scope >
         </ dependency >
 
 
     </ dependencies >
     < build >
         < finalName >${project.artifactId}</ finalName >
         < plugins >
             < plugin >
                 < groupId >org.springframework.boot</ groupId >
                 < artifactId >spring-boot-maven-plugin</ artifactId >
                 < version >${spring.boot.version}</ version >
                 < configuration >
                     < mainClass >sample.rs.service.SampleRestApplication</ mainClass >
                 </ configuration >
                 < executions >
                     < execution >
                         < goals >
                             < goal >repackage</ goal >
                         </ goals >
                     </ execution >
                 </ executions >
             </ plugin >
         </ plugins >
     </ build >

2、springboot配置文件 application.properties

1
2
  server.servlet-path = /
  spring.jersey.application-path = /api


3、springboot啓動class

1
2
3
4
5
6
7
8
9
10
import  org.springframework.boot.SpringApplication;
import  org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public  class  SampleRestApplication {
 
     public  static  void  main(String[] args) {
         SpringApplication.run(SampleRestApplication. class , args);
     }
}

4、Jersey配置類,整合swagger

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import  javax.annotation.PostConstruct;
 
import  org.glassfish.jersey.server.ResourceConfig;
import  org.glassfish.jersey.server.wadl.internal.WadlResource;
import  org.springframework.beans.factory.annotation.Value;
import  org.springframework.stereotype.Component;
 
import  io.swagger.jaxrs.config.BeanConfig;
import  io.swagger.jaxrs.listing.ApiListingResource;
import  io.swagger.jaxrs.listing.SwaggerSerializers;
import  sample.jersey.demo1.HelloResource;
import  sample.jersey.demo1.JerseyTest;
import  sample.jersey.demo2.Endpoint;
import  sample.jersey.demo2.ReverseEndpoint;
import  sample.jersey.demo3.HelloService;
 
@Component
public  class  JerseyConfig  extends  ResourceConfig {
 
     @Value ( "${spring.jersey.application-path}" )
     private  String apiPath;
 
     public  JerseyConfig() {
         register(Endpoint. class );
         register(ReverseEndpoint. class );
         this .registerEndpoints();
     }
 
     @PostConstruct
     public  void  init() {
         // Register components where DI is needed
         this .configureSwagger();
     }
 
     private  void  registerEndpoints() {
         this .register(HelloResource. class );
         this .register(JerseyTest. class );
         this .register(HelloService. class );
         // Access through /<Jersey's servlet path>/application.wadl
         this .register(WadlResource. class );
     }
 
     private  void  configureSwagger() {
         // Available at localhost:port/swagger.json
         this .register(ApiListingResource. class );
         this .register(SwaggerSerializers. class );
         BeanConfig config =  new  BeanConfig();
         config.setConfigId( "springboot-jersey-swagger-docker-example" );
         config.setTitle( "Spring Boot + Jersey + Swagger + Docker Example" );
         config.setVersion( "v1" );
         config.setContact( "wzh" );
         config.setSchemes( new  String[] {  "http" "https"  });
         config.setBasePath( this .apiPath);
         config.setResourcePackage( "sample.jersey" );
         config.setPrettyPrint( true );
         config.setScan( true );
     }
}

5、Swagger配置類,支持spirngMVC RESTful文檔功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import  static  com.google.common.base.Predicates.or;
import  static  springfox.documentation.builders.PathSelectors.regex;
 
import  java.util.Arrays;
 
import  org.springframework.beans.factory.annotation.Value;
import  org.springframework.context.annotation.Bean;
import  org.springframework.context.annotation.Configuration;
 
import  com.google.common.base.Predicate;
 
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.SecurityScheme;
import  springfox.documentation.spi.DocumentationType;
import  springfox.documentation.spring.web.plugins.Docket;
import  springfox.documentation.swagger2.annotations.EnableSwagger2;
 
/**
  * api doc -- springfox swagger configuration
  */
 
@Configuration
@EnableSwagger2
public  class  SwaggerConfig {
 
     @Value ( "${spring.jersey.application-path}" )
     private  String apiPath;
 
     @Bean
     public  SecurityScheme apiKey() {
         return  new  ApiKey( "access_token" "accessToken" "header" );
     }
 
     @Bean
     public  Docket apiConfig() {
         return  new  Docket(DocumentationType.SWAGGER_2).groupName( "controller" )
                 // 調用apiInfo方法,創建一個ApiInfo實例,裏面是展示在文檔頁面信息內容
                 .apiInfo(apiInfo()).select()
                 // 控制暴露出去的路徑下的實例
                 // 如果某個接口不想暴露,可以使用以下註解
                 // @ApiIgnore 這樣,該接口就不會暴露在 swagger2 的頁面下
                 .apis(RequestHandlerSelectors.basePackage( "sample.jersey.controller" )).paths(PathSelectors.any())
                 .build().useDefaultResponseMessages( false ).securitySchemes(Arrays.asList(apiKey()));
     }
 
     @Bean
     public  Docket restConfig() {
         return  new  Docket(DocumentationType.SWAGGER_2).groupName( "jax-rs" ).apiInfo(restInfo()).forCodeGeneration( true )
                 .pathMapping( "/" ).select().paths(paths()) // 過濾的接口
                 .build().useDefaultResponseMessages( false );
     }
 
     // 請求url匹配,支持and or,可以過濾篩選
     private  Predicate<String> paths() {
         return  or(regex( "/test/.*" ), regex( "/rest/.*" ));  //
     }
 
     private  ApiInfo apiInfo() {
         return  new  ApiInfoBuilder().title( "berheley service controller api " ) // 大標題
                 .description( "spring boot webservice 平臺 API" ) // 小標題
                 // .termsOfServiceUrl("http://ww.swagger.com/")
                 // .contact(new Contact("swagger", "www.swagger.com",
                 // "[email protected]"))
                 .version( "2.0" ).build();
     }
 
     private  ApiInfo restInfo() {
         return  new  ApiInfoBuilder().title( "berheley service rest api " ) // 大標題
                 .description( "spring boot webservice 平臺 API" ) // 小標題
                 .version( "2.0" ).build();
     }
}

6、SprintMVC風格的web 服務示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package  sample.jersey.controller;
 
import  org.springframework.stereotype.Controller;
import  org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.bind.annotation.RequestMethod;
import  org.springframework.web.bind.annotation.RequestParam;
import  org.springframework.web.bind.annotation.ResponseBody;
 
import  io.swagger.annotations.ApiOperation;
import  io.swagger.annotations.ApiParam;
 
@Controller
@RequestMapping ( "/test" )
public  class  TestController {
 
     @ResponseBody
     @RequestMapping (value =  "/show" , method = RequestMethod.POST)  // 這裏指定RequestMethod,如果不指定Swagger會把所有RequestMethod都輸出,在實際應用中,具體指定請求類型也使接口更爲嚴謹。
     @ApiOperation (value =  "測試接口" , notes =  "測試接口詳細描述" )
     public  String show( @ApiParam (required =  true , name =  "name" , value =  "姓名" @RequestParam (name =  "name" ) String stuName) {
         return  "success" ;
     }
}

7、JAX-RS 實現的服務示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package  sample.jersey.demo3;
 
import  javax.ws.rs.GET;
import  javax.ws.rs.Path;
import  javax.ws.rs.PathParam;
import  javax.ws.rs.Produces;
import  javax.ws.rs.core.MediaType;
 
import  org.springframework.stereotype.Service;
 
@Path ( "/rest" )
@Component
public  class  HelloService {
 
     @GET
     @Path ( "/sayHello/{a}" )
     @Produces (MediaType.TEXT_PLAIN)
     public  String sayHello( @PathParam ( "a" ) String a) {
         return  "Hello "  + a +  ", Welcome to CXF RS Spring Boot World!!!" ;
     }
}

8、將swagger-ui包中的index.html複製到static目錄下,修改資源文件路徑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
相關文章
相關標籤/搜索