【问题标题】:Custom AbstractEndpoint listening to "/" (root)自定义 AbstractEndpoint 监听“/”(根)
【发布时间】:2017-10-25 14:21:15
【问题描述】:

我已经实现了一个启动器,可以按照我喜欢的方式配置 Swagger。此外,我想将每个调用重定向到应用程序的根 URL(例如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?

【问题讨论】:

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


    【解决方案1】:

    我通过在@Configuration 中添加WebMvcConfigurerAdapter bean 以更简单的方法解决了这个问题:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2015-04-19
      • 2017-02-18
      • 2011-12-24
      相关资源
      最近更新 更多