Bootstrapping a web application with Spring 3.1 and Java based Configuration, part 1

DZone 's Guide to

Bootstrapping a web application with Spring 3.1 and Java based Configuration, part 1

· Java Zone ·
Free Resource

1. Overview

This is the first of a series of posts about setting up a RESTfull web application using Spring 3.1 with Java based configuration. The post will focus on bootstrapping the web application, discussing how to make the jump from XML to Java without having to completely migrate the entire XML configuration.

2. The Maven pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
   xsi:schem	aLocation=
   "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


         <name>Springframework Maven Snapshot Repository</name>



2.1. Justification of the cglib dependency

You may wonder why cglib is a dependency – it turns out there is a valid reason to include it – the entire configuration cannot function without it. If removed, Spring will throw:

Caused by: java.lang.IllegalStateException: CGLIB is required to process @Configuration classes. Either add CGLIB to the classpath or remove the following @Configuration bean definitions

The reason this happens is explained by the way Spring deals with @Configuration classes. These classes are effectively beans, and because of this they need to be aware of the Context, and respect scope and other bean semantics. This is achieved by dynamically creating a cglib proxy with this awareness for each @Configuration class, hence the cglib dependency.

Also, because of this, there are a few restrictions for Configuration annotated classes:

  • Configuration classes should not be final
  • They should have a constructor with no arguments

2.2. The cglib dependency in Spring 3.2

Starting with Spring 3.2, it is no longer necessary to add cglib as an explicit dependency. This is because Spring is in now inlining cglib – which will ensure that all class based proxying functionality will work out of the box with Spring 3.2.

The new cglib code is placed under the Spring package: org.springframework.cglib (replacing the original net.sf.cglib). The reason for the package change is to avoid conflicts with any cglib versions already existing on the classpath.

Also, the new cglib 3.0 is now used, upgraded from the older 2.2 dependency (see this JIRA issue for more details).

3. The Java based web configuration

@ImportResource( { "classpath*:/rest_config.xml" } )
@ComponentScan( basePackages = "org.rest", excludeFilters = { @Filter( Configuration.class ) } )
public class WebConfig{
   public PropertyPlaceholderConfigurer properties(){
      PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
      		Resource[] resources = new ClassPathResource[ ] {
         new ClassPathResource( "persistence.properties" ),
         new ClassPathResource( "restfull.properties" )
      ppc.setLocations( resources );
      ppc.setIgnoreUnresolvablePlaceholders( true );
      return ppc;

First, the @Configuration annotation – this is the main artifact used by the Java based Spring configuration; it is itself meta-annotated with @Component, which makes the annotated classes standard beans and as such, also candidates for component scanning. The main purpose of @Configuration classes is to be sources of bean definitions for the Spring IoC Container. For a more detailed description, see the official docs.

Then, @ImportResource is used to import the existing XML based Spring configuration. This may be configuration which is still being migrated from XML to Java, or simply legacy configuration that you wish to keep. Either way, importing it into the Container is essential for a successful migration, allowing small steps without to much risk. The equivalent XML annotation that is replaced is:

<import resource=”classpath*:/rest_config.xml” />

Moving on to @ComponentScan – this configures the component scanning directive, effectively replacing the XML:

<context:component-scan base-package=”org.rest” />

The configuration classes are filtered/excluded out of component scanning; this is because they are already specified to and used by the Container – allowing them to be rediscovered and introduced into the Spring context will result in the following error:

Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name ‘webConfig’ for bean class [org.rest.spring.WebConfig] conflicts with existing, non-compatible bean definition of same name and class [org.rest.spring.WebConfig]

And finally, using the @Bean annotation to configure the properties supportPropertyPlaceholderConfigurer is initialized in a @Bean annotated method, indicating it will produce a Spring bean managed by the Container. This new configuration has replaced the following XML:

location=”classpath:persistence.properties, classpath:restfull.properties”

3.1. The web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   id="WebApp_ID" version="3.0">
      <welcome-file />

First, the DispatcherServlet is configured to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext. The newer AnnotationConfigWebApplicationContext accepts @Configuration annotated classes as input for the Container configuration and is needed in order to set up the Java based context.

Unlike XmlWebApplicationContext, it assumes no default configuration class locations, so the “contextConfigLocation” init-param for the servlet must be set. This will point to the fully qualified name(s) of the Java based Spring configuration.

Other than this, the web.xml doesn’t really change from a XML to a Java based configuration.

4. Conclusion

The presented approach allows for a smooth migration of the Spring configuration from XML to Java, mixing the old and the new. This is important for older projects, which may have a lot of XML based configuration that cannot be migrated all at once. This way, the web.xml and bootstrapping of the application is the first step in a migration, after which the remaining XML beans can be ported in small increments.

In part 2, I will cover the MVC configuration and how to set up a RESTful API with JSON payload with only Java based configuration. In the meantime, you can check out the github project.


Published at DZone with permission of Eugen Paraschiv , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}