首先导入相关jar包
创建dao类IUserDao
package cn.qblank.aop.dao;
import org.springframework.stereotype.Component;
@Component
public interface IUserDao {
void add();
void delete();
}
创建dao实现类UserDao实现接口
package cn.qblank.aop.dao.impl;
import org.springframework.stereotype.Component;
import cn.qblank.aop.dao.IUserDao;
@Component
public class UserDao implements IUserDao{
@Override
public void add() {
int i = 1/0;
System.out.println("添加数据中...");
}
@Override
public void delete() {
System.out.println("删除数据...");
}
}
创建切面类Aop
package cn.qblank.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Component
@Aspect //指定为切面类
public class Aop {
/**
* 环绕
* @param pjp
* @return
* @throws Throwable
*/
@Around("execution(public * cn.qblank.aop.dao.*.*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("开启事务....");
Object obj = pjp.proceed();
System.out.println("提交事务....");
return obj;
}
/**
* 抛出异常
*/
@AfterThrowing("execution(public * cn.qblank.aop.dao.*.*(..))")
public void afterThrowing(){
System.out.println("回滚事务!!!");
}
}
创建Config类进行注解扫描
package cn.qblank.aop;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan("cn.qblank.aop")
@EnableAspectJAutoProxy
public class AppConfig {
}
接下来我们进行测试
package cn.qblank.aop.Main;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import cn.qblank.aop.AppConfig;
import cn.qblank.aop.dao.IUserDao;
public class Test {
public static void main(String[] args) {
//开启扫描
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
IUserDao userDao = context.getBean(IUserDao.class);
// userDao.add();
userDao.delete();
context.close();
}
}
运行结果如下: