Spring——AOP(面向切面编程)@AspectJ注解方式

来源:互联网 发布:周围神经炎知乎 编辑:程序博客网 时间:2024/05/23 19:20

要通过@AspectJ注解方式,实现Spring AOP ,需要三个步骤:

1.在配置文件中添加<aop:aspectj-autoproxy/>,启动对@AspectJ注解的支持。

2.定义切面Bean,在这个类的开头添加@AspectJ。

3.定义增强处理,在方法开头用@Before、@After、@Around修饰。

——————————————————————————————————————————————————————————————————————————

1.在配置文件中添加<aop:aspectj-autoproxy/>,启动对@AspectJ注解的支持。

<!-- 启动对@AspectJ注解的支持 -->  <aop:aspectj-autoproxy/> 

2.定义切面类,其他方法可以插入这个类里的方法。在这个类的开头添加@AspectJ。

// 使用@Aspect 定义一个切面类   @Aspect  public class LogAspect {          // 定义该类的其他内容           ...  } 

3.定义增强处理,在方法开头用@Before、@After、@Around修饰。

@Component  @Aspect  public class AopLog {            //方法执行前调用,插入前面。     @Before("execution (* com.zywang.services.impl.*.*(..))")      public void MyMethod() {          System.out.println("你们都可以来插入我");      }            //方法执行后调用,插入后面。      @After("execution (* com.zywang.services.impl.*.*(..))")      public void MyMethod() {          System.out.println("你们都可以来插入我");      }            //方法执行的前后调用,前后都插入。      @Around("execution (* com.zywang.services.impl.*.*(..))")      public Object MyMethod(ProceedingJoinPoint point) throws Throwable{          System.out.println("begin around");          Object object = point.proceed();          System.out.println("你们都可以来插入我");          return object;      }            //方法运行出现异常时调用,出现异常后插入。      @AfterThrowing(pointcut = "execution (* com.zywang.services.impl.*.*(..))",throwing = "ex")      public void MyMethod(Exception ex){          System.out.println("afterThrowing");          System.out.println(ex);      }  }  

Before增强处理:

@Before("execution (* com.zywang.services.impl.*.*(..))")

@Before( pointout = "execution (* com.zywang.services.impl.*.*(..))" ) 

@Before( value = "execution (* com.zywang.services.impl.*.*(..))" )

这三种写法都是对的。表示这些包里的方法都是切入点,在执行这些方法之前要执行Before(),即也可以理解为用Before()切入这些方法。

AfterReturning增强处理:

@AfterReturning(returning="rvt", pointcut="execution(* com.wicresoft.app.service.impl.*.*(..))")

如果底下的函数有参数,则必须写returning。

AfterThrowing 增强处理:

@AfterThrowing(pointcut ="execution(* cn.huaxia.spring.*.*(..))", throwing ="th")

After 增强处理:
Around 增强处理:

————————————————————————————————————————————————————————————

另外:我们可以申明切入点我们可以在多处使用。

Spring 切入点定义包含两个部分:

  • 一个切入点表达式。
  • 一个包含不需要参数和方法体的切入点方法。
// 使用@Pointcut Annotation 时指定切入点表达式   @pointcut("execution * transfer(..)")  // 使用一个返回值为void,方法体为空的方法来命名切入点   private void anyOldTransfer(){}    // 使用上面定义的切入点   @AfterReturning(pointcut="anyOldTransfer()", returning="reVal")  public void writeLog(String msg, Object reVal){      ...  } 


 

 

 

0 0
原创粉丝点击