Swagger2>记录SpringBoot MvcEndpoint

时间:2016-08-26 06:49:19

标签: java spring-boot swagger-ui swagger-2.0 spring-boot-actuator

我目前正在我的Swagger2项目中试用SpringBoot(效果很好),但是,它只会选择我的@RestController课程。

我在想:

  1. 是否可以用来接听Spring-Actuator MvcEndpoint
  2. Swagger2组件(例如/swagger-ui.html/v2/api-docs)是否可以托管在management port (e.g. http://${management.address}:${management.port})下,而不是server.port
  3. Application.java

    @EnableSwagger2
    @SpringBootApplication
    public class Application {
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build();
        }
    }
    

    AdminController.java (又名自定义Actuator端点)

    @Component
    public class AdminController implements MvcEndpoint { ... }
    

    application.yml

    server.port: 8080
    management.address: 127.0.0.1
    management.port: 8081
    

    的build.gradle

    compile("org.springframework.boot:spring-boot-starter-actuator")
    compile "io.springfox:springfox-swagger2:2.5.0"
    compile "io.springfox:springfox-swagger-ui:2.5.0"
    

    版本:

    • SpringBoot:1.4.0.RELEASE
    • Gradle:3.0

1 个答案:

答案 0 :(得分:3)

是的,定制它以选择“spring-boot-starter-actuator”exprosed端点是明智之举。

关键点是添加自定义RequestHandlerSelectors谓词,com.example.Swagger2Config.RequestHandlerSelectors是启动时的一个很好的例子。

以下是配置类:

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket actuator() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("Spring Boot Actuator")
                .select()
                .apis(RequestHandlerSelectorsExt.withInterface())
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("App")
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    static class RequestHandlerSelectorsExt {
        public static Predicate<RequestHandler> withInterface() {
            return new Predicate<RequestHandler>() {
                @Override
                public boolean apply(RequestHandler input) {
                    return declaringClass(input) == EndpointMvcAdapter.class;
                }
            };
        }

        private static Class<?> declaringClass(RequestHandler input) {
            return input.getHandlerMethod().getMethod().getDeclaringClass();
        }
    }
}

然后你可以在swagger ui中获得API。 enter image description here

这是github中的demo项目。

2)我真的不知道你的“address:port,而不是server.port”的确切含义,显然它就像“localhost:8080”一样托管在“address:port”中,请附加更多信息这个。