自定义AbstractEndpoint听" /" (根)

时间:2017-10-25 14:21:15

标签: spring-boot spring-boot-actuator spring-boot-starter

我已经实现了一个以我喜欢的方式配置Swagger的启动器。此外,我还想将每次调用应用的根网址(例如localhost:8080)重定向到/swagger-ui.html。 因此,我添加了一个自己的AbstractEndpoint,它在@Configuration类中实例化,如下所示:

@Configuration
@Profile("swagger")
@EnableSwagger2
public class SwaggerConfig {

    ...

    @Bean
    public RootEndpoint rootEndpoint() {
        return new RootEndpoint();
    }

    @Bean
    @ConditionalOnBean(RootEndpoint.class)
    @ConditionalOnEnabledEndpoint("root")
    public RootMvcEndpoint rootMvcEndpoint(RootEndpoint rootEndpoint) {
        return new RootMvcEndpoint(rootEndpoint);
    }
}

各个班级如下:

public class RootEndpoint extends AbstractEndpoint<String> {

    public RootEndpoint() {
        super("root");
    }

    @Override
    public String invoke() {
        return ""; // real calls shall be handled by RootMvcEndpoint
    }
}

public class RootMvcEndpoint extends EndpointMvcAdapter {

    public RootMvcEndpoint(RootEndpoint delegate) {
        super(delegate);
    }

    @RequestMapping(method = {RequestMethod.GET}, produces = { "*/*" })
    public void redirect(HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.sendRedirect("/swagger-ui.html");
    }
}

public RootEndpoint()中所述,自定义端点绑定到/root。不幸的是,我无法指定super("");super("/");,因为这些值会引发异常(Id must only contains letters, numbers and '_')。

如何使用@Configuration文件实例化bean,让自定义端点在启动器中监听根URL?

1 个答案:

答案 0 :(得分:0)

我通过在WebMvcConfigurerAdapter中添加@Configuration bean来更简单地解决了这个问题:

@Bean
public WebMvcConfigurerAdapter redirectToSwagger() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("").setViewName("redirect:/swagger-ui.html");
        }
    };
}