Spring Learning (2): AOP (Aspect-Oriented Programming)

>

Here are some posts and blogs that help me to understand this concept:
AOP Example
Understand AOP

What is AOP?

Here is the best explaination that I found to understand this abstract terminology. AOP is a way to modify existing classes in a code base to embellish them or change their behavior based on rules defined separately. This modification can be done before the classes are put into a jar/war, or can happen dynamically while the code is being loaded.
The way that AOP can help is it changes the way we modify our existing code when we need to add a same logic to multiple places in our codebase. It works by define the rule for how to find the joint points in the code base and what are the extra logic you wanted to do with them.

Key Terminologies

  • Aspect: In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).
  • Join point: In Spring AOP, a join point always represents a method execution.
  • Pointcut: The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.
  • Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object.
  • Target object: object being advised by one or more aspects. In Spring, this object will always be a proxied object.
  • AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.
  • Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

Three Ways of Achieving AOP


public interface UserService {

	public void add();

	public void delete();

	public void update();

	public void search();

}

public class UserServiceImpl implements UserService{

	@Override
	public void add() {
		System.out.println("add user");
   }

	@Override
	public void delete() {
		System.out.println("delete user");
   }

	@Override
	public void update() {
		System.out.println("update user");
   }

	@Override
	public void search() {
		System.out.println("search user");
   }
 }
								

1. Using Spring API


public class Log implements MethodBeforeAdvice {

	//Object : target object
	@Override
	public void before(Method method, Object[] objects, Object o) throws Throwable {
		System.out.println( o.getClass().getName()  + method.getName() );
	}
}
public class AfterLog implements AfterReturningAdvice {
	//method: callback function
	//target target object
	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		System.out.println("execute" + target.getClass().getName()+method.getName()+"method,"
		+"return value:"+returnValue);
	}
}

 < ?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.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
	 < bean id="userService" class="com.kuang.service.UserServiceImpl"/>
	 < bean id="log" class="com.kuang.log.Log"/>
	 < bean id="afterLog" class="com.kuang.log.AfterLog"/>

	 < aop:config>
		 < aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
		 < aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
		 < aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
	 < /aop:config>

 < /beans>

public class MyTest {
	@Test
	public void test(){
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
		UserService userService = (UserService) context.getBean("userService");
		userService.search();
   }
 }
				

2. Define Cutting Point Class Ourselves


//create joint point class
public class MyJoinPoint{
	public void before(){
		System.out.println("---------Before Execution---------");
	}
	public void after(){
		System.out.println("---------After Execution---------");
	}
}

//update spring config
 < bean id='myJointPoint' class="com.siyu.config.MyJoinPoint"/>
 < aop:config>
	 < aop:aspect ref='myJointPoint'>
		 < aop:pointcut id="myDiyJointPoint" expression="execution(* com.siyu.service.UserServiceImpl.*(..))" />
		 < aop:before pointcut-ref="myDiyJointPoint" method="before"/>
		 < aop:after pointcut-ref="myDiyJointPoint" method="after"/>
	 < aop:aspect />
 < /aop:config>
				

3. Using AspectJ Annotation (Commonly Used)


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspectpublic class AnnotationJointCut {
	@Before()
	public void before(){
		System.out.println("---------Before Execution---------");
	}
	@After()
	public void after(){
		System.out.println("---------After Execution---------");
	}
	@Around()
	public void around(ProceedingJoinPoint jp) throws Throwable{
		System.out.println("Before");
		System.out.println("Signature:"+jp.getSignature());
		//proceed with Joint point method
		Object proceed = jp.proceed();
		System.out.println("After");
		System.out.println(proceed);
	}
}

//in config file
 < bean id="annotationPointcut" class="com.siyu.config.AnnotationPointcut"/>
 < aop:aspectj-autoproxy/>
									

What are the common cases that AOP is used for?

  • Logging
  • Exception Handling & Interrupt Error Actions
  • Permission Checking & Security Checking
  • Transaction Management
  • Prepare data/envrionment before data call and processing results after data call
Menu