CodesJava

Easy learning with example program codes

Spring AOP AspectJ Annotation Configuration Example


AspectJ libraries provides the facility to declare aspect, pointcut etc with the help of annotations. Let us discuss the commonly used AspectJ annotations first.

Declaring an aspect:

The @Aspect annotation is used to declare a class as an aspect.

@Aspect
public class AspectModule {
 
}

Declaring a pointcut:

The @Pointcut annotation is used to declare a pointcut. The expression parameter represents the expression used for matching the join point.

@Pointcut("execution(expression)")
private void businessService() {
	//Block of code.
}

Declaring advices:

The @{ADVICE-NAME} annotations is used to declare an advice.

Advice types:

Before:
It executes before the method execution.

After:
It executes after the method execution. It not depends upon the method outcome.

after-returning:
It executes after the method execution when method completes successfully.

after-throwing:
It executes after the method execution when method exits by throwing an exception.

Around:
It executes before and after the advised method is called.

Spring AOP AspectJ Annotation Configuration Advice Example:

BusinessLogic.java

/**
 * This class will be used as a bean class.
 * @author codesjava
 */
public class BusinessLogic {
	public void implementBusinessLogic(){
	  System.out.println("Business logic executed.");
	}
 
	public String returnValue(){
	  System.out.println("Return value executed.");
	  return "codesjava.com";
	}
 
	public void throwException(){
	  System.out.println("Business logic throw exception.");
	  throw new ArithmeticException("Arithmetic exception occure.");
	}
}

AdviceTest.java

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
 
@Aspect
public class AdviceTest {  
 
@Pointcut("execution(* com.codesjava.business.*.*(..))")
private void selectAll(){
 
}
 
@Before("selectAll()")
public void beforeAdvice(){
     System.out.println("Before advice executed.");
}
 
@After("selectAll()")
public void afterAdvice(){
    System.out.println("After advice executed.");
}
 
@AfterReturning(pointcut = "selectAll()", returning="retVal")
public void afterReturningAdvice(Object retVal){
    System.out.println("After returning advice executed.");
    System.out.println("Returning value: " + retVal);
}
 
@AfterThrowing(pointcut = "selectAll()", throwing = "ex")
public void afterThrowingAdvice(ArithmeticException ex){
  System.out.println("Throwing advice executed.");
  System.out.println("Exception: " + ex.getMessage());   
}
}

applicationContext.xml

<?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-3.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 
     <aop:config>
      <aop:aspect id="log" ref="adviceTest">
         <aop:pointcut id="selectAll" 
         expression="execution(* com.codesjava.business.*.*(..))"/>
         <aop:before pointcut-ref="selectAll" method="beforeAdvice"/>
         <aop:after pointcut-ref="selectAll" method="afterAdvice"/>
         <aop:after-returning pointcut-ref="selectAll" 
                              returning="retVal"
                              method="afterReturningAdvice"/>
         <aop:after-throwing pointcut-ref="selectAll" 
                             throwing="ex"
                             method="afterThrowingAdvice"/>
      </aop:aspect>
   </aop:config>
 
   <bean id="businessLogic" 
    class="com.codesjava.business.BusinessLogic"/>
   <bean id="adviceTest" 
    class="com.codesjava.business.AdviceTest"/>
 
</beans>

Test.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class Test {
 public static void main(String[] args) {
  //Get ApplicationContext using spring configuration file.
  ApplicationContext context = 
    new ClassPathXmlApplicationContext("applicationContext.xml");
 
  //Get BusinessLogic bean object from ApplicationContext instance. 
  BusinessLogic businessLogic = 
    (BusinessLogic) context.getBean("businessLogic");
 
  //Call implementBusinessLogic method of BusinessLogic bean.
  businessLogic.implementBusinessLogic();
  System.out.println("------------------------------------");
  businessLogic.returnValue();
  System.out.println("------------------------------------");
  businessLogic.throwException();
 } 
}

Output:

Before advice executed.
Business logic executed.
After advice executed.
After returning advice executed.
Returning value: null
-----------------------------------------
Before advice executed.
Return value executed.
After advice executed.
After returning advice executed.
Returning value: codesjava.com
-----------------------------------------
Before advice executed.
Business logic throw exception.
After advice executed.
Throwing advice executed.
Exception: Arithmetic exception occure.
Exception in thread "main" java.lang.ArithmeticException: Arithmetic exception occure.
	at com.codesjava.business.BusinessLogic.throwException(BusinessLogic.java:19)
	at com.codesjava.business.BusinessLogic$$FastClassByCGLIB$$19ab96db.invoke(<generated>)
	at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
	at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:692)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
	at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:42)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
	at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:50)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
	at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
	at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:50)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
	at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:625)
	at com.codesjava.business.BusinessLogic$$EnhancerByCGLIB$$4299115d.throwException(<generated>)
	at com.codesjava.business.Test.main(Test.java:20)

 
Download this example.
 

Spring Tutorial

Spring framework.
Spring framework architecture.
Spring ioc container.
Spring bean.
Spring bean scopes.
Spring bean life cycle.
Spring callback methods.
Spring hello world.
Spring bean definition inheritance.
Spring bean definition template.
Spring dependency injection.
Spring constructor based injection.
Constructor injection type ambiguities.
Setter based dependency injection.
Spring dependency injection collections.
Spring autowire
Spring autowire by name
Spring autowire by type
Spring autowire by constructor
Spring JDBC tutorial
Spring JDBC Prepared Statement
Spring ResultSetExtractor
Spring RowMapper
Spring aop tutorial.
Spring AOP AspectJ Xml.
Spring AOP AspectJ Annotation.
Spring MVC tutorial.
Spring mvc framework.
Spring mvc configuration file.
Spring mvc hello world.
Spring MVC multiple controller.
Spring MVC login.
Spring mvc form handling.
Spring mvc exception handling.
Spring spel tutorial.
Spring spel hello world.
Spring spel operators.
Spring spel ternary operator.
Spring spel standardevaluationcontext.
Spring spel bean reference.
Spring spel method invocation.
Spring spel list, map.
Spring spel regex.
Maven Eclipse Spring
Spring boot overview
Spring boot architecture diagram
Spring boot components
Spring boot starter parent
Spring boot web app configuration
Run spring boot application
Spring boot change port
Spring boot change context path
Spring boot log sql statements
Spring boot hello world
Spring boot JSP
Spring boot thymeleaf
Spring boot with mysql
Spring security overview
Spring security architecture
Spring security maven dependency
Spring security xml
Spring security annotation
Spring security custom login xml
Spring security custom login annotation
Spring security form login
Spring security remember me
Spring security method level
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki