1.使用maven引入依赖:
<dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.2.4.RELEASE</version> </dependency>
2.编写切面类:
/** * 切面类 */ @Aspect //定义切面 public class MyAspectAnno { @Before(value="myPointcut1()") public void before(JoinPoint joinPoint){ System.out.println("前置通知=================="+joinPoint); } @AfterReturning(value="myPointcut2()",returning = "result") public void afterReturing(Object result){ System.out.println("后置通知=================="+result); } @Around(value="myPointcut3()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("环绕前通知================"); Object obj = joinPoint.proceed(); // 执行目标方法 System.out.println("环绕后通知================"); return obj; } @AfterThrowing(value="myPointcut4()",throwing = "e") public void afterThrowing(Throwable e){ System.out.println("异常抛出通知=============="+e.getMessage()); } @After(value="myPointcut5()") public void after(){ System.out.println("最终通知=================="); } @Pointcut(value="execution(* com.imooc.aspectJ.demo1.ProductDao.save(..))") //给切面命名 <!-- * 表示所有的修饰符 如:public,private等-->
private void myPointcut1(){} @Pointcut(value="execution(* com.imooc.aspectJ.demo1.ProductDao.update(..))") private void myPointcut2(){} @Pointcut(value="execution(* com.imooc.aspectJ.demo1.ProductDao.delete(..))") private void myPointcut3(){} @Pointcut(value="execution(* com.imooc.aspectJ.demo1.ProductDao.findOne(..))") private void myPointcut4(){} @Pointcut(value="execution(* com.imooc.aspectJ.demo1.ProductDao.findAll(..))") private void myPointcut5(){} }
<!-- * 表示所有的修饰符 如:public,private等-->