Lets Introduce the AspectJ Annotation!

to the previous example!

pom.xml needs this new dependency..
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjtools</artifactId>
    <version>1.8.12</version>
</dependency>

MyService.java
package biz.tugay;
 
public interface MyService {
 
    void serve();
}

MyServiceImpl.java
package biz.tugay;
 
import org.springframework.stereotype.Component;
 
@Component("myService")
public class MyServiceImpl implements MyService {
 
    @Override
    public void serve() {
        System.out.println("biz.tugay.MyServiceImpl#serve");
    }
}

MyMethodBeforeAdviceImpl.java
package biz.tugay;
 
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
 
@Component(value = "myMethodBeforeAdvice")
@Aspect
public class MyMethodBeforeAdviceImpl {
 
    @Before("execution(void biz.tugay.MyService.serve())")
    public void before() throws Throwable {
        System.out.println("biz.tugay.MyMethodBeforeAdviceImpl#before");
    }
}

App.java
package biz.tugay;
 
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class App {
 
    public static void main(String[] args) {
        final ClassPathXmlApplicationContext classPathXmlApplicationContext
                = new ClassPathXmlApplicationContext("beans.xml");
 
        final MyService myService 
                = classPathXmlApplicationContext.getBean("myService", MyService.class);
 
        myService.serve();
    }
}

Notes

  • Our Advice class looks a lot more different now. It is actually more like an Advisor now, since it both declares what kind of Advice it is (with the @Before annotation) and the Pointcut (with the AspectJ expression language).
  • We do not directly use the ProxyFactoryBean, the proxying is automated now.