1.重要概念
1.1 通知
通知:就是会在目标方法执行前后 执行的方法
try{
try{
//@Before
method.invoke(..);
}finally{
//@After
}
//@AfterReturning
}catch(){
//@AfterThrowing
}
举例,
以下这个方法就是通知,目标方法是UserDao类的addUser(),在addUser执行之后执行了log方法,所以log方法是后置通知,通过在方法上加上@After注解来表示。
@After(value="execution(* cn.xh.dao.UserDao.addUser(..))")
public void log(){
System.out.println("记录日志");
}
切入点
切入点:需要增强的目标方法
如果只是一个具体的方法需要增强,通过类名和方法名找到它就可以了。
但是往往真实的需求中很多方法需要同样的通知进行增强
execution(* cn.xh.dao.UserDao.addUser(…)就是用来描述需要应用通知的方法的。
这里的含义是cn.xh.dao包UserDao类中的参数任意,返回值任意的addUser方法。
连接点
连接点:就是可以应用通知进行增强的方法。
一旦连接点被增强,就成为切入点。
//addUser被增强,所以也是切入点
public void addUser(){
System.out.println("添加用户");
}
//连接点
public void updateUser(){
System.out.println("修改用户");
}
//连接点
public void deleteUser(){
System.out.println("删除用户");
}
//三个方法都是连接点。
切面
切面:是切入点和通知的结合
织入
织入:就是通过动态代理对目标对象方法进行增强的过程。
2.示例
package com.tutorialspoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
@Aspect
public class Logging {
/** Following is the definition for a pointcut to select
* all the methods available. So advice will be called
* for all the methods.
*/
@Pointcut("execution(* com.tutorialspoint.*.*(..))")
private void selectAll(){}
/**
* This is the method which I would like to execute
* before a selected method execution.
*/
@Before("selectAll()")
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}
/**
* This is the method which I would like to execute
* after a selected method execution.
*/
@After("selectAll()")
public void afterAdvice(){
System.out.println("Student profile has been setup.");
}
/**
* This is the method which I would like to execute
* when any method returns.
*/
@AfterReturning(pointcut = "selectAll()", returning="retVal")
public void afterReturningAdvice(Object retVal){
System.out.println("Returning:" + retVal.toString() );
}
/**
* This is the method which I would like to execute
* if there is an exception raised by any method.
*/
@AfterThrowing(pointcut = "selectAll()", throwing = "ex")
public void AfterThrowingAdvice(IllegalArgumentException ex){
System.out.println("There has been an exception: " + ex.toString());
}
}