Spring框架中的AspectJ实现前后置通知

引言

上次给大家讲解了Spring框架中AOP的两种实现方式当中的Schema-based,今天继续给大家讲解一下使用AspectJ来实现通知。相对于Schema-based来讲,AspectJ的实现方式要相对简单一些,话不多说,直接上代码。

具体步骤

1.导入jar包

2.新建一个Demo类

package a.b.test;

public class Demo {
	public void demo1() throws Exception{
//		int i = 5/0;
		System.out.println("demo1");
	}
}

3.新建通知类

相比Schema-based来说,在AspectJ中不需要是一个类去实现一个通知,所以我们只需要一个类或方法就够了。

package a.b.advice;

import org.aspectj.lang.ProceedingJoinPoint;

public class MyAdvice {
	public void mybefore(){
		System.out.println("前置");
	}
        public void myafter(){
		System.out.println("后置1");
	}
	public void myaftering(){
		System.out.println("后置2");
	}
}

4.applicationContext.xml

<?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: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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="demo" class="a.b.test.Demo"></bean>
    <bean id="myadvice" class="a.b.advice.MyAdvice"></bean>
    <aop:config>
    	<aop:aspect ref="myadvice">
    		<aop:pointcut expression="execution(* a.b.test.Demo.demo1())" id="mypoint"/>
    		<aop:before method="mybefore" pointcut-ref="mypoint"/>
    		<aop:after method="myafter" pointcut-ref="mypoint"/>
    		<aop:after-returning method="myaftering" pointcut-ref="mypoint"/> 
    	</aop:aspect>
    </aop:config>
</beans>

5.测试

package a.b.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		Demo demo = ac.getBean("demo",Demo.class);
	}
	
}

6.运行结果

其中有一些需要注意的,在配置文件中,后置通知它有两个标签,一个是<aop:after>,还有一个是<aop:after-returning>。通知类的代码执行顺序是按照配置标签的顺序来执行的,这两个标签谁在前面,就先执行谁的代码。那这二者的区别是什么,按照之前讲的,如果Demo类中出现异常,则后置通知不执行。但是在这里却不一样,可是运行代码时,仍然会执行后置通知,但结果只输出了后置1。所以区别就是<aop:after-returning>标签只能在切点正常执行完成之后,才会有输出。而<aop:after>标签不管是切点出不出异常,它都会输出结果。

以上就是使用AspectJ方式来实现前后置通知

猜你喜欢

转载自blog.csdn.net/Let_Me/article/details/81207423