簡體   English   中英

如何將 swagger 與球衣 + spring-boot 結合起來

[英]How to integrate swagger with jersey + spring-boot

我正在使用 springboot + jersey 進行 web RESTful 實現。 現在我要將 swagger 集成到我們的應用程序中。 我做了以下。

@Configuration
@EnableSwagger2
public class JerseyConfiguration extends ResourceConfig {

    public JerseyConfiguration(){
        register(HelloworldAPI.class);
        configureSwagger();
    }

    private void configureSwagger() {
        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setVersion("1.0.2");
        beanConfig.setSchemes(new String[]{"http"});
        beanConfig.setHost("localhost:8080");
        beanConfig.setBasePath("/");
        beanConfig.setResourcePackage("com.cooltoo.api");
        beanConfig.setPrettyPrint(true);
        beanConfig.setScan(true);
    }
}

我添加了以下對 build.gradle 的依賴:

compile('io.springfox:springfox-swagger2:'+springfoxSwaggerVersion)
compile('io.springfox:springfox-petstore:'+springfoxSwaggerVersion)
compile('io.springfox:springfox-swagger-ui:'+springfoxSwaggerVersion)
compile('io.swagger:swagger-jersey2-jaxrs:1.5.8')

我能夠啟動 web 應用程序,但我徘徊哪個 url 是為了 swagger? 我嘗試使用http://localhost:8080http://localhost:8080/swaggerhttp://localhost:8080/swagger-ui.html 但是沒有一個可以訪問。

我認為如果使用Spring MVC而不是JAX-RS實現來實現端點, @EnableSwagger2注釋和springfox依賴項將會起作用。

我幾個月前在博客上發表過關於微軟服務的文章,使用Spring Boot,Jersey Swagger和Docker

基本上,如果您需要記錄Jersey實現的端點,則需要:

1)確保您的Spring Boot應用程序通過以下方式掃描位於特定軟件包中的組件(即com.asimio.jerseyexample.config):

@SpringBootApplication(
    scanBasePackages = {
        "com.asimio.jerseyexample.config", "com.asimio.jerseyexample.rest"
    }
)

2)Jersey配置類實現:

package com.asimio.jerseyexample.config;
...
@Component
public class JerseyConfig extends ResourceConfig {

    @Value("${spring.jersey.application-path:/}")
    private String apiPath;

    public JerseyConfig() {
        // Register endpoints, providers, ...
        this.registerEndpoints();
    }

    @PostConstruct
    public void init() {
        // Register components where DI is needed
        this.configureSwagger();
    }

    private void registerEndpoints() {
        this.register(HelloResource.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("Orlando L Otero");
        config.setSchemes(new String[] { "http", "https" });
        config.setBasePath(this.apiPath);
        config.setResourcePackage("com.asimio.jerseyexample.rest.v1");
        config.setPrettyPrint(true);
        config.setScan(true);
    }
}

3)使用JAX-RS(Jersey)和Swagger注釋的資源實現:

package com.asimio.jerseyexample.rest.v1;
...
@Component
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "Hello resource", produces = "application/json")
public class HelloResource {

    private static final Logger LOGGER = LoggerFactory.getLogger(HelloResource.class);

    @GET
    @Path("v1/hello/{name}")
    @ApiOperation(value = "Gets a hello resource. Version 1 - (version in URL)", response = Hello.class)
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "Hello resource found"),
        @ApiResponse(code = 404, message = "Hello resource not found")
    })
    public Response getHelloVersionInUrl(@ApiParam @PathParam("name") String name) {
        LOGGER.info("getHelloVersionInUrl() v1");
        return this.getHello(name, "Version 1 - passed in URL");
    }
...
}

4)確保您的應用程序的Spring Boot配置文件區分Spring MVC(用於執行器端點)和Jersey(用於資源)端點:

application.yml

...
# Spring MVC dispatcher servlet path. Needs to be different than Jersey's to enable/disable Actuator endpoints access (/info, /health, ...)
server.servlet-path: /
# Jersey dispatcher servlet
spring.jersey.application-path: /api
...

我建議使用Simply Swagger Jersey JAXRS依賴並開始。 使用Swagger和Spring Boot相當容易,但是當使用Jersey時,它可能很棘手。

我們需要做的第一件事是將Swagger配置為與Jersey一起使用並更新您的Jersey Config,如下所示。

Jersey Config是我們需要進行所有配置的地方

import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;

import javax.annotation.PostConstruct;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
    @Component
    @ApplicationPath("/api")
    public class JerseyConfig extends ResourceConfig {
        @Autowired
        public JerseyConfig(ObjectMapper objectMapper) {

            packages("com.rest.resources"); 
            // u can also specify resource class names like below
            //register(UserResource.class)  
            //register(AdminResource.class)

        }

         @PostConstruct
          public void init() {
            // Register components where DI is needed
            this.SwaggerConfig();
          }
        private void SwaggerConfig() {
            this.register(ApiListingResource.class);
            this.register(SwaggerSerializers.class);

            BeanConfig swaggerConfigBean = new BeanConfig();
            swaggerConfigBean.setConfigId("Swagger Jersey Example");
            swaggerConfigBean.setTitle("Using Swagger ,Jersey And Spring Boot ");
            swaggerConfigBean.setVersion("v1");
            swaggerConfigBean.setContact("DeveloperName");
            swaggerConfigBean.setSchemes(new String[] { "http", "https" });
            swaggerConfigBean.setBasePath("/api");
            swaggerConfigBean.setResourcePackage("com.rest.resources");
            swaggerConfigBean.setPrettyPrint(true);
            swaggerConfigBean.setScan(true);
          }

現在我們已經完成了所有配置,我們需要驗證是否成功生成了swagger.json。 這是一個重要的步驟,驗證以下URL。

http://localhost:PORT/baseContext/api/swagger.json

因為我們已經將@Application Path指定為“/ api”並且我們沒有配置任何上下文所以我們的基本上下文是“/”.Hence我們訪問url作為http:// localhost:8080 / api / swagger.json

現在我們加載了swagger.json,現在我們需要配置Swagger UI。 它就像一個簡單的Web應用程序中的靜態HTML或資源訪問。

如果您不確定如何配置,請訪問本文 ,其中介紹了如何在文章末尾加載swagger-UI

也許您使用相當舊版本的springfox,但現在(對於版本2.4.0)它必須配置與您的代碼非常不同,請參閱http://springfox.github.io/springfox/docs/current/

例如,我有以下springfox配置:

@Configuration
@EnableSwagger2
class SwaggerConfig {
    @Bean
    Docket rsApi() {
        new Docket(DocumentationType.SWAGGER_12)
            .apiInfo(apiInfo())
            .select()
                    .apis(RequestHandlerSelectors.basePackage('com.test.service'))
            .paths(PathSelectors.any())
            .build()
            .pathMapping('/')
            .useDefaultResponseMessages(false)
    }

    private ApiInfo apiInfo() {
        new ApiInfoBuilder()
            .title('Test API')
            .description('Test API')
            .version('0.0.10.SNAPSHOT')
            .termsOfServiceUrl('')
            .contact('Test company')
            .license('Public')
            .licenseUrl('http://example.com/')
            .build()
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM