AOP概念
- 切面(Aspect):所有关注点的抽象。就像类是所有对象的抽象一样,切面就是所有关注点的抽象。
- 连接点(JoinPoint):被拦截到的点。在插入切面时所切入的位置。
- 通知(Advice):拦截到连接点所做的事(执行的方法)。拦截到连接点,所切入进去的内容。
- 切入点(PointCut):可以理解为连接点的集合。
- 目标对象(Target Object):被切入的对象。在spring中即为被代理的对象。
- 织入(Weaving):将切面应用到目标上,并建立代理对象的过程。
- 引入(Introduction):对目标对象声明新方法和属性。对目标对象增加新的方法和属性,相当于动态的对目标对象进行了更新。
AOP实现
实现方式一:通过配置aop的参数来实现
新建业务类Handle
public class Handle { public void copy() { System.out.println("copy : "); } public void delete() { System.out.println("delete : "); } }
业务类Handle实现了两个方法,copy()和delete()
新建切面MyAspect
public class MyAspect { public void start(){ System.out.println("start handle"); } public void stop(){ System.out.println("stop handle"); } }
切面类实现了两个方法,start()和stop()
配置xml文件aoptest.xml
<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" xmlns:context="http://www.springframework.org/schema/context" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd "> <bean id="handle" class="cn.taozui.handle.Handle"></bean> <bean id="aspect" class="cn.taozui.aspect.MyAspect"></bean> <aop:config> <aop:aspect id="myaspect" ref="aspect"> <aop:pointcut id="pointcut" expression="execution(* cn.taozui.handle.*.*(..))" /> <aop:before method="start" pointcut-ref="pointcut" /> <aop:after method="stop" pointcut-ref="pointcut"/> </aop:aspect> </aop:config> </beans>
配置文件中,实现了一个Handle的实例handle,实现了一个MyAspect的实例aspect,这部分是通过ioc实现,下面的配置完成了aop的配置
测试类Test
public class Test { public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("aoptest.xml"); Handle h = (Handle)app.getBean("handle"); h.copy(); h.delete(); } }
测试类运行了copy()和delete(),运行时会在方法执行前插入前置通知before,方法执行完后插入后置通知after
运行结果
start handle --前置通知的方法执行的信息 copy : --连接点方法执行的信息 stop handle --后置通知的方法执行的信息 start handle --前置通知的方法执行的信息 delete : --连接点方法执行的信息 stop handle --后置通知的方法执行的信息