我创建了一个带有父上下文(服务)和子上下文(spring-webmvc控制器)的spring启动应用程序:
@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)。我想我必须做两件事:
春季引导方式是什么?
答案 0 :(得分:26)
正如@josh-ghiloni已经说过的那样,您需要为要创建的每个隔离的Web上下文注册ServletRegistrationBean
。
您需要从xml或java配置类创建应用程序上下文。您可以使用@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;
}
}
答案 1 :(得分:8)
创建一个声明servlet及其映射的ServletRegistrationBean
。您可能还希望从调用的自动配置中排除DispatcherServletAutoConfiguration
,因为它会在DispatcherServlet
注册/
并覆盖您的<{p}}
编辑尽管下面的评论说你可能不需要这个,但除非你需要在不同的端口上运行你的API(并且听起来不像你这样做),Dave Syer,其中一位作者Spring Boot回答了一个非常相似的问题:Configure multiple servletcontainers/servlets with spring boot