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>
</bean>
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
con.setAutoCommit(false);
try {
///do your work
con.commit();
} catch (…) {
con.rollback();
log..
} 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">
<props>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
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>
</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) {
dao1.insert(…);
dao2.delete(…);
dao3.update(…);
}
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>
<bean id=”dao2” class=”<package>.ActualDao2”>
<property name=”dataSource”><ref bean=”configuredDataSource” /></property>
</bean>
<!—- 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>
</bean>
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
