Spring实现AOP(Before/AfterReturning/Around/AfterThrowing/After)

AspectJ提供不同的通知类型

  • Before前置通知
  • AfterReturning后置通知
  • Around 环绕通知
  • AfterThrowing拋 出通知
  • After 最终final通知,不管是否异常,该通知都会执行
  • DeclareParents引介通知

1. 首先导包和引入命名空间,请查看

2. 创建接口和实现类

接口:

public interface StudentService {
	void addStudent();
}

实现类:

public class StudentServiceImpl implements StudentService{
	@Override
	public void addStudent() {
		System.out.println("添加学生");
		
	}
}

3. 创建增强类(AOP类)等等 说法不一致

public class AopDemo {
	public void before() {
		System.out.println("前置方法");
	}
	public void after() {
		System.out.println("后置方法");
	}
	public void after1(JoinPoint joinPoint,Object rv) {
		System.out.println("当前运行的类是"+joinPoint.getTarget().getClass().getName()+"运行的方法名为:"+joinPoint.getSignature().getName());
		System.out.println("返回值为:"+rv);
	}
	public void around(ProceedingJoinPoint pd) throws Throwable {
		System.out.println("环绕头");
		Object object = pd.proceed();
		System.out.println("环绕尾");
	}
	public void afterTrowing(JoinPoint joinPoint,Throwable ex) {
		System.out.println(
				"亲爱的管理员,目前系统出现异常,请及时处理,发生异常的类是"
				+joinPoint.getTarget().getClass().getName()
				+",发生异常的方法为:"
				+joinPoint.getSignature().getName()
				+",异常信息为:"
				+ex.getMessage()
				);
	}
	public void afterFinally() {
		System.out.println("这是一个最终通知");
	}
}

4. 在xml文件内,实例bean和配置切入点和切面

	<bean id="studentService" class="com.hisoft.service.impl.StudentServiceImpl"/>
	<bean id="aopDemo" class="com.hisoft.aop.AopDemo"/>
	//实例化bean,StudentServiceImpl类和aop类
	
	//配置切入点和切面
	<aop:config proxy-target-class="true">
		<!--配置切入点(其实就是拦截哪些方法)以service结尾的bean。 进行增强-->
		<aop:pointcut expression="bean(*Service)" id="myPointcurd"/>
		<!--配置切面:关联切入点和切面,要对哪些方法进行怎么样的增强。ref :目标到增强的类- - >
		<aop:aspect ref="aopDemo">
			<!--配置前置通知
				method:该增强调用的通知类中的方法名(MyAspect)
				pointcut-ref:关联的切入点-->
			//前置
			<aop:before method="before" pointcut-ref="myPointcurd"/>
			//后置
			<aop:after-returning method="after" pointcut-ref="myPointcurd"/>
			<!--这个returning是切入点的返回值,这个里面的值要和增强类的参数一致-->
			//后置带参
			<aop:after-returning method="after1" pointcut-ref="myPointcurd" returning="rv"/>
			//环绕
			<aop:around method="around" pointcut-ref="myPointcurd"/>
			//抛出通知
			<aop:after-throwing method="afterTrowing" pointcut-ref="myPointcurd" throwing="ex"/>
			//最终通知
			<aop:after method="afterFinally" pointcut-ref="myPointcurd"/>
		</aop:aspect>
	</aop:config>

5. 测试

我这里使用main方法进行测试了,没有使用junit(效果是一样的)

public class UserTest {

	public static void main(String[] args) {
		ApplicationContext app =new ClassPathXmlApplicationContext("applicationContext.xml");
		StudentServiceImpl ss = (StudentServiceImpl) app.getBean("studentService");
		ss.addStudent();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值