Background
During my university days as an undergraduate came across a term constraint logic programming. Constraint Logic Programming meant programming within certain well defined constraints. This meant a program could only be written following those constraints. Aspect oriented programming (AOP) has all such features. Broadly speaking, Spring framework is a form of constraint logic programming through its implementation of different grades of design patterns.
Introduction
Spring Framework can be used to develop robust, maintainable applications. Spring is rapidly becoming a popular framework for development using resources effectively. It loads only those software components, which are required to execute desired functionality. This is the powerful feature of lazy loading component based on its memory based configuration, only when its referred. So, memory contains only those application server components required by the functionality, just like a DLL in windows applications. You can also control this feature by changing the XML file containing the bean configuration.
The Spring Framework makes use of best practices that have been proven over the years in numerous applications and formalized as design patterns. It meticulously codifies these patterns as first class objects that you as an architect and developer can take away and integrate into your own application.
Good thing about the Spring Framework is the application developed by you is not dependent on Spring API while deploying it in production environment i.e. its non-invasive. Spring comprises of all kinds of modules required to develop full scale JEE applications. There are some key concepts, which you need to pickup, like Spring IOC, Spring AOP, Spring Web and Spring MVC.
The IOC component of the Spring Framework addresses the enterprise concern of taking the classes, objects, and services that are to compose an application, by providing a standard means of composing these various heterogeneous components into a complete working application.
Spring's AOP package provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method interceptors and point cuts to cleanly decouple code implementing functionality that should logically speaking be separated. Using source-level meta-data functionality you can also incorporate all kinds of behavioral information into your code. Cross cutting or common concerns can be implemented as discrete aspects, cleaning up the actual application code. Besides, making it easy to change common concern code without changing the actual application code. This is certainly an elegant way to write reusable components.
Spring's Web package provides basic web-oriented integration features, such as multipart file-upload functionality, the initialization of the IOC container using servlet listeners and a web-oriented application context. When using Spring together with Struts, this is the package to integrate with.
Spring's MVC package provides a Model-View-Controller (MVC) implementation for web-applications. Spring's MVC framework is not just any old implementation; it provides a clean separation between domain model code and web forms, and allows you to use all the other features of the Spring Framework. This is definitely an improvement over Struts.
In this article we’ll be focusing on discussing about some key concepts of Spring AOP. We’ll also learn, how to code using the Spring AOP with just basic knowledge of Java.
Spring AOP Concepts
Spring's AOP package provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method interceptors and point cuts to cleanly decouple code implementing functionality that should logically speaking be separated. Using source-level metadata functionality you can also incorporate all kinds of behavioral information into your code.
To understand AOP we need know about some AOP concepts. I list some of them here as part of our discussion on how to code using Spring AOP.
- Aspect: A modularization of a concern for which the implementation might otherwise cut across multiple objects. Transaction management, logging and security are some of the good examples of cross cutting concerns in enterprise applications.
- Joinpoint: Point during the execution of a program, such as a method invocation or a particular exception being thrown.
- Advice: Action taken by the AOP framework at a particular joinpoint. Different types of advice include "around," "before" and "throws" advice. Advice types are discussed below. Many AOP frameworks model an advice as an interceptor, maintaining a chain of interceptors "around" the joinpoint.
- Pointcut: A set of join points specifying when an advice should fire. An AOP framework must allow developers to specify pointcuts: for example, using regular expressions.
- Introduction: Adding methods or fields to an advised class. Spring allows you to introduce new interfaces to any advised object. For example, you could use an introduction to make any object implement an interface, to simplify the tracking of changes to an object's state.
- Target Object: Object containing the joinpoint. Also referred to as advised or proxied object.
- AOP Proxy: Object created by the AOP framework, including advice. An AOP proxy is a dynamic proxy that uses code generated at runtime.
- Weaving: Assembling aspects to create an advised object. This can be done at compile time, or at runtime.
Different advice types include:
- Around Advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice will perform custom behavior before and after the method invocation. They decide whether to proceed to the joinpoint or to shortcut executing by returning their own return value or throwing an exception.
- Before Advice: Advice that executes before a joinpoint, but which does not have the ability to prevent execution flow proceeding to the join point
- Throws Advice: Advice to be executed if a method throws an exception
- After Returning Advice: Advice to be executed after a joinpoint completes normally, i.e. the method is executed successully without throwing any exception.
It is recommended to use, the least powerful advice type yet the most specific advice type, that can implement the required behavior. For example, if you need only to update a cache with the return value of a method, you are better off implementing an after returning advice than an around advice, although an around advice can accomplish the same thing.
The pointcut concept is the key to AOP, distinguishing AOP from older technologies offering interception. Point cuts enable advice to be targeted independently of the OO hierarchy. For example, an around advice providing declarative transaction management can be applied to a set of methods spanning multiple objects. Thus pointcuts provide the structural element of AOP.
We will look at how write code based on some of these concepts. Software requirements , to code in Spring is mentioned in appendix for your reference.
Writing a Hello World
To start with let’s develop a hello world example using Spring AOP basics. You need to program to an interface in Spring.
First you need create an interface named Hello as follows:
package hello;
public interface Hello {
public String sayhello(String a);
}
The implementation HelloImpl can be as follows:
package hello;
public class HelloImpl implements Hello {
private String greeting; // parameter set in hello.xml
public HelloImpl() {
}
public HelloImpl(String greeting) {
this.greeting = greeting;
}
public String sayhello(String name) {
return greeting+name;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
As you can see its plain java code so far. Now comes the interesting part of configuring this bean.
Here we show a simple way of configuring a bean without any jargon in hello.xml file.
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<bean id="hello" class="hello.HelloImpl">
<property name="greeting">
<value>Good Morning !...</value>
</property>
</bean>
</beans>
You need to follow spring-beans.dtd, while configuring the bean. A bean can be defined within a … tag and its attributes within … tag.
Here attribute id defines resource name by which to get its implementation, class is the fully class name of the implementation class HelloImpl . The property name is same as the attributes of HelloImpl. Obviously you define properties for only bean implementation classes. Ensure that all properties have only their setters defined as shown above.
To run this you need to write a client HelloClient was shown below:
package hello;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class HelloClient {
public static void main(String args[]) throws Exception {
Resource resource = null;
BeanFactory beanFactory = null;
Hello bean = null;
try {
resource = new ClassPathResource("hello/hello.xml");
beanFactory = new XmlBeanFactory(resource);
bean = (Hello) beanFactory.getBean("hello");
String response = bean.sayhello(args[0]); // let say its "Friend"
System.out.println(response);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
In the above code the resource representing the bean factory can be obtained in the following way:
1. As a class path resource
Resource resource = new ClassPathResource("hello/hello.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);
2. As a file system application context
ApplicationContext context = new FileSystemXmlApplicationContext("/resources/hello.xml");
3. As a class path resource as an application context
ApplicationContext context = new ClassPathXmlApplicationContext ("hello/hello.xml");
ClassPathXmlApplicationContext is generally used when you have more than one configuration file.
The purpose of the whole exercise was to get the BeanFactory from which to obtain the required bean. This is done in these statement below.
BeanFactory beanFactory = new XmlBeanFactory(resource);
Using application context method it’ll be as given below. Notice that the bean name is same as id attribute the one defined in hello.xml.
Hello bean = (Hello) context.getBean("hello");
After this like in EJB you can call the business method of the bean. On running the above you should get the following result.
Good Morning !...Friend
It’s a simple hello world program in plain old java and configured in a xml file. We’ll go a bit deeper now.
Hello World Version 2
Let’s make it interesting by changing the configuration slightly. The interface and its implementation will be defined separately in the same xml configuration file.
<!-- CONFIGURATION -->
<bean id="hello" class="org.springframework.aop.framework.ProxyFactoryBean"<
<property name="proxyInterfaces">
<value>hello.Hello</value>
</property>
<property name="target">
<ref local="beanTarget">
</property>
</bean>
<!-- CLASS -->
<bean id="beanTarget" class="spring1.HelloImpl">
<property name="greeting">
<value>Good Morning!...</value>
</property>
</bean>
</beans>
Here we are using ProxyFactoryBean to define the interface Hello as the property proxyInterfaces. And its implementation is defined as the property target. The target has a local reference to the desired implementation definition beanTarget.
Good thing about this approach is without changing the HelloClient by simply changing the beanTarget or changing the local reference. We can get different functionality by providing different implementations of Hello and defining one of them as the target implementation.
The essential Spring skills required to make effective use of Spring features are listed below ranked in the order of importance:
- IOC or DI concepts and how they are implemented in Spring
- AOP or Aspect Oriented Programming
- ApplicationContext & BeanFactory related
- JDBC Integration
- Transaction Support
- ORM / JPA Support
- JMS Integration
- EJB Integration (if you do use EJB)
- Spring Security
- Spring MVC (for UI only)
This is a basic article on Spring AOP. It’ll be followed by more advanced articles. Your feedback is valuable in making them better.
Conclusion
Spring IOC (Inversion of Control) and AOP (Aspect Oriented Programming) is an elegant way of developing applications, which are easy to develop and test.
The code given in this article can be used to get a quick start on Spring AOP.
________________________________________________________
Appendix
Software Requirements
You will need the following software setup to work on Spring AOP:
- MyEclipse
- Spring IDE eclipse plugin from www.springide.org/updatesite
- Download Spring 2.5 jars from www.springframework.org
- Java 5
- Any db like Oracle
Ensure that you have the following jars in lib folder of a java project’s classpath in eclipse:
- commons-logging.jar
- junit-4.1.jar
- log4j-1.2.8.jar
- spring.jar
You can get these jars from Spring Framework