小编tar*_*ion的帖子

如何在模块化Spring Boot应用程序中定义隔离的Web上下文?

鉴于Spring Boot应用程序由一个引导程序模块和两个或多个独立的业务模块组成 - 每个模块都公开了特定于业务域的REST API,并且每个模块都使用独立的隔离文档存储来实现数据持久性,我该如何进行关于配置这样的应用程序,例如:

  • 引导程序模块定义父上下文(非Web),它为底层模块(全局配置,对象映射器等)提供某些共享资源.
  • 每个业务模块在同一端口上公开其REST控制器,但使用不同的上下文路径.理想情况下,我希望能够为每个模块定义基本路径(例如/ api/catalog,/ api/orders),并分别定义每个控制器中的子路径.
  • 每个业务模块都定义自己的存储库配置(例如,每个模块的MongoDb设置不同)

为了隔离各个业务模块的上下文(允许我在每个模块中管理独立的存储库配置),我尝试使用SpringApplicationBuilder中可用的上下文层次结构来隔离每个业务模块的上下文:

public class Application {

    @Configuration
    protected static class ParentContext {
    }

    public static void main(String[] args) throws Exception {
        new SpringApplicationBuilder(ParentContext.class)
            .child(products.config.ModuleConfiguration.class)
                .web(true)
            .sibling(orders.config.ModuleConfiguration.class)
                .web(true)
            .run(args);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,由于每个模块都包含一个使用@EnableAutoConfiguration注释的配置类,这会导致Spring Boot尝试启动两个独立的嵌入式servlet容器,每个容器都尝试绑定到同一个端口:

@Configuration
@EnableAutoConfiguration
public class WebApplicationConfiguration {

    @Value("${api.basePath:/api}")
    protected String apiBasePath;

    @Bean
    public DispatcherServlet dispatcherServlet() {
        return new DispatcherServlet();
    }

    @Bean
    public ServletRegistrationBean dispatcherServletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet(),
            apiBasePath + "/products/*");
        registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);

        return registration;
    }
}
Run Code Online (Sandbox Code Playgroud)

关于上下文层次结构的Spring Boot文档指出父上下文不能是Web上下文,所以我对如何在隔离的子上下文之间共享嵌入式servlet容器感到有点迷茫. …

spring-mvc spring-boot

8
推荐指数
1
解决办法
742
查看次数

标签 统计

spring-boot ×1

spring-mvc ×1