|
| 1 | +package org.baeldung.config; |
| 2 | + |
| 3 | +import java.util.Set; |
| 4 | + |
| 5 | +import javax.servlet.ServletContext; |
| 6 | +import javax.servlet.ServletException; |
| 7 | +import javax.servlet.ServletRegistration; |
| 8 | + |
| 9 | +import org.springframework.web.WebApplicationInitializer; |
| 10 | +import org.springframework.web.context.ContextLoaderListener; |
| 11 | +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; |
| 12 | +import org.springframework.web.servlet.DispatcherServlet; |
| 13 | + |
| 14 | +public class MainWebAppInitializer implements WebApplicationInitializer { |
| 15 | + |
| 16 | + public MainWebAppInitializer() { |
| 17 | + super(); |
| 18 | + } |
| 19 | + |
| 20 | + // |
| 21 | + |
| 22 | + /** |
| 23 | + * Register and configure all Servlet container components necessary to power the web application. |
| 24 | + */ |
| 25 | + @Override |
| 26 | + public void onStartup(final ServletContext sc) throws ServletException { |
| 27 | + System.out.println("MyWebAppInitializer.onStartup()"); |
| 28 | + |
| 29 | + // Create the 'root' Spring application context |
| 30 | + final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); |
| 31 | + root.scan("org.baeldung.config.parent"); |
| 32 | + // root.getEnvironment().setDefaultProfiles("embedded"); |
| 33 | + |
| 34 | + // Manages the lifecycle of the root application context |
| 35 | + sc.addListener(new ContextLoaderListener(root)); |
| 36 | + |
| 37 | + // Handles requests into the application |
| 38 | + final AnnotationConfigWebApplicationContext childWebApplicationContext = new AnnotationConfigWebApplicationContext(); |
| 39 | + childWebApplicationContext.scan("org.baeldung.config.child"); |
| 40 | + final ServletRegistration.Dynamic appServlet = sc.addServlet("api", new DispatcherServlet(childWebApplicationContext)); |
| 41 | + appServlet.setLoadOnStartup(1); |
| 42 | + final Set<String> mappingConflicts = appServlet.addMapping("/"); |
| 43 | + if (!mappingConflicts.isEmpty()) { |
| 44 | + throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | +} |
0 commit comments