Posts Tagged ‘Spring Framework’

A good resource for Spring AOP

Monday, April 27th, 2009

A good resource for spring and AOP, “Spring 2.5 Aspect Oriented Programming“; has been published by Packt Publishing. I strongly suggest reading if you are a little bit familiar with Spring and interested in AOP.

Before you start reading my review about it, you can find more information about the book and how to get it, at this page.

Although Spring Framework has been seen as just an IoC container by some of the programmers, most of the programmers nowadays start to realize that this kind of view would be an over simplification of its capabilities. It has many features and one of them is using it for AOP. In book Spring 2.5 Aspect Oriented Programming written by Massilimiano Dessi and published by Packt Publishing, the use of Spring for AOP is well explained.

First of all, the need for AOP is explained in an analytical way, allowing readers to make comparison between a scenario with and without help of AOP. After this persuasive attitude, the introduction of AOP specific concepts (such as “pointcut”, “joinpoint”, “advice”) and introduction to some more Spring-AOP specific concepts (such as advisor) are provided. A language that is going to be used throughout the book is built in the beginning; and this enables readers to gain a better insight about the AOP paradigm while reading the book.

As well as describing how to realize AOP using Spring, chapters 2-4 also explain what is happening behind the scene. In this sense, this part of the book might be used as a “Cookbook”. Despite existence of diverse options while using Spring; some advice has been given about when to use which, depending on the context. While illustrating the use of AOP by giving some simple examples; the book also explains what kind of dilemmas might a programmer get into and make suggestions about which way would be more convenient.

After giving those details, the book comes back to a more conceptual point about AOP. From the beginning, a concept such as “croscutting concerns” has been mentioned as the most fundamental reason why AOP has been evolved. As object oriented programmers, we have experience about a lot of scenarios and we even have design patterns that help us a lot. However, when we decide to use AOP in our applications; the need to have some kind of decision mechanism that regards when to use it confronts us; since it is a new paradigm compared to OOP. At first glance, this may seem like an easy task; but not at all! While programmers are still arguing about the patterns and anti-patterns about AOP, there are some scenarios that is perfectly legal to use AOP. Some of them are concurrency, caching, security / role assignment. Use of AOP in those scenarios is illustrated in the book in a dialectic manner. First, implementation without using AOP and then with the use of AOP is provided; which enables readers to make comparison between them. This chapter illustrates very typical scenarios in which the use of AOP is approved and perfectly legal.

Domain Driven Design is very popular nowadays and the book connects AOP with it in chapters 6 and 7. First of all; without causing reader to get drown details, the relevant concepts are identified. Before applying AOP, a good Object-Oriented design has been given. Domain layer is separated from application and infastructure layers. Some of the croscutting concerns are identified and the reader is informed about how they are going to be handled. Moreover, the domain objects are designed in such a way that they would be able to take advantage of inversion of control (IoC). Simply, “Model” is created on this chapter, which is going to be associated with a “View” and a “Controller” in the subsequent chapter. Spring MVC has been used in chapter 7 in order to associate Model in chapter 6 with an appopriate view and controller. For readers who are not familiar with Spring MVC; a little information is provided, but there are lots of documentation in World Wide Web for Spring MVC; one of those should be read before starting this chapter. In chapter 7, AOP has been used for caching, concurrency, security in a sensible manner.

To conclude, the book Spring 2.5: Aspect Oriented Programming is an excellent source for programmers who are familiar with OOP, Spring Framework and interested in applying AOP on a real project.

Spring and Caching

Tuesday, February 3rd, 2009

Caching is one of the most efficient approaches in case performance needs to be optimized; especially in a scenario with persistence layer. In such a kind of software,  because expensive objects can be passed during the communication with the repository, each request means increased time complexity. In this case, to minimize the time complexity, most of the time the best thing is to minimize the number of calls to the repository.

Caching can simply be considered as moving data from one place to another. However, the most important condition is, the destination should be more easily accessible. If we move data to a place which could be the  more expensively accessible, then this would not be a sensible approach at all.

Caching in Java could be done in numerous ways. In fact, technologies such as AOP make caching even more easier to design and maintain.

In this article, you will find a simple example of caching using one of the caching frameworks, EHCache, and Spring Framework. Spring Framework also uses its own AOP support for injecting caching behaviour to objects and procedures.

In order to demonstrate the technology, I had to pick up a straightforward scenario. In fact, I am aware that this example is too simple for caching to increase efficiency.

Suppose we need to read data from a file and print the content of it. The design is really simple. However, if we also need the same data multiple times in a small period, such as 1.000 times in a minute, then it could be a point where we might start worrying about the performance. In order to improve the performance we may choose the caching approach and use Spring to achieve our goal.

What we need to do is injecting caching behaviour using Spring and we will do that without doing any extras to the code that is being executed. This is important since our task in fact is to refactor the code in such a way that it will have a better performance. One important thing here is, the refactoring should not interfere with the previous work.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Bar {

public String read() throws FileNotFoundException
{
System.out.println(“read() is executed.”);

Scanner scan = new Scanner(new File(“a.txt”));
String str = “”;
while(scan.hasNextLine())
{
str += scan.nextLine();
}

return str;
}

}

public static void processBar(Bar b) throws FileNotFoundException
{
for(int i = 0; i < 1000; i++)
{
System.out.println(b.read());
}
}

Assume that this part was written before considering some improvements regarding to the performance were needed. In order to improve this using Spring, we need to create a configuration file to define caching behaviour and inject this behaviour to class Bar.

