Spring启动多模块servletDispatchers

Mai*_*jer 13 java spring servlets spring-mvc spring-boot

我有一个以下项目结构

-Project
 |-config
 |  |-modules
 |     |-admin
 |     |-web
 |- platform 
Run Code Online (Sandbox Code Playgroud)

Platform是包含spring-boot启动类的项目,Platform依赖于config,config依赖于目录模块中的所有内容.Platform也是使用mvn spring-boot:run命令启动的模块.

我想要完成的是模块管理员和网络(两个网络应用程序)都有自己的映射

  • /管理员
  • /网络

以下代码表示管理模块中的控制器,Web模块还包含一个类似的控制器(这就是要点)

@Controller
public class AdminController {

    @RequestMapping("/")
    public String adminController() {
       return "admin";
    }
}
Run Code Online (Sandbox Code Playgroud)

这里有一些用于配置管理模块的代码

@Configuration
public class Config implements EmbeddedServletContainerCustomizer {

@Autowired
protected WebApplicationContext webApplicationContext;

@Autowired
protected ServerProperties server;

@Autowired(required = false)
protected MultipartConfigElement multipartConfig;

protected DispatcherServlet createDispatcherServlet() {

    AnnotationConfigEmbeddedWebApplicationContext webContext = new AnnotationConfigEmbeddedWebApplicationContext();
    webContext.setParent(webApplicationContext);
    webContext.scan("some.base.package");
    return new DispatcherServlet(webContext);
}

protected ServletRegistrationBean createModuleDispatcher(DispatcherServlet apiModuleDispatcherServlet) {
    ServletRegistrationBean registration =
            new ServletRegistrationBean(apiModuleDispatcherServlet,
                    "/admin");

    registration.setName("admin");
    registration.setMultipartConfig(this.multipartConfig);

    return registration;
}


@Bean(name = "adminsServletRegistrationBean")
public ServletRegistrationBean apiModuleADispatcherServletRegistration() {
    return createModuleDispatcher(createDispatcherServlet());
}

public void customize(ConfigurableEmbeddedServletContainer container) {
    container.setContextPath("/admin");
}
}
Run Code Online (Sandbox Code Playgroud)

类似于Web模块的东西

我已经尝试了一些给定答案的实现.

  1. 使用多个调度程序servlet/web上下文与spring boot
  2. 带有多个调度程序servlet的Spring Boot(JAR),用于使用Spring Data REST的不同REST API
  3. 还有很多谷歌搜索

当我让组件扫描时,扫描两个模块(删除ComponentScan过滤器)

我得到一个不明确的映射发现异常,说两个控制器方法都调度到相同的路径"/"

但是当在其中一个模块上禁用组件扫描时,管理模块确实会映射到/ admin.

当我禁用两个控制器时,我看到/ web和/ admin dispatchServlets被映射.

所以我理解异常,但我不明白如何解决这个问题.对我来说,每个模块我必须这样做,我不想用它来映射它

@RequestMapping("/admin")
Run Code Online (Sandbox Code Playgroud)

在控制器类上

我还尝试在application.properties中指定contextPath和servletPath

所以我的问题是:达到我的目标的最佳方法是什么,或者我是否尝试使用spring-boot来实现它的目标.

编辑 概念证明会很好

Mai*_*jer 4

所以我找到了解决方案。你可以看看这里您可以通过此链接

您必须在主应用程序中注册调度程序 servlet,并且不要使用 @SpringBootApplication 注释。

对于完整的示例,只需签出项目并检查代码

编辑:本周晚些时候我将提供详细的答案