Using multiple dispatcher servlets / web contexts with spring boot

后端 未结 2 1919
一个人的身影
一个人的身影 2020-12-04 18:40

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

@Configuration
public class MainApiApplic         


        
2条回答
  •  伪装坚强ぢ
    2020-12-04 19:01

    As @josh-ghiloni already said, you need to register a ServletRegistrationBean for every isolated web context you want to create. You need to create an application context from a xml or java config class. You can use @Import and @ComponentScan annotation to add shared services to the parent context. Here is an example:

    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;
        }
    }
    

提交回复
热议问题