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

要通过@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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值