ehcache.xml file:

<ehcache>
<cache name=”barCache” maxElementsInMemory=”500″
eternal=”true”
memoryStoreEvictionPolicy=”LFU” timeToLiveSeconds=”0″ />

</ehcache>

We also need an applicationContext.xml file to configure the beans.

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:p=”http://www.springframework.org/schema/p”
xmlns:context=”http://www.springframework.org/schema/context”
xmlns:aop=”http://www.springframework.org/schema/aop”
xmlns:tx=”http://www.springframework.org/schema/tx”
xmlns:jee=”http://www.springframework.org/schema/jee”
xmlns:ehcache=”http://www.springmodules.org/schema/ehcache”
xsi:schemaLocation=”
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd”>

<ehcache:config configLocation=”classpath:ehcache.xml” />

<ehcache:proxy id=”barBean”>
<bean class=”Bar” />
<ehcache:caching methodName=”read” cacheName=”barCache” />
</ehcache:proxy>

</beans>

Now, to test the code,

public static void main(String[] args) throws InterruptedException, FileNotFoundException
{
ApplicationContext ctx = new ClassPathXmlApplicationContext(“applicationContext.xml”);

Bar b = (Bar)ctx.getBean(“barBean”);

processBar(b);
}

As it is clearly indicated, without modifying any java code at all, caching behaviour has been injected. The properties and preferences related to the caching could be modified any time by just altering the xml file. For instance, by changing timeToLiveSeconds property, one could alter the time limit.
In order to keep things simple, nothing related to flushing have been added. In fact, flushing is essential in real caching examples. Flushing is simply to remove all or some part of cache at some point.

For instance, what if a method that writes to the file in Bar class has been invoked in somewhere during the caching period? It certainly wouldn’t make sense to keep that cache anymore, since it is certain that the content of the text file is modified.

To illustrate this, suppose class Bar has the following method:

public void write(String str) throws IOException
{
BufferedWriter out = new BufferedWriter(new FileWriter(“a.txt”));
out.write(str);
out.close();

}

It is not difficult to add flushing using Spring. In fact, it could even be configured by adding just one line to the xml file in most cases.

<ehcache:proxy id=”barBean”>
<bean class=”Bar” />
<ehcache:caching methodName=”read” cacheName=”barCache” />

<ehcache:flushing methodName=”write” cacheNames=”barCache” />

</ehcache:proxy>

As you might have noticed, the bold line has been added to the XML file. Please also notice that ehcache:flushing tag has cacheNames attribute rather than having cacheName.

Now, Bar class’ caching behaviour is configured in such a way that it will be flushed whenever write method is called. Unless write(str) is called, the cache will be used instead of connecting to the text file each time.

Using AOP to Retrieve Spring Beans

Saturday, January 3rd, 2009

In order to perform IoC with Spring, the programmer(s) should use a spring factory object to access each bean (might be defined in an XML file) when the beans are required.

This process might cause some problems in many ways and some of them are:

– The programmers who need to access an instance of a bean must be aware of the name of the bean that is specified in the XML file.

– Each time a programmer retrieves a bean, a casting to the requested type must be made.

* Although these two issues might be resolved by using one of the factory patterns, this type of solution would simply contradict with the use of Spring Framework and IoC for that case.

– A constructor call can still be made to one of these beans’ classes. This is problematic when we are dealing with singleton beans – which is most likely to be the case when we need Spring and IoC.

Using AOP, we can simply deal with those kind of problems. Although it would be wiser to use Spring Framework for wiring, I will demonstrate it using AspectJ.

package ali.test;

public class Foo {

private String bar;

public void setBar(String bar)
{
this.bar = bar;
}

public String getBar()
{
return bar;
}
}

We need to have a spring factory type.

package ali.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringFactory {

private ApplicationContext context = null;
public SpringFactory()
{
init();
}
private void init()
{
context = new ClassPathXmlApplicationContext(“/applicationContext.xml”);
}

public Object getBean(String name)
{
return context.getBean(name);
}
}

And let applicationContext.xml file be

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:aop=”http://www.springframework.org/schema/aop”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd”>

<bean id=”foo” class=”ali.test.Foo” scope=”singleton”>
<property name=”bar” value=”hello!”/>
</bean>

</beans>

So far so good. Now, we are adding our FooCreationAspect that will grab the instance of requested bean using Spring Factory in each call.

package ali.test;

public aspect FooCreationAspect {

private SpringFactory fac;

public FooCreationAspect()
{
fac = new SpringFactory();
}

pointcut fooCreationViaConstructor() : call(Foo.new(..));

Foo around() : fooCreationViaConstructor()
{
Foo f = (Foo)fac.getBean(“foo”);
return f;
}
}

Simple as that. A few tests are to be made:

public static void main(String[] args)
{
Foo f = new Foo();

System.out.println(f.getBar());

f.setBar(“bar2”);

Foo f2 = new Foo();

System.out.println(f2.getBar());
}

The output is :

hello!

bar2

Simply illustrates that the same bean is returned as f2, even if we make a separate constructor call.

Notice that one should be be careful using this technique. If some some complex tasks need to be completed at each execution of the constructor, perhaps the use of this technique needs some second considerations. However, usually (and ideally!) bean objects don’t perform any complex operations and this technique would work well frequently.

Moreover, you may also want to annotate the constructor to make developers aware of the fact that the type is singleton.