一. Spring的基于ApsectJ的注解的AOP开发
1. 编写目标类并配置
2. 编写切面类并配置
3. 在配置文件中打开注解的AOP开发
4. 在切面类上使用注解@Aspect
5. 前置通知@Before
6. 后置通知@AfterReturning
7. 注解配置切入点
8. 环绕通知@Around, 使用切入点
9. 异常抛出通知@AfterThrowing
10. 最终通知@After
二. AOP注解开发例子
1. 新建一个名为AOPAnnotation的Java项目
2. 创建UserDaoImpl.java类
package com.lywgames.dao.impl;
public class UserDaoImpl{
public void insert() {
System.out.println("插入数据");
}
public void select() {
System.out.println("查询数据");
}
public void update() {
System.out.println("更新数据");
throw new RuntimeException();
}
public int delete() {
System.out.println("删除数据");
return 1;
}
}
3. 创建AspectJAop.java切面类
package com.lywgames.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
/**
* 切面类
*/
@Aspect
public class AspectJAop {
@Before(value="execution(* com.lywgames.dao.impl.UserDaoImpl.insert(..))")
public void beforeInsertCheck() {
System.out.println("检测插入数据");
}
@AfterReturning(value="execution(* com.lywgames.dao.impl.UserDaoImpl.delete(..))", returning="result")
public void afterDelete(int result) {
System.out.println("删除后返回值:" + result);
}
@Around(value="AspectJAop.selectPoint()")
public Object arround(ProceedingJoinPoint joinPoint) {
try {
System.out.println("查询前鼓鼓掌。");
Object obj = joinPoint.proceed();
System.out.println("查询后鼓鼓掌。");
return obj;
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
@AfterThrowing(value="AspectJAop.updateExceptionPoint()", throwing="ex")
public void updateException(Throwable ex) {
System.out.println("更新发生了异常:" + ex.toString());
}
@After(value="AspectJAop.updateFinallyPoint()")
public void myFinally() {
System.out.println("更新方法发生了异常, 最终通知一样会执行完成。");
}
@Pointcut(value="execution(* com.lywgames.dao.impl.UserDaoImpl.select(..))")
private void selectPoint() {}
@Pointcut(value="execution(* com.lywgames.dao.impl.UserDaoImpl.update(..))")
private void updateExceptionPoint() {}
@Pointcut(value="execution(* com.lywgames.dao.impl.UserDaoImpl.update(..))")
private void updateFinallyPoint() {}
}
4. 创建AopAction.java测试类
package com.lywgames.action;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lywgames.dao.impl.UserDaoImpl;
public class AopAction {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDaoImpl userDaoImpl = context.getBean(UserDaoImpl.class);
userDaoImpl.insert();
userDaoImpl.delete();
userDaoImpl.select();
userDaoImpl.update();
context.close();
}
}
5. 在src目录下添加applicationContext.xml配置
6. 运行项目