前言
AOP(Aspect Oriented Programming):面向切面编程。它是Spring框架中的一个重要内容,复杂的概念在这也就不说了,举个例子给大家简单的讲解一下。
概述
面向切面编程(AOP)是什么?大家都知道,正常程序的执行流程都是纵向执行的,从上而下执行。而AOP则是在程序原有执行流程中,针对某一个或某一些方法来添加通知,以此形成横切面的过程就叫做面向切面编程。它不需要修改原有的程序代码,有着较高的扩展性。简单画个图,如下:
实现方式
Spring框架中为我们提供了两种实现AOP的方式,Schema-based和AspectJ。
Schema-based:每个通知都需要实现接口或类,配置在<aop:config>标签
AspectJ:每个通知不需要实现接口或类,配置在<aop:config>的子标签<aop:aspect>
具体步骤
今天只给大家讲解一下Schema-based的实现
1.导入相关jar包
2.新建一个Demo类,供测试使用
package a.b.test;
public class Demo {
public void demo1(){
System.out.println("demo1");
}
public void demo2(){
System.out.println("demo2");
}
public void demo3(){
System.out.println("demo3");
}
}
3.新建通知类
前置通知
package a.b.advice;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyBeforeAdvice implements MethodBeforeAdvice{
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
System.out.println("执行前置通知");
}
}
后置通知
package a.b.advice;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class MyAfterAdvice implements AfterReturningAdvice{
public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
System.out.println("执行后置通知");
}
}
arg0:切点方法返回值
arg1:切点方法对象
arg2:切点方法参数
arg3:切点方法所在类的对象
4.applicationContext.xml
引入AOP命名控件,配置通知类的<bean>,配置切面
<?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="mybefore" class="a.b.advice.MyBeforeAdvice"></bean>
<bean id="myafter" class="a.b.advice.MyAfterAdvice"></bean>
<!-- 配置切面 -->
<aop:config>
<!-- 配置切点 -->
<aop:pointcut expression="execution(* a.b.test.Demo.demo2())" id="mypoint"/>
<!-- 通知 -->
<aop:advisor advice-ref="mybefore" pointcut-ref="mypoint"/>
<aop:advisor advice-ref="myafter" pointcut-ref="mypoint"/>
</aop:config>
<!-- 配置Demo类,测试使用 -->
<bean id="demo" class="a.b.test.Demo"></bean>
</beans>
5.测试
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Demo demo = ac.getBean("demo", Demo.class);
demo.demo1();
demo.demo2();
demo.demo3();
}
}
6.运行结果
最后给大家讲几个······概念:
- 原有功能:切点,pointcut
- 前置通知:在切点之前执行的功能。before advice
- 后置通知:在切点之后执行的功能。after advice
- 如果切点执行过程中出现异常,会触发异常通知。throws advice
- 所有功能总称叫做切面
- 织入:把切面嵌入到原有功能的过程叫做织入
以上就是整个Schema-based实现AOP的过程