Spring 3.1 – Constructor Namespace

by
Tags:
Category:

Spring Namespaces

Spring provides several namespaces to simplify XML configuration, such as jdbc, tx, aop, etc. We Spring developers are already familiar with the required beans namespace.


  
  

Spring Namespaces are defined at the top of the XML file. Here we define the namespaces we need to use, and reference the schema (XSD) that validates the XML.



    
    

In Spring XML configuration we declare dependency injection with either “setter injection” (via properties tag) or “constructor injection”. Spring already provided the Property or “p” namespace, to simplify property setting, in other words, invoking setters on a bean.

Here we have a simple bean that can be configured with either a constructor or setter.

public class SimpleBean {
  private String myString;
  private String myOtherString;
  public SimpleBean() {}
  public SimpleBean(String myString) {
    this.myString = myString;
} public SimpleBean(String myString, String other) { this.myString = myString; this.myOtherString = other; } public String getMyString() { return myString; } public String getMyOtherString() { return myOtherString; } }

Instead of:



    
        
    

We could use:



  

With the Property namespace, there is no significant benefit, it is simply a matter of preference.

Spring Constructor Injection

Some developers choose to use “constructor injection” for several reasons.

  • Setting required elements
  • Immutable classes for thread safety
  • Third party class that only provides constructor setting

One of the main issues with “constructor injection”, prior to Spring 3.1, is that it is unclear which arguments are being set in the constructor injection. Also, if the constructor has multiple arguments, one can inadvertently set arguments in the wrong sequence.



  
    
    
  

Spring 3.1 Constructor “c” Namespace

Unlike the “p” namespace, the “c” namespace provides us with descriptive references, allowing us to reference the constructor’s arguments by name. This feature is even more useful when we have multiple constructor arguments, as below.



  

Deployment Requirements

NOTE: Code using the “c” namespace, MUST be deployed with Java Debugging Tables (the -g option)!

Summary

We Spring developers have shortcuts at our disposal to make configuration easier or less terse. The new “c” namespace provides us the benefit of named variables that we know from using the “p” namespace or . We should strive to make our beans immutable for thread safety. By using the “c” namespace get the developers lean towards property setting for readability.

Notice that both the “p” ad “c” namespaces do not have a schema reference in the XML header.