Saturday, May 19, 2007

Introduction to AspectJ 5 with Spring and JavaConfig

Using the articles about JavaConfig in Guice vs. Spring JavaConfig: A comparison of DI styles and Simplifying Enterprise Applications with Spring 2.0 and AspectJ I managed to use aspectj configured with spring in java code only, that is without using xml files.

Here is the annotated aspectj class:

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

public class HelloFromAspectJ {
@Pointcut("execution(* main(..))")
public void mainMethod() {}

public void sayHello() {
System.out.println("Hello from AspectJ!");

Here is the ordinary java class which is adviced by the above aspect:

public class HelloService {
public void main() {
System.out.println("Hello World!");

And here is the configuration class, which replaced the spring's configuration xml file:

import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator;
import org.springframework.context.ApplicationContext;

public class SpringConfig {
public HelloService helloService() {
return new HelloService();
public HelloFromAspectJ helloFromAspectJ() {
return new HelloFromAspectJ();
public AnnotationAwareAspectJAutoProxyCreator annotationAwareAspectJAutoProxyCreator() {
return new AnnotationAwareAspectJAutoProxyCreator();

public static void main(String[] args) {
ApplicationContext ctx = new AnnotationApplicationContext(SpringConfig.class);
HelloService helloService = (HelloService) ctx.getBean("helloService");

Note that the bean AnnotationAwareAspectJAutoProxyCreator is the enabler of annotated aspects in spring. It has the same function as the
element in the spring's xml configuration.

1 comment:

ranma172 said...

Thank you Mert.

I've tried to use aspects with JavaConfig following the tutorial in but it doesn't tell you how to inject dependencies on an aspect.

With your solution, now I control the creation of the aspect bean, so I can inject dependencies to it (by constructor, setter or whatever).

Now I will try to pass arguments to the advice methods. I'm a little confused with that "execution(...) and args(...)" syntax.