在Spring Boot中使用多个调度程序Servlet / Web上下文

I created a spring boot application with a parent context (services) and child context (spring-webmvc controllers):

@Configuration

public class MainApiApplication {

public static void main(String[] args) {

new SpringApplicationBuilder()

.parent(Services.class)

.child(ApiOne.class, MainApiApplication.class)

.run(args);

}

@Bean

public EmbeddedServletContainerFactory servletContainer() {

return new TomcatEmbeddedServletContainerFactory();

}

}

现在,我想为ApiTwo.class配置添加另一个客户端上下文(和DispatcherServlet)。我认为我必须做两件事:

  1. 将servletContainer(因此MainApiApplication.class配置)移出子上下文,然后
  2. 添加路径映射/ one /-> ApiOne.class和/ two / ApiTwo.class

spring boot是怎么做的?

回答:

正如@ josh-ghiloni所说,你需要为ServletRegistrationBean要创建的每个隔离的Web上下文注册一个。你需要从xml或java config类创建应用程序上下文。你可以使用@Import@ComponentScan注释将共享服务添加到父上下文。这是一个例子:

import org.springframework.boot.SpringApplication;

import org.springframework.boot.context.embedded.ServletRegistrationBean;

import org.springframework.context.annotation.Bean;

import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import org.springframework.web.context.support.XmlWebApplicationContext;

import org.springframework.web.servlet.DispatcherServlet;

//@ComponentScan({"..."})

//@Import({})

public class Starter {

public static void main(String[] args) throws Exception {

SpringApplication.run(Starter.class, args);

}

@Bean

public ServletRegistrationBean apiV1() {

DispatcherServlet dispatcherServlet = new DispatcherServlet();

XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();

applicationContext.setConfigLocation("classpath:/META-INF/spring/webmvc-context.xml");

dispatcherServlet.setApplicationContext(applicationContext);

ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, "/api/1/*");

servletRegistrationBean.setName("api-v1");

return servletRegistrationBean;

}

@Bean

public ServletRegistrationBean apiV2() {

DispatcherServlet dispatcherServlet = new DispatcherServlet();

AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();

applicationContext.register(ResourceConfig.class);

dispatcherServlet.setApplicationContext(applicationContext);

ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, "/api/2/*");

servletRegistrationBean.setName("api-v2");

return servletRegistrationBean;

}

}

以上是 在Spring Boot中使用多个调度程序Servlet / Web上下文 的全部内容, 来源链接: utcz.com/qa/404240.html

回到顶部