Aspects with Spring and Maven for getting rid of singletons

We wanted to update some old hibernate DAOs we had laying around which were implemented using singletons.  Instead of using singletons we wanted to wire these up using the Spring context. This was seemed to be an easy refactoring task. However, diving into the code we came to realize that we had several taglibs developed (extending from SimpleTagSupport) that was using these DAOs. And since you can't have constructors for these tags to dependency inject our DAOs we had to look elsewhere.

Aspects to the rescue! By using the @Configurable annotation found in spring we could have spring set up our DAO services in our tags instead of using that singleton pattern.

public class MyTag extends SimpleTagSupport {
    private MySweetRepository repository;

I now had to choose wether I wanted to have compile time weaving or load time weaving. I opted for compile time because I didn't want to change our production environment too much by introducing -javaagent. And having tried the javaagent path with Tomcat before, I wasn't jumping with enthusiasm of wrestling with that beast again.

Since we are using maven to compile our project I needed some dependencies for aspects:



And then to set up the aspectj compiler for maven:


Running 'mvn package' will now give me java classes with aspects woven into them. You can for example use an java decompiler such as jad to check this.

Just one final bit missing now, and that is to set up my spring application context to actually wire this up.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <context:spring-configured />
    <context:annotation-config />

spring-configured will make sure the @Configurable annotation kicks in as the class is instantiated, while annotation-config will do the actual job of checking for @Autowired and place the correct DAO service into my tag.

So now I have gotten rid of my old school singleton patterns and replaced them with DAOs that are wired up in my spring config. I did a complete refactoring of our database layer in one afternoon using this technique.

Be Sociable, Share!

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

AddThis Social Bookmark Button

One Response to “Aspects with Spring and Maven for getting rid of singletons”

  1. Nice work man!

    Even if our original estimates for this task were exceeded (quite a bit :)) we will benefit from this work in the long run.