【问题标题】:How to specify my restful API for swagger-ui in spring-boot application如何在spring-boot应用程序中为swagger-ui指定我的restful API
【发布时间】:2016-04-01 02:51:49
【问题描述】:

我使用 spring-boot + jersey 作为 restful 实现。我已经设置了招摇,我可以在浏览器上打开招摇 ui。但是 swagger-ui 没有任何 API 可以显示,它是一个空页面。下面是我为配置 swagger 设置的代码。如何让 swagger 扫描我在 jersey 中的 API 定义?

SwaggerConfiguration.java

@Configuration
@EnableSwagger2
public class SwaggerConfiguration  {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("/com.hello.*"))
                .build().pathMapping("/swagger2");
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("App API")
                .description("App API")
                .version("1.0.0-SNAPSHOT")
                .termsOfServiceUrl("")
                .contact("Cooltoo company")
                .license("Public")
                .licenseUrl("http://hello.com/")
                .build();
}

JerseyConfiguration.java

@Configuration
@EnableSwagger2

@EnableAutoConfiguration
@Api(value = "home", description = "Demo API")
@ApplicationPath("/nursego")
public class JerseyConfiguration extends ResourceConfig {

    public JerseyConfiguration() {
        register(BadgeAPI.class);
        register(MultiPartFeature.class);
        register(OrderAPI.class);
        register(NurseAPI.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("/nursego");
        beanConfig.setResourcePackage("com.cooltoo.backend.api");
        beanConfig.setPrettyPrint(true);
        beanConfig.setScan(true);
        register( io.swagger.jaxrs.listing.ApiListingResource.class );
        register( io.swagger.jaxrs.listing.SwaggerSerializers.class );
    }
}

当我打开 http://localhost:8080/swagger-ui.html 时,我看到了下图,但它们都不是来自我的 API。我不知道他们来自哪里

【问题讨论】:

    标签: spring-boot jersey swagger


    【解决方案1】:

    我使用 BeanConfig 类将 Swagger 嵌入到我的 SpringBoot+Jersey 实现中,代码示例如下,

    @Component
    @ApplicationPath( "/api" )
    public class JerseyConfig extends ResourceConfig{
    
        public JerseyConfig(){
           // method for embedding the Swagger
            configSwagger();
           // registers the REST resource classes
            configEndPoints();
        }
    
        private void configEndPoints(){
            // here register all the REST resource classes
        }
    
        private void configSwagger(){
            BeanConfig beanConfig = new BeanConfig();
            beanConfig.setSchemes( new String[]{ "http" } );
            beanConfig.setHost( "localhost:9001" );
            beanConfig.setBasePath( "/api" );
            beanConfig.setDescription( "REST API services for accessing the pcg application"  );
            beanConfig.setTitle( "RESTAPI" );
            beanConfig.setVersion( "1.0.1" );
            // this will tell Swagger config to scan only these packages
            beanConfig.setResourcePackage( "com.aig.rest.web" );
            beanConfig.setScan( true );     
    
            register( io.swagger.jaxrs.listing.ApiListingResource.class );
            register( io.swagger.jaxrs.listing.SwaggerSerializers.class );
    
        }
    
    }
    

    【讨论】:

    • 我已经添加了这段代码,但它似乎不起作用。我在 swagger-ui 页面上得到了一些不相关的 API,例如:“basic-error-controller,endpoint-mvc-adapter:Endpoint Mvc Adapter,environment-mvc-endpoint:Environment Mvc Endpoint”。它们不是来自我的 API。 swagger 好像没有扫描我的资源包。我已经在我的帖子中添加了这个页面的截图
    • 您在配置级别启动 BeanConfig,即在初始化服务器之后。而不是在注册 REST api 时添加 swagger 配置
    • 我在球衣资源配置构造函数中添加了。是不是加错地方了?
    • 这是一个正确的添加方法,你能发布更多的信息,比如 ResourceConfig 和项目结构
    • 我已经发布了从 ResourceConfig 扩展的球衣实现类。
    【解决方案2】:

    如果端点是使用 Spring MVC 而不是 Jersey(或任何其他 JAX-RS impl)实现的,我相信 @EnableSwagger2 注释有效。

    我在今年早些时候创建的一篇博文中详细介绍了如何实现这一点,Microservices using Spring Boot, Jersey Swagger and Docker

    基本上,如果您需要通过 Swagger 记录您的 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
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 2019-08-03
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      相关资源
      最近更新 更多