spring boot,Where's the Root WebApplicationContext and Servlet WebApplicationContext

Viewed 1057

I use spring-boot-starter-web 1.5.17.I can't find any auto configuration about build Root WebApplicationContext and Servlet WebApplicationContext.

When not use spring boot,we need do this

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected String[] getServletMappings() {
    return new String[]{"/"};
}


@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class<?>[]{SecurityAdminConfig.class, DataSourceConfig.class, JavaConfig.class};
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class<?>[]{WebMvcConfig.class};
}
//controller、service

I know WebMvcAutoConfiguration do a lot of spring MVC configuration,but i can't find about auto build Root WebApplicationContext and Servlet WebApplicationContext.

public abstract class AbstractAnnotationConfigDispatcherServletInitializer
    extends AbstractDispatcherServletInitializer {

@Override
protected WebApplicationContext createRootApplicationContext() {
    Class<?>[] configClasses = getRootConfigClasses();
    if (!ObjectUtils.isEmpty(configClasses)) {
        AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
        rootAppContext.register(configClasses);
        return rootAppContext;
    }
    else {
        return null;
    }
}

@Override
protected WebApplicationContext createServletApplicationContext() {
    AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
    Class<?>[] configClasses = getServletConfigClasses();
    if (!ObjectUtils.isEmpty(configClasses)) {
        servletAppContext.register(configClasses);
    }
    return servletAppContext;
}


protected abstract Class<?>[] getRootConfigClasses();


protected abstract Class<?>[] getServletConfigClasses();

}

How can know this beans go Root WebApplicationContext or Servlet WebApplicationContext?

image here

2 Answers

There is, by default, a single application context in a Spring Boot web (or otherwise) application. It is created by SpringApplication when your application starts.

The right way to do it would be this:

public class App {
    public static void main(String[] args) {
        new SpringApplicationBuilder()
          .parent(ParentConfig.class).web(WebApplicationType.NONE)
          .child(WebConfig.class).web(WebApplicationType.SERVLET)
          .sibling(RestConfig.class).web(WebApplicationType.SERVLET)
          .run(args);
    }
}

I have taken it from here: However, it is still not clear why by default everything is in the same context.. Also, I am not sure if that's fine that other beans created by WebMvcAutoconfiguration will be shared across all child contexts.

Related