Many people ask about me Spring’s XML format and question its verbosity. In this post I’d like to elaborate on Spring’s XML structure in general, some enhancements we made in Spring 1.2 and a short preview on what we’ll be adding in Spring 1.3.
To XML or not to XML
As most of you might know, there’s a long-running debate on the purpose of XML. XML in the Java-world is generally seen as a language which shouldn’t be used for procedural programming. By some people, one of the better examples of this ‘bad practice’ is considered to be Jelly.
I personally agree that XML shouldn’t be used to do scripting. XML documents should contain data. The data can be related to a particular business domain, but it might just as well be technical data.
In Spring, XML is used to inject objects with objects they depend on. In other words, the XML is used to ‘assemble’ your application from a number of components or classes you or other people have developed. The XML represents the static assembly of your application, the object graph that makes your application. Using Spring’s Dependency Injection container with the XML format it offers, you completely decouple you application code from the assembly of the final application the code is supposed to function in. Other people (like Keith and Dhananjay Nene more recently on TSS) elaborate more on the concept of Dependency Injection. I want to focus on Spring’s XML format and the benefits it brings.
To conclude to discussion on XML, I think that XML is a perfect way to express the static assembly of your application; the configuration that is needed to get things going. Actual behavior related to the problem your application is solving shouldn’t be coded in XML. That’s what the application code is for.
Spring’s XML format
Spring was first released in March 2004. In the first version the XML in some places got a bit verbose. Overall, the format for defining properties was verbose as well (for a reason, which we’ll review later). More than 300.000 downloads, 2 major releases and 9 minor ones later there have numerous enhancements and additions to the Spring Framework. One of the key areas in which improvements have been made is the XML format. In the next section I’ll guide you through some of the enhancements that have been made in 1.2 in particular, but also in the earlier releases. And still we’re not finished. Spring 1.3 will include a major new feature that will allow for even more compact XML that you will be able to customize to your own specific needs if you want. I’ll shortly elaborate on this as well.
Before we go on, I’d like to stress that I (and I think the Spring team as a whole) think the decision to begin with a consistent and simple XML format has been a really good one. The XML format Spring started out with is still usable and without any exception it covers all you need. If we would have gone for an XML format more tailored at specific use cases of the Spring Framework, first of all, the framework wouldn’t have been so extensible and usable as it is right now. Also, you probably would have found yourself in situations where the XML doesn’t suit the requirements you’re having. Things probably wouldn’t have been that flexible. The XML format Spring currently features is tailored to Dependency Injection and nothing more. As I’ve said already, 1.3 will include enhancements that will go beyond just that and will focus on more that just expressing object-types, dependencies and other properties.
The following is a detailed piece on a couple of enhancements that were made to the XML format since 1.0. I’ll try to keep historic discussions to a minimum but focus on real-world use cases and best practices instead.
Defining properties and bean references
One of the major enhancements in 1.2 was the addition of a simpler format for defining properties. The good-old way of defining properties was the following:
<bean class="example.Person"> <property name="firstName"> <value>Alef</value> </property> </bean>
In 1.2, things have changed. From now on, you don’t need to include the nested value-tag anymore. Instead you can use the value-attribute. This comes with a small limitation however. Attributes aren’t allowed to contain <![CDATA]>, so if you want to specify CDATA text as the value for a specific property, you still need to use the nested value-tag (of course the old format is still supported). Here’s an example of how this new feature makes your XML much more concise:
<bean class="example.Person"> <property name="firstName" value="Alef"/> </bean>
Bean references in Spring 1.0 and 1.1 had to be defined using the nested or format where the latter points to a bean definition defined in the same XML file (XML ID are used here so validation of the XML will fail of you haven’t defined the bean). In Spring 1.2, what we’ve done for properties, has also been applied to the definition of bean references. In short, this comes down the following:
<bean id="someGirl" class="example.Person"/> <bean class="example.Person"> <property name="spouse" ref="someGirl"/> </bean>
instead of
<bean class="example.Person"> <property name="spouse"> <ref bean="someGirl"/> </property><property> </property></bean>
Factory and lookup methods
Spring is one fancy factory, we all know that. Sometimes however, you might need to incorporate a good-old factory in your application context. For some reason, you might not be able to get that old-style configuration out of the way (you might for example not have control over the code). In Spring 1.0, one thing you could use was the MethodInvokingFactoryBean, a FactoryBean that retrieves an object by calling a static method on a class or an instance method on a bean defined elsewhere in the context. This resulted in a bunch of XML. In Spring 1.1, short-hand ways to get this behavior have been introduced:
class MyStaticSpoolerFactory {
public Spooler getInstance()
}
class Spooler {
public Monitor getMonitor();
Considering the above class, you can now use:
<bean id="mySpooler" class="example.MyStaticFactory" factory-method="getInstance"/> <bean id="myMonitor" factory-bean="mySpooler" factory-method="getMonitor"/> <!-- pass the spooler monitor to a screen outputting status --> <bean class="example.MonitorScreen"> <property name="monitor" ref="myMonitor"/> </bean>
instead of
<bean id="mySpooler" class="org.sprfr.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetClass"> <value>example.MyStaticFactory</value> </property> <property name="targetMethod"> <value>getInstance</value> </property> </bean> <bean id="myMonitor" class="org.sprfr.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetObject"> <ref local="mySpooler"/> </property> <property name="targetMethod"> <value>getMonitor</value> </property> </bean> <bean class="example.MonitorScreen"> <property name="monitor"> <ref local="myMonitor"/> </property> </bean>
More info by the way on factory methods can be found in one of my previous posts.
Defining collections
Spring has supported the use of collections since it was first released. There are a couple of interested things you might not now about defining collections:
<property name="myList"> <list> <value>Alef</value> </list> </property>
is in fact the same as:
<property name="myList" value="Alef"/>
Of course the same works for a java.util.Set.
Note that this only works for a single value. The PropertyEditor machinery doesn’t support delimiting multiple elements by commas or things like that.
Inner beans
A feature not really spoken about that much is the ability to define so-called inner beans. Not only do inner beans result in more consistent XML, it also allows you to ‘hide’ beans from the entire context.
<bean class="example.Person"> <property mame="firstName" value="Alef"/> <property name="children"> <list> <bean class="example.Person"> <property name="firstName" value="Peggy"/> </bean> <bean class="example.Person"> <property name="firstName" value="Ricky"/> </bean> </list> </property> </bean>
is much concise as
<bean class="example.Person"> <property name="firstName" value="Alef"/> <property name="children"> <list> <ref local="peggy"/> <ref local="ricky"/> </list> </property> </bean> <bean id="peggy" class="example.Person"> <property name="dateOfBirth" value="20040607"/> <property name="firstName" value="Peggy"/> </bean> <bean id="ricky" class="example.Person"> <property name="dateOfBirth" value="20040607"/> <property name="firstName" value="Ricky"/> </bean>
Also, in the last example, both Alef as well as Maggy and Ricky are ‘first-class citizens’ in the Spring context. context.getBean("ricky") will give you the ricky bean while this might not be what you really want.
Inner beans were already part of Spring 1.0, however since then support has greatly increased. In earlier version for example, life cycle support wasn’t as good as it is now. Inner beans right now enjoy the same power as full-fledged beans.
Bean hierachies (parent and abstract)
In the example above, we saw some repition in the sense that for each bean we had to specify that it was of type example.Person and we also had to specify the date of birth for both Peggy and Ricky (question: are they twins?
).
Using Spring’s parent feature, you can leave out common properties of beans by specifying a parent. Let’s have a look at the parent feature at work:
<bean id="peggy" class="example.Person"> <property name="dateOfBirth" value="20040607"/> <property name="firstName" value="Peggy"/> </bean> <bean id="ricky" parent="peggy"> <property name="firstName" value="Ricky"/> </bean>
In the above example, the ricky bean inherits all its properties from the peggy bean. It overrides however, the firstName property. This results in two beans, both of type example.Person, each with the same date of birth, but with a different first name.
Parent beans allows you to change the class as well. So we could also change the example to the following:
<bean id="peggy" class="example.Girl"> <property name="dateOfBirth" value="20040607"/> <property name="firstName" value="Peggy"/> </bean> <bean id="ricky" class="example.Boy"> <property name="firstName" value="Ricky"/> </bean>
If you’ve seen this, you might in fact ask whether or not it’s possible to define abstract beans also. Well, as a matter of fact, it is! Let’s change the sample around a bit again:
<bean id="alef" class="example.Person"/> <bean id="oneOfTheTwins" abstract="true"> <property name="parent" ref="alef"/> <property name="dateOfBirth" value="20040607"/> </bean> <bean id="ricky" parent="oneOfTheTwins" class="example.Boy"> <property name="firstName" value="Ricky"/> </bean> <bean id="ricky" parent="oneOfTheTwins" class="example.Girl"> <property name="firstName" value="Peggy"/> </bean>
As you can see, it’s pretty much possible to elimate all repitition using parent/child beans and the abstract feature.
Note that abstract beans are not instantiated by the Spring Dependency Injection container, nor will they be returned if you ask for them programmatically (context.getBean("oneOfTheTwins") that is).
Autowiring
Another interesting feature that not many of you might have seen is Spring’s autowiring capability. Spring heavily relies on reflection to inject dependencies and properties (not that this doesn’t impact performance really, since the larger part of your beans will be instantiated when the context or application is starting up–after that, no reflection is needed anymore since the beans have already been configured). Using reflection, Spring can also detect and automatically satisfy those dependencies. I will give a simple example here. For more in-depth information you should definitely have a look at the Spring reference manual where autowiring is covered in much more detail.
class MyDependency {
}
class MyManager {
public void setDependency(MyDependency dep) {
// assign dep to field
}
}
If we consider the above manager and dependency, we can wire them up as follows:
<bean class="example.MyManager"> <property name="dependency" ref="myDependency"/> </bean> <bean id="myDependency" class="example.MyDependency"/>
Using autowiring however, we can leave our the property element from the first bean definition, leaving us with just two one-liners:
<bean class="example.MyManager" autowire="byType"/> <bean id="myDependency" class="example.MyDependency"/>
Of course, the above example doesn’t really add much value, since it’s such a simple configuration. But in large projects, it might in fact come in quite handy.
Spring’s autowiring feature can be used in one of four modes:
- By type: Spring will try to satisfy dependencies based on the type (Class) defined in the JavaBean setter. This is what we used in the above example
- By name: using this mode, Spring will satisfy dependencies by bean name. If we would rename the
myDependencybean in the above example todependencyit would work as well, since the JavaBean setter has the same ‘name’ as the name of the bean - By constructor: will result in autowiring of the bean’s constructor instead of JavaBeans setters
- Automatic: automatic autowiring is also supported. Spring will try to find the way it can satisfy the largest amount of dependencies of a specific bean. This works somewhat automagically and I must admit that I’m not a big fan of this specific type of autowiring
Personally I don’t use autowiring that much since I a pretty fast typer and I’d like to get things right and leave it with that. Some people however tend to use autowiring while prototyping parts of an application. The top-level beans element allows you to switch autowiring on or off for the entire context. Using this feature, the only thing you need to do if you define a new bean is add it to the context. Dependencies will then be automatically satisfied. If you go into production however, I suggest you change the remove the default autowiring attribute and make all dependencies explicit though bean references since they provide excellent documentation on how the application is assembled from its individual components.
There’s more where that came from
I hope I’ve shown you some features Spring has that will allow you to create more consistent and readable XML. There are certainly more interesting ways to keep the XML manageable. Be sure to check the reference documentation and the Spring Beans DTD for more info on how Spring XML works.
XML simplification coming in Spring 1.3
I promised to also shortly talk about our plans to include a major enhancement to the way Spring handles XML files to create beans. After a lot of discussion, we’ve finally got to a decent approach to allow for extending Spring’s XML format. To be able to target more specific use cases and to let the XML focus on more than just dependency injection, we’re about to implement some code that will allow you to do the following:
<j2ee :jndi id="dataSource" refName="java:comp/env/jdbc/MyDataSource"/>
to create a reference to a JNDI-based DataSource instead of
<bean class="org.sprfr.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/MyDataSource"/> </bean>
and
<instance :pooled id="parser" class="example.DocumentParser"> <property name="myConfigProperty" value="1"/> </instance>
to create a pooled version of the DocumentParser bean intead of the much more verbose XML fragment shown below.
<bean id="parser" class="org.sprfr.aop.framework.ProxyFactoryBean"> <property name="targetSource" ref="commonsPoolTargetSource"/> </bean> <bean id="commonsPoolTargetSource" class="org.sprfr.aop.target.CommonsPoolTargetSource"> <property name="maxSize" value="30"/> <property name="targetBeanName" value="parserTarget"/> </bean> <bean id="parserTarget" class="example.DocumenParser"/>
We still have to work out how this will work in detail but the first test cases have been completed successfully and to be honest, I’m pretty excited about this. The pooling example by the way has been taken from my previous entry on instance management.
p.s. For readers that know me: no I did not all of sudden get children, and if I had children, I certainly wouldn’t have named them Peggy and Ricky.

The enormous size of the XML files has been my main complaint of Spring, this is great step in the right direction.
Less XML is nice, but why have any XML at all? Why not write a simple Java method to assemble your application, as you would in a unit test?
The problem with XML is that it’s not refactorable unless someone writes a special plugin. Even basic things like “show usages” don’t work, let alone using “extract method” to factor out repeated parts of your assembly specification.
This looks promising,keep on pushing it.
That’s a great summary, cheers.
I’ve written down how I do Spring Schema Extension: http://jroller.com/page/SKI_BUM/20050713#spring_schema_extension_or_spring
From a totally different approach, I started a poject a month ago(http://www.sourceforge.net/projects/jacn), aiming to get rif of XML alltogether. The idea is to use a subset of Java syntax to “declare” object relationships in a valid Java source file. The runtime will decompile the class files to extract the relationship and build a DOM to pass to the Spring bean definition engine. Right now I’m test-using it in a project with over 50 managed beans. It’s getting quite useable… The experience has been quite refreshing.
ringtones free