Spring Scoped Proxy Beans – An Alternative to Method Injection

Few months back, I wrote on JavaLobby about how you can use Method Injection in scenarios where bean lifecycles are different i.e. you want to inject a non-singleton bean inside a singleton bean. For those of you who are not aware of Method Injection, it allows you to inject methods instead of objects in your class. Method Injection is useful in scenarios where you need to inject a smaller scope bean in a larger scope bean. For example, you have to inject a prototype bean inside an singleton bean , on each method invocation of Singleton bean. Just defining your bean prototype, does not create new instance each time a singleton bean is called because container creates a singleton bean only once, and thus only sets a prototype bean once. So, it is completely wrong to think that if you make your bean prototype you will get  new instance each time prototype bean is called.

To make this problem more concrete, lets consider we have to inject a validator instance each time a RequestProcessor bean is called. I want validator bean to be prototype because Validator has a state like a collection of error messages which will be different for each request.

RequestProcessor class

@Component
public class RequestProcessor implements Processor {

    @Autowired(required = true)
    private Validator validator;

    public Response process(Request request) {
        List errorMessages = validator.validate(request);
        if (!errorMessages.isEmpty()) {
            return null;
        }
        return null;
    }

}

Validator class

@Component
@Scope(value = "prototype")
public class Validator {

    private List<String> errorMessages = new ArrayList<String>();

    public Validator() {
        System.out.println("New Instance");
    }

    public List<String> validate(Request request) {
        errorMessages.add("Validation Failed");
        return errorMessages;
    }

}

Because I am using Spring annotations, the only thing I need specify in xml is to activate annotation detection and classpath scanning for annotated components.

<?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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<context:annotation-config />

	<context:component-scan base-package="com.shekhar.spring.scoped.proxy"></context:component-scan>
</beans>

Now lets write a test to see how many instances of prototype bean gets created when we call the processor 10 times.

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class RequestProcessorTest {

    @Autowired
    private Processor processor;

    @Test
    public void testProcess() {
        for (int i = 0; i < 10; i++) {
            Response response = processor.process(new Request());
            assertNull(response);
        }
    }

}

If you run this test, you will see that only one instance of validator bean gets created as “New Instance” will get printed only once. This is because container creates RequestProcessor bean only once, and thus only sets Validator bean once and reuses that bean on each invocation of process method.

One possible solution for this problem is to use Method Injection which I have already talked about in my JavaLobby article. I didn’t liked method injection approach because it imposes restriction on your class i.e. you have to make your class abstract. In this blog, I am going to talk about the second approach for handling such a problem. The second approach is to use Spring AOP Scoped proxies which injects a new validator instance each time RequestProcessor bean is called. To make it work, the only change you have to do is to specify proxyMode in Validator class.

@Component
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")
public class Validator {

    private List<String> errorMessages = new ArrayList<String>();

    public Validator() {
        System.out.println("New Instance");
    }

    public List<String> validate(Request request) {
        errorMessages.add("Validation Failed");
        return errorMessages;
    }

}

There are four possible values for proxyMode attribute.I have used TARGET_CLASS which creates a class based proxy. This mode requires that you have CGLIB jar in your classpath.If you run your test again you will see that 10 instances of Validator class will be created. I found this solution more cleaner as I don’t have to make my class abstract and it makes unit testing of RequestProcessor class easier.

Top 10 New Features in Maven 3

Maven 3.0 was just released and the Java build tool has come a long way since version 2 was released almost six years back. Maven 2 had reached a stage where it was difficult to extend and its code was difficult to understand. In version 3.0 many of the Maven internals have been revamped to overcome all the issues associated with Maven 2. In this article, I run down the top 10 features in Maven 3.

Read More

Reduce Boilerplate Code for DAO’s — Hades Introduction

Most web applications will have DAO’s for accessing the database layer. A DAO provides an interface for some type of database or persistence mechanism, providing CRUD and finders operations without exposing any database details. So, in your application you will have different DAO’s for different entities. Most of the time, code that you have written in one DAO will get duplicated in other DAO’s because much of the functionality in DAO’s is same (like CRUD and finder methods).

One of way of avoiding this problem is to have generic DAO and have your domain classes inherit this generic DAO implementation. You can also add finders using Spring AOP; this approach is explained Per Mellqvist in this article. There is a problem with the approach: this boiler plate code becomes part of your application source code and you will have to maintain it. The more code you write, there are more chances of new bugs getting introduced in your application. So, to avoid writing this code in an application, we can use an open source framework called Hades.

Read More

Speed up your build with Maven 3

I have been trying to find ways to make my project’s maven build run fast. It is very frustrating and annoying when your project’s full build takes 12 minutes to complete. It does not happen too often in a day because you work at module level,  but 2-3 times a day you need to build the full project and if your build takes this long,  it really slows you down. These days builds take a lot of time because you embed all sorts of plugins in your build like checkstyle, findbugs, cobertura (It is evil because it run your test twice), etc.  Although,  It does give you time to have coffee but 12 minutes is way too much. So, I was really pissed off.

Few days back I was checking my tweets and found out that Maven is releasing its new version and it will have some performance improvements. Maven 3 is the latest version of maven which is expected to be released today.  So, I decided to play with it. I downloaded the beta version of  Maven 3, changed my windows path system variable to point to Maven 3 and ran a mvn clean install on my project. Without any build failures or other problems, the build just ran fine. I have heard that when Maven 2 was released people had hard time migrating from version 1 to 2 as it was not backward compatible. But Maven 3.0 is completely backward compatible and most of the plugins will also work fine. To my surprise, the build took 9 minutes. This is still a high number but it was way better than 12 minutes. Seeing this decrease in build time motivated me to read more about Maven 3.

After reading some blogs and watching Jason Van Zyl presentation,  I found out that there are lot of new features in Maven 3. One of the new features in Maven3 is Parallel Builds. Parallel build analyzes your project’s dependency graph and schedule modules that can be run in parallel. This is a very cool feature and it really sped up the build. To run a paralled build, you can type

mvn -T 4 clean install
mvn -T 2C clean install

The first command will run your build with 4 threads and second command will build your project with 2 threads per core. How fast your build will become, depends a lot on your project/build structure, how your unit tests are distributed in modules  so it may vary from project to project. For my project with 4 threads, the build time got reduced to under 6 minutes, which I think is  great.  You should try out some combination with number of threads or number of threads per core to find out the best possible combination for your project. I am very happy that build time of my project got reduced to almost half.

In his presentation, Jason Van Zyl talks a shell based tool called Maven Shell which can also further improve the performance. Maven Shell is maven embedded in a long lived shell process. It does not comes bundled with maven 3 so you have to download it from http://shell.sonatype.org/. I tried running my project build inside Maven Shell but it gives PermGen space error all the time. I tried changing the perm gen memory setting but it didn’t helped. Maven shell is expected to run much fast because it caches the parsed POMs.

Maven 3 is definitely worth spending time so have a look at it. I have just touched the tip of iceberg , there are lot of new features in Maven 3.  I will try and talk about others in my future blogs.