SpringAOP应用之XML+注解模式

  1. XML 中开启Spring 对注解AOP 的⽀持
<!--开启aop注解驱动
	proxy-target-class:true强制使用cglib-->
<aop:aspectj-autoproxy/>
  1. 将applicationContext.xml中配置的AOP一步一步替换成注解
<bean id="logUtil" class="com.tong.utils.LogUtils"></bean>
<aop:config>
	<aop:aspect id="logAdvice" ref="LogUtils">
		<aop:pointcut id="pt1" expression="execution(* com.tong.edu.service.impl.TransferServiceImpl.*(..))"/>
		<aop:before method="beforeMethod" pointcut-ref="pt1"/>
		<aop:after-returning method="successMethod" returning="retValue"/>
		<aop:around method="arroundMethod" pointcut-ref="pt1"/>
    </aop:aspect>
</aop:config>
  1. 横切逻辑LogUtils替换成功后的注解
  package com.tong.utils;
  //将XML中的配置Bean-->logUtil替换
  @Component
  //XML中的<aop:aspect>标签
  @Aspect
  public class LogUtils {
  	//声明一个空实现方法,唯一作用就是承载@Pointcut当作切入点
      @Pointcut("execution(* com.tong.service.impl.TransferServiceImpl.*(..))")
      public void pt1(){
      }
      
      /**
       * 业务逻辑开始之前执行
       */
      //方位信息注解替换<aop:before>标签
      @Before("pt1()")
      public void beforeMethod(JoinPoint joinPoint) {
          Object[] args = joinPoint.getArgs();
          for (int i = 0; i < args.length; i++) {
              Object arg = args[i];
              System.out.println(arg);
          }
          System.out.println("业务逻辑开始执行之前执行.......");
      }
  
      /**
       * 业务逻辑结束时执行(无论异常与否)
       */
      @After("pt1()")
      public void afterMethod() {
          System.out.println("业务逻辑结束时执行,无论异常与否都执行.......");
      }
  
      /**
       * 异常时时执行
       */
      @AfterThrowing("pt1()")
      public void exceptionMethod() {
          System.out.println("异常时执行.......");
      }
  
      /**
       * 业务逻辑正常时执行
       */
      @AfterReturning(value = "pt1()",returning = "retVal")
      public void successMethod(Object retVal) {
          System.out.println("业务逻辑正常时执行.......");
      }
  
      /**
       * 环绕通知
       *
       */
      /*@Around("pt1()")*/
      public Object arroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
          System.out.println("环绕通知中的beforemethod....");

          Object result = null;
          try{
              // 控制原有业务逻辑是否执行
              // result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
          }catch(Exception e) {
              System.out.println("环绕通知中的exceptionmethod....");
          }finally {
              System.out.println("环绕通知中的after method....");
          }
  
          return result;
      }
  }

纯注解模式

在使⽤注解驱动开发aop时,我们要明确的就是,是注解替换掉配置⽂件中的下⾯这⾏配置:

<!--开启aop注解驱动
	proxy-target-class:true强制使用cglib-->
<aop:aspectj-autoproxy/>

在配置类中使⽤如下注解进⾏替换上述配置

@Configuration
@ComponentScan("com.tong")
@EnableAspectJAutoProxy //开启spring对注解AOP的⽀持
public class SpringConfiguration {
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值