Saturday, January 18, 2014

Understanding Spring Web Initialization

Few years ago majority of us were used to write XML config files everywhere, to setup even simple Java EE application. Today using Java or Groovy to configure projects is becoming preferred way - you just need to take a look at Gradle or functionalities introduced in further versions of the Spring Framework to gen up on this.

Now I'll deal with configuring Spring contexts for web application.

Java EE provides ServletContainerInitializer interface, which allows libraries to be notified of a web application startup. Since Spring 3.1 we have SpringServletContainerInitializer class which handles WebApplicationInitializer by instantiating all found classes implementing this interface, sorting them basing on @Order annotation (non-annotated classes gets the highest possible order, so they are processed at the end) and invoking onStartup() method.


Spring since version 3.2 provides us a few classes implementing WebApplicationInitializer interface, from which first is AbstractContextLoaderInitializer. This class included in spring-web module uses abstract createRootApplicationContext() method to create application context, delegates it to ContextLoaderListener which then is being registered in the ServletContext instance. Creating application context using this class looks as follows:
public class SpringAnnotationWebInitializer
  extends AbstractContextLoaderInitializer {

  @Override
  protected WebApplicationContext createRootApplicationContext() {
    AnnotationConfigWebApplicationContext applicationContext =
      new AnnotationConfigWebApplicationContext();
    applicationContext.register(SpringAnnotationConfig.class);
    return applicationContext;
  }

}

That was the simplest way to start up Spring web context. But if we want to experience benefits provided by Spring MVC and don't want to manually register DispatcherServlet it'll be better to use another class: AbstractDispatcherServletInitializer. It extends previous class and adds two abstract methods: createServletApplicationContext() and getServletMappings().  First method returns WebApplicationContext that will be passed to DispatcherServlet, which will be automatically added into container ServletContext. Please notice that this context will be established as a child of the context returned by createRootApplicationContext() method. Second method - as you have probably already deduced - returns mappings that are used during servlet registration. You can also override getServletFilters() method if you need any custom filters, because default implementation returns just empty array. Exemplary implementation using this class could be:
public class SpringWebMvcInitializer
  extends AbstractDispatcherServletInitializer {

  @Override
  protected WebApplicationContext createRootApplicationContext() {
    AnnotationConfigWebApplicationContext applicationContext =
      new AnnotationConfigWebApplicationContext();
    applicationContext.register(SpringRootConfig.class);
    return applicationContext;
  }

  @Override
  protected WebApplicationContext createServletApplicationContext() {
    AnnotationConfigWebApplicationContext applicationContext =
      new AnnotationConfigWebApplicationContext();
    applicationContext.register(SpringMvcConfig.class);
    return applicationContext;
  }

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

}

And now last but definitely not least class: AbstractAnnotationConfigDispatcherServletInitializer. Here we can see further step in simplifying Spring initialization - we don't need to manually create contexts but just set appropriate config classes in getRootConfigClasses() and getServletConfigClasses() methods. I hope you are already familiar with those names, because they works exactly like in the former case. Of course due to this class extends AbstractDispatcherServletInitializer we can still override getServletFilters(). Finally we can implement our configuration in the following way:
public class SpringWebMvcSimpleInitializer
  extends AbstractAnnotationConfigDispatcherServletInitializer {

  @Override
  protected Class<?>[] getRootConfigClasses() {
    return new Class[] {SpringRootConfig.class};
  }

  @Override
  protected Class<?>[] getServletConfigClasses() {
    return new Class[] {SpringMvcConfig.class};
  }

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

}

If you like to see wider context please follow examples in my GitHub repo: https://github.com/jkubrynski/spring-java-config-samples/

7 comments:

nanosik said...

Great job Kuba, as always :)

Tomasz Biczel said...

Spring Boot is also a great addition to the Spring family especially for smaller projects and on the beginning of the development.

Jakub Kubrynski said...

You're right, but problem with Spring Boot are big lacks in documentation. Unfortunatelly recently we had to abamdon it due to interation testing problems. But iI think that Comditional introduced in Spring 4 is really powerful and it will move development simplification to the next level :)

del65 said...

Spring Roo is also a great way to start and configure a simple Spring project from scratch (and update it afterwards).

Jakub Kubrynski said...

The problem with Spring Roo is that it generates code that your have to maintain later. Spring Boot is operating on "convention over configuration" and that's its power :)

sanjeev sinha said...

Hello,

I tried the same.

In my case the getRootConfigClasses does not return the ApplicationConfig class where I do the JPA config.What could be the potential reason behind that.
This how the logs is:
6:38:35,992 INFO [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/odb]] (ServerService Thread Pool -- 139) Spring WebApplicationInitializers detected on classpath: [com.amadeus.odb.config.RestWebApplicationInitializer2@366a0fd0]
16:38:36,107 INFO [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/odb]] (ServerService Thread Pool -- 139) Initializing Spring FrameworkServlet 'dispatcher',

Then I was expecting Persistence unit log to appear, which is not happening.
An hint would be of great help.
Thanks
Sanjeev.

Jakub Kubrynski said...

Sanjeev - could you provide more details? Maybe you're able to share some code on Github?