spring AOP切面开发 基于aspectJ框架切点的注解开发


spring AOP切面开发 基于aspectJ框架切点的注解开发


基于annotation方案,注解开发

第一步:在配置文件中开启aspectj的注解

<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


<!-- 过滤可以使用注解的对象的类 -->
<context:component-scan base-package="cmo.demo"></context:component-scan>

<!-- 开启aspectj注解自动代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

</beans>
 



第二步:

A,在通知类中用@component标签来声明一个通知

B,在通知类中用@Aspect来声明一个切面

C,在通知类的方法中设置要过滤后,增强的方法

@Pointcut("execution(* *Test(..))")

public void pointcutTest(){};

D,在通知类中用标签来设置环绕通知,前置通知等

@Before("pointcutTest()")

package cmo.demo.aspectj_annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

//用注解声明是一个通知
@Component
@Aspect    //声明这个类就是一个切面
public class CustomerServiceHelper {
	
	@Pointcut("execution(* *Test(..))")
	public void pointcutTest(){};
	
	
	@Before("pointcutTest()")
	public void before(JoinPoint jp) {
		System.out.println("前置通知...");
	}
	
	@AfterReturning("pointcutTest()")
	public void afterReturing(JoinPoint jp){
		System.out.println("后置通知");
	}
	
	@Around("pointcutTest()")
	public void around(ProceedingJoinPoint pjp) throws Throwable{
		System.out.println("环绕方法+方法前");
		
		Object proceed = pjp.proceed();
		
		System.out.println("环绕方法+方法后");
	}
	
	@AfterThrowing(value="pointcutTest()",throwing="ex")
	public void throwtest(JoinPoint jp, Throwable ex){
		System.out.println("我要抛异常了"+ex);
	}
	
	
	@After("pointcutTest()")
	public void after(JoinPoint jp){
		System.out.println("最终会执行的方法");

	}

}







将配置文件和通知类写完以后就可以实现以上功能了





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值