首页 文章

如何将swagger与平针织 spring 靴融为一体

提问于
浏览
3

我正在使用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是为了招摇?我尝试了http://localhost:8080http://localhost:8080/swaggerhttp://localhost:8080/swagger-ui.html . 但是没有一个可以被访问 .

3 回答

  • 1

    我认为如果使用Spring MVC而不是JAX-RS实现来实现 endpoints ,那么 @EnableSwagger2 注释和 springfox 依赖项将会起作用 .

    几个月前我在博客上发表了这篇文章,Microservices using Spring Boot, Jersey Swagger and Docker

    基本上,如果您需要记录Jersey实现的 endpoints ,则需要:

    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(用于 Actuator endpoints )和Jersey(用于资源) endpoints :

    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
    ...
    
  • 0

    我建议使用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或资源访问 .

    如果您不确定如何配置,请visit this article说明如何在文章末尾加载swagger-UI .

  • 8

    也许您使用相当旧版本的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()
        }
    }
    

相关问题