Its Better in Spring

Friday, June 09, 2006

Architects Introduction to Spring


In today’s era, developing software applications is hard enough even with good tools and technologies. There are tools and frameworks in the market that claim will do everything, but they turn out to be heavy-weight & inflexible. They introduce heavy dependency in the project & demand a complete understanding of its inner workings.
Bruce Tate terms this as a Framework Bloat.
*Better, Faster, Lighter Java
Also, mega frameworks come with lot of buzzwords. Words such as ‘revolutionizes’, ‘cross-platform’, ‘services’, ‘global’ etc. which are overused & abused have caused them to lose their intrinsic meaning. They might be good catch phrases, targeting primarily the CIO’s, CTO’s etc, but for an Architects it’s a nightmare. Morever, let’s not forget the 3-letter oversimplified acronyms used by these big vendors. In simple words, it’s too much FLUFF without any STUFF [.

Spring Framework

So, why Spring? Most of you might already feel the urge to close this document, because they had enough of new open-source frameworks. The urge might further strengthen, after I mention that Spring can only be configured through XML , because if you’re using Struts/Tiles/Validator/EJB’s you already experienced the XML Over-usage Syndrome. But I promise it will be worth while reading this article.

It will be sensible to first explore the real problem that Spring is trying to resolve. A typical scenario in any project would be the usage of DataSource object for data interactions. Since most of the data-sources are configured in the J2EE compliant servers, we would typically need to write the necessary plumbing code to fetch this data-source, preferably through JNDI lookup. I wouldn’t waste my time in writing all of that code here, but I will show you how easy it is to configure this in Spring.

Listing 1.1
<bean id="configuredDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName"><value>${jdbc.jndi}</value></property>

Don’t worry about the XML syntax or Spring specific objects being used above. But focus on how a configuredDataSource is fetched by looking up in the JNDI tree through a system property jdbc.jndi value. The key here is that your code will receive an already configured java.sql.DataSource object without writing any JDBC or Spring dependent code.

Another typical scenario that almost all projects have to deal with is controlling the database updates through transaction demarcation. The following code indicates how transaction management is probably done in the code using JDBC.

Listing 1.2
try {
///do your work
} catch (…) {
} finally {
try {
stat.close(); con.close();

With Spring, you wouldn’t have to worry about such mundane tasks, as shown…

Listing 1.3
<property name="transactionAttributes">
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>

Again don’t worry about what and where to configure them, instead focus on how transaction boundaries are being set on methods that start with certain pattern, for e.g. in the above partial configuration section, I am forcing transaction to be required for all the inserts, updates and deletes , where as I am enforcing read-only calls on the methods other than inserts/updates/delete methods.

Furthermore, it relieves the Business Objects and Dao’s from manually setting their own transaction boundaries . Also note that your code still is 100% Spring free.

Listing 1.4
try {
//do your work
} catch(..) { log… }

What is Spring?

Spring is a light-weight container written entirely in Java. It was written from ground up so that you don’t have to. Spring is one-stop-shop for all your enterprise needs. Spring is supported and recommended by the community and has been widely accepted by most enterprise architects for the flexibility and simplicity it offers. Above all, Spring doesn’t introduce any dependencies in your code.
Spring's main aim is to make J2EE easier to use and promote good programming practice.

But I was skeptical and timid when I was exposed to Spring for the first time, just like you. But after trying it & using it, I saw the obvious advantages of using it in the projects.

At the core lie two important aspects, POJO, IoC. Let’s first discuss what a POJO means.

*The term was coined while Rebbecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely
*Martin Fowler on POJO

POJO simply means a normal Java Object that is NOT an EntityBean, a SessionBean or any type of object that inherits or adapts to any of the heavy-weight framework classes. POJO’s are inherent to the project and represent a solution for a problem of Essential Difficulty .

Finally, let’s define Dependency Injection

In computer programming, Inversion of Control (IOC), or also called Dependency Injection is a popular Object-oriented programming principle which inverts the way an object gets its dependencies
*wikipedia entry

Dependency Injection means that the classes are provided with the dependencies instead of them looking up for the dependencies.
In J2EE environment, classes need to interact with the J2EE compliant server for enterprise objects in order to leverage the services offered by the server. But, as we all know, it is a daunting task to do the lookups and configuration, just to get an enterprise object for e.g. a home interface and not to mention all of the exception handling that needs to be handled for every call.
Spring abstracts these mundane tasks and handles the exceptions gracefully. Spring can inject these configured objects right into your classes, liberating the classes from the code bloat.

Following is a simple DAO class which can be termed as a POJO. Recollect from listing 1.1, we configured a DataSource through JNDI lookup, listing 1.2 shows how Spring injects the DataSource into the DAO class through DAO’s setter method. This is termed as Dependency Injection.

As you can see, the DAO still is 100% Spring Free and simply focuses on business logic. Also, as you notice, using XML configuration we are weaving objects to each other, where as the objects themselves have no idea about each other. Since the dependency is externalized, it greatly reduces versioning issues, gives us flexibility in replacing with better performance classes, change behavior of classes dynamically etc.

Listing 1.5
public class ActualDao extends AbstractDao {
private DataSource dataSource;
public void insertActualBean(ActualBean dataBean) {
//do your work

public void setDataSource (DataSource newSource) {
this.dataSource= newSource;

Listing 1.6 - XML Configuration File
<bean id=”actualDao” class=”<package>.ActualDao”>
<property name=”dataSource”><ref bean=”configuredDataSource”/></bean>

What about required skill-sets?

You might argue that developers will now have to be acquainted with the XML Syntax and Spring objects in order to successfully bind these objects. You’re argument is reasonable, since you’re worried about the dependency it would create in the project.
But, when you’re working under J2EE environment, you already have specific roles that each individual has to perform. You can extend these existing roles to incorporate Spring related tasks.

As per J2EE Specification
• Application Component Provider [ACP]

Application component providers produce the building blocks of a J2EE application. They typically have expertise in developing reusable components as well as sufficient business domain knowledge. Application component providers need not know anything about the operational environment in which their components will be used. There are multiple roles for application component providers, including HTML page authors, document programmers, enterprise bean developers, and so on. These roles use tools provided by a tool provider to produce J2EE components and applications

• Application Assembler [AA]

An application assembler takes a set of components developed by application component providers and assembles them into a complete J2EE application. Their expertise lies in providing solutions for a specific problem domain, for example, the financial industry. Application assemblers may not be familiar with the source code of the components that they use, but they use declarative descriptors for the components in order to know how to build applications from them. Like application component providers, they need not know anything about the operational environment in which their applications will be used. An application assembler will generally use GUI tools provided by either an application component provider or tool provider. An application assembler is responsible for providing assembly instructions describing external dependencies of the application that the deployer must resolve in the deployment process.

Application Assembler is the only person who needs to be aware of Spring related XML syntax and objects required for configuration purposes. As Application Component Provider, they simply need to focus on the business requirements and draft a list of services that they would need in order to perform their tasks.

Consider the e.g. where an ACP needs access to 3 different Dao’s to perform his task inside a Business Object, as show in the Listing 1.7.
All the ACP needs to do is provide the SETTER methods and have the AA know about these methods either through JavaDocs or class diagrams.
The AA will then configure all of the Dao’s and provide the DataSource to each one of them and finally set them to the Business Object as requested.

AA needs to be an expert in Spring framework where as ACP doesn’t need to know anything about Spring, exactly as described in their roles. In a typical J2EE project, you would see that AA is usually one person, where as ACP are in numbers.

Listing 1.7

public class ActualBusinessObject {
private ActualDao1 dao1;
private ActualDao2 dao2;
private ActualDao3 dao3;

public void doSomeActualTask(ActualBean dataBean) {

public void setActualDao1(ActualDao1 newDao1) { this.dao1= newDao1; }
public void setActualDao2(ActualDao2 newDao2) { this.dao2= newDao2; }
public void setActualDao3(ActualDao3 newDao3) { this.dao3= newDao3; }

Listing 1.8 XML Configuration

<!—- from listing 1.1: configured the datasource -->

<bean id=”dao1” class=”<package>.ActualDao1”>
<property name=”dataSource”><ref bean=”configuredDataSource” /></property>

<bean id=”dao2” class=”<package>.ActualDao2”>
<property name=”dataSource”><ref bean=”configuredDataSource” /></property>

<!—- same for dao3 -->

<bean id=”businesObject” class=”<package>.ActualBusinessObject”>
<property name=”actualDao1”><ref bean=”dao1”/></property>
<property name=”actualDao2”><;ref bean=”dao2”/></property>
<property name=”actualDao3”><ref bean=”dao3”/></property>

Again, the ActualBusinessObject is 100% Spring free .

Another subtle nature of Spring framework is Coding to Interfaces . Spring promotes good programming practices, and one such good practice is use of Interfaces. This allows a clear separation of concerns, allowing plug & play of implementations.

There is more to Spring than what you have seen in this article. In fact, Spring has solution for every J2EE compliant project. I have summarized the key advantages and highlights of Spring container at the end.

Why use Spring

1. Spring is based on IoC pattern, that means your classes are injected with dependencies instead of the classes binding to the dependencies directly.
2. Spring has excellent support for integrating Hibernate . Most Hibernate core factories can be easily loaded through Spring.
3. Spring supports Aspect Oriented Programming , which allows developers to modify existing classes without changing the classes themselves.
4. Spring has supporting classes for JSF/Struts/Tiles/Validator frameworks. That means you can configure your Struts actions in Spring.
5. Spring provides richer interfaces for resource, message & i18n handling.
6. Spring also provides Web framework called Spring Web Flow, ideal for web applications that guide the user through controlled navigations that drive business processes.
7. Acegi Security framework, based on Spring framework, is security framework that can be easily plugged in using J2EE projects. Acegi Security simply provides security interface to concrete security systems like LDAP, ACL, Database driven etc. Without ACEGI, you would have to write all of the code to interact with JAAS and other related modules.
8. Spring supports EJB configuration as well. This will relieve the client from retrieving home interfaces for looking up for objects in JNDI tree.
9. Spring provides services for JavaMail, JMS, JAXP, JTI, JTA, JNDI, JDBC, RMI, SOAP, Web-Services.
10. There are plug-in’s available for auto-generating configuration XML files for Spring.

In conclusion, using Spring alleviates the burden from developers in writing all of the plumbing code to work with the enterprise objects. Furthermore, it enforces good programming principles, like open-close, separation of concerns, design by contract etc.

For more information, please visit Spring website

Using AOP for Logging

We all know the importance of log files in the system. Though we might think they are mundane & trivial, they transform into god like figure during bug resolution. But logging shouldn't be responsibility of developers because they will either abuse it or completely forget about it.
The best of way of doing this is to intercept calls & log their outcome. Spring allows an excellent way of doing this through AOP support [Spring 2.0 has much better support for AOP framework & AspectJ]
First before we dwell into AOP, i would recommend you to get to know what exactly is AOP & terminologies associated with it. There is sufficient documentation @ Spring AOP Support
The general approach is to proxy an existing class by adding an advice [in this case a logger] to a set of joinpoints [that constitutes as pointcut]. But this could quickly become configuration nightmare. for e.g. imagine a class called UserService that we need to log using LoggingMethodInterceptor for every method call...

public class LoggingMethodInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation arg0) throws Throwable {“Before method call...
Object returnVal= arg0.proceed();“After method call...)
return returnVal;

The configuration file might look something like this…

<bean id="userServiceTarget" class="com.test.UserService"/>
<bean id="loggingInterceptor" class="com.test.LoggingInterceptor"/>
<bean id="userService" class="org.springframework.aop.framework.
<property name="target">
<ref bean="userServiceTarget"/>
<property name="interceptorNames">
Try doing this for every object declared in Spring!!! But we all know, Spring is smarter than that...
Spring provides us with ways to automatically configure objects declared in the context with the given interceptors...
Spring provides two classes org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator & org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator
Spring recommends usage of DefaultAdvisorAutoProxyCreator because of its ease of configuration.
But we need to first create a pointcuts for it to find in the context, which is very simple to do. The reason we need to do this is that AOP ProxyFactoryBean automatically creates the pointcuts for us. Since we are trying to autoproxy every class, we need to explicitly define pointcuts.

<bean id="loggerAdvice"  class="com.test.LoggingInterceptor"/>
<bean id="loggerInterceptor"
<property name="advice" ref="loggerAdvice"/>
<property name="pattern" value=".*Something.*"/>
Couple of things are happening here,
• we are declaring the pointcut to use regular expression pattern matching.
• second we are providing it with the advice it needs to execute when the pattern matches
• third we are providing with the pattern itself. In the above example, any method with following names will qualify, doSomething(); doSomethingElse(), doNothingSomething(), but following will fail, dosomething() because its case sensitive.
The pattern matching is quite simple, Spring uses JDK regular expression pattern matching. if one is not available then it falls back on Perl5 pattern matching.
To know more or test different patterns please visit ORO website There is an applet that allows you to test different patterns.

Finally our autoproxy class,

<bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>

That's it!! All the beans declared inside the context will be now proxied & the interceptor will log appropriate messages.

But this might not what you want, maybe you want to only log for those beans ending with name such as Service. for e.g. ReferralService, AccountService, UserService etc.
In such scenario, we could use the BeanNameAutoProxyCreator which expects a pattern for bean name matching, in this scenario *service

<bean class="org.springframework.aop.framework.autoproxy.

<property name="beanNames"><value>*Service</value></property>
<property name="interceptorNames">
<list> <value>loggerInterceptor</value>

BeanNameAutoProxyCreator will only proxy those beans that have ending name with Service. This allows us to specifically target special objects that need logging.
Of course we are not restricted to do just logging; we could implement security, auditing, debugging etc...

One might question the performance related to use AOP on all or majority of the objects. I tried a performance test with & without AOP, and I found that the loading time was increased by about 5 milliseconds for about 5 objects. But the execution time remained the same. Since, all of our objects are preloaded, this shouldn’t be much of a problem. On contrary, for objects lazy initialized might see some lag but once loaded there execution time will remain same.

Tuesday, June 06, 2006

Robust Exception Handling with Spring

Exception Handling has always been an after thought process or an as-you-go addition. Exception handling, in general, is dreaded by programmers due to frequent try-catch blocks because most programmers don’t know what the next set of action should be. Even worse, they sometimes catch it and take no action.

Exceptions fall in two broad categories[1], checked and unchecked. There has been lot of debate on whether checked exceptions really add any value to a Java application. Checked exceptions force developers to handle it through the try-catch blocks. In some instances, they simply try to catch the top-level exception and just print the stack trace, thereby losing all of the information related to the original source that threw it.

Listing 1.1

try {

} catch (Exception ex) {

Then there is another way of code hacking is to duck the exceptions by simply making the method throw the exception,

Listing 1.2

public void someMethod() throws Exception

Most programmers prefer doing this to avoid handling of exception thrown by libraries they probably using inside their methods.

To further exacerbate the problem, exceptions thrown by JDBC are even worse since the only exception thrown is usually SQLException[2]. Not only this exception is a checked exception that a programmer has to handle, but also the exception carries vendor specific information, such as error codes, states etc. If a programmer has to deal with this exception directly or even indirectly, he/she would have to interrogate the exception to retrieve information related to his/her requirements.

Quite often, databases implement business rules through triggers or stored procedures. In such scenario, they raise errors through custom errors numbers that are specific to each vendor.

Lets take an example, a trigger on a specific table would throw an exception with number # 22211 indicating a insertion of a duplicate SSN was attempted. In Java realm, the programmer would like to throw a more specific exception like DuplicateSSNFoundException that extends RuntimeException. So in order to achieve this transformation,

Listing 1.3

Try {
//attempt insert here
} catch (SQLException ex) {

if(ex.getErrorCode==22211) {
throw new DuplicateSSNFoundException(..);
} else {
//in real world, don’t just throw runtime exception
throw new RuntimeException(.., ex);

Imagine if another process were trying to perform an insert as well, it would have to repeat the same piece of code[3].

Furthermore, you have tied yourself to a vendor specific error number pattern.

To rectify these issues, we need a central class that would handle all of the exceptions raised by the database[4]. The class will be responsible for translating the error numbers into more appropriate Java exceptions. The class will be used by the database API and will be called only in an event of an exception is thrown. This relieves all of the application classes from handling any exceptions and instead focuses more on the requirements. Moreover, centralizing exception handling will also improve code reusability and robustness.

First we will create a runtime exception called BusinessException that will represent business rule violation. All subclasses, for e.g. DuplicateSSNFoundException should extend from this class.

Listing 1.4

public class BusinessExceptionTranslator {

public BusinessException translate(String task, String sql, SQLException exception) {


Since we want to map error numbers to more specific Java exception & still don’t want to tie up to an vendor specific error numbering, we would need create an interface that would address both our needs

Listing 1.5

public interface BusinessExceptionMapper {
public boolean shouldMap(Exception ex);
public BusinessException map(Exception rawException);


Finally, we will create an Oracle specific implementation of BusinessExceptionMapper that will hold the mappings of error numbers to the actual exceptions to be thrown.

Listing 1.6

public class OracleErrorNumberExceptionMapper implements BusinessExceptionMapper {

private Map mappings;

public void setErrorNumberExceptionMappings(Map mappings) {..}

The class is fairly simple and achieves the separation of concerns. The class is given mappings of error numbers to exception classes, as shown

key: 22211 value: com.test.DuplicateSSNFoundException

The class in turn is injected into BusinessExceptionTranslator through its setter method. The translator first calls the shouldMap method to check whether mapper can map the error number thrown i.e. OracleErrorNumberExceptionMapper checks to see whether there is any entry with the given error number,

Listing 1.7

return mappings.containsKey(Integer.toString(ex.getErrorCode));

If it returns true, BusinessExceptionTranslator will call map method, which in turn will create a new instance of the mapped exception class and return it.

Sometimes exceptions are embedded inside the message. These messages might be encoded or follow certain vendor specific pattern. In such scenario, OracleErroNumberExceptionMapper wouldn’t satisfy our needs since it revolves around error codes.

In addition, these messages might be intended for the user, so he/she can resolve it differently.

Lets create an interface that will allow its implementations to achieve this task, ExceptionMessageExtractor

Listing 1.8

public interface ExceptionMessageExtractor {

public boolean shouldExtract(Exception ex);

//you can return a list of messages or maybe exception that embeds //messages.

public BusinessException extract(Exception ex);


The implementation classes now can implement vendor specific or business specific logic for retrieving the messages embedded inside the SQLException. For e.g. lets say the message is embedded between START_ and _END text, as shown

Listing 1.9

ORA: 991: raise_xx xx START_You do not have enough credit for this loan, please lower your loan amount_END version 1..xx xx xxx xx

JDBC 4.0 xxx xxx

As you can see, the actual message is embedded inside vendor specific outer message. Our new implementation class OracleMessageExtractor will accomplish this task

Listing 1.10

public class OracleMessageExtractor implements ExceptionMessageExtractor { ...

This class will be injected into BusinessExceptionTranslator through its setter method. The translator, as mentioned above, would check against the mapper and if it doesn’t support it, it would check against the extractor through shouldExtract method. If it returns true, the translator will call extract method on the extractor, i.e. OracleMessageExtractor.

As mentioned earlier, if a database implements most of the business rules through triggers, constraints or stored procedure, which it should anyway, any violation of the rules should be displayed to the user on their display. This will allow user to take an appropriate action to resolve the issue.

In multi-tier environment, the display can take many forms, such as computer, PDA, cell phone etc. If these custom business messages were to be shown on a specific display, we would need to reformat each message to adjust as per the display requirements.

This would require View to take the responsibility of reformatting messages to fit as per the display needs.

But what if we can reformat the message, as per the display, right at the source of creation. To begin, lets create an interface called DeviceAwareMessageAdapter

Listing 1.11

public interface DeviceAwareMessageAdapter {

void put(String message)


Object getHolder();


Using this approach, we should be able plug any adapter specific to a display as per our requirements. For e.g. Struts displays its messages on the screen through ActionMessage objects contained in ActionMessages. We could create an implementation class, StrutsAwareMessageAdapter that would hold ActionMessages as the underlying holder. The view wouldn’t need to worry about the conversion and simply get the holder and place it in the request.

Listing 1.12

public class StrutsAwareMessageAdapter implements DeviceAwareMessageAdapter {

private ActionMessages messages;

public void put(String message) {

messages.add(..., new ActionMessage(message));


public Object getHolder() { return messages; }


This class is injected into ExceptionMessageExtractor, and used during its extraction of the message from the exception.

Now we could send multiple messages inside an exception, the extractor would extract all of these messages and add them individually to ActionMessages through StrutsAwareMessageAdapter.

This class can be reused in other instances as well and is not restricted to just exception handling, as you can clearly see. For e.g. any custom validations done in façade can easily be injected with device adapter.

If you're using Spring MVC then you could instead leverage MessageSource interface & configure proper message sources. The ApplicationContext implements the MessageSource interface, so you could redesign the above interfaces to use it fetch messages from different sources [such properties file, database etc]

A complete class diagram[5] is attached with this article. The newer version has couple of more changes than compared to classes described in this article. Also, there are few more classes, but I won’t get into much detail because they are self-explanatory.

Some people might argue the need for such a component or some of you might not be comfortable with so many interfaces. But I personally feel it eliminates need for individual exception handling from all layers in an application. Furthermore, it allows declarative configuration of exception mappings, message patterns etc.

Of course, as always, there is for sure more room for improvement. So, please let me know your thoughts on it.

[1] Actually, there are two types, namely Error and Throwable. Error is seldom used and represents more catastrophic problems that are pretty much irrecoverable.

[2] As per JDBC 4.0, there are few more sub-classes of SQLException but I am not sure where can use them.

[3] You could very well abstract it to parent or transfer it to util class

[4] Though we are not restricted to just handle exceptions raised by database, we could have the class work with any source.

[5] I used Rational Development Platform to create most of my diagrams.