- AOP:面向切面(方面)编程,扩展功能不修改源代码实现
- AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码
- AOP底层使用动态代理实现
(1)第一种情况,有接口情况,使用动态代理创建接口实现类代理对象
(2)第二种情况,没有接口情况,使用动态代理创建类的子类代理对象 - AOP操作术语:
(1)Joinpoint(连接点): 类里面可以被增强的方法,这些方法称为连接点
(2)Pointcut(切入点):所谓切入点是指我们要对哪些Joinpoint进行拦截的定义.
(3)Advice(通知/增强):所谓通知是指拦截到Joinpoint之后所要做的事情就是通知.通知分为前置通知,后置通知,异常通知,最终通知,环绕通知(切面要完成的功能)
(4)Aspect(切面): 是切入点和通知(引介)的结合
(5)Introduction(引介):引介是一种特殊的通知在不修改类代码的前提下,Introduction可以在运行期为类动态地添加一些方法或Field.
(6)Target(目标对象):代理的目标对象(要增强的类)
(7)Weaving(织入):是把增强应用到目标的过程.把advice 应用到 target的过程
(8)Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类 - 在spring里面进行aop操作,使用aspectj实现
(1)aspectj不是spring一部分,和spring一起使用进行aop操作
(2)Spring2.0以后新增了对AspectJ支持 - 使用aspectj实现aop有两种方式
(1)基于aspectj的xml配置
(2)基于aspectj的注解方式
<?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="book" class="cn.itcast.aop.Book"></bean>
<bean id="myBook" class="cn.itcast.aop.MyBook"></bean>
<aop:config>
<aop:pointcut expression="execution(* cn.aop.Book.*(..))" id="pointcut1"/>
<aop:aspect ref="myBook">
<aop:before method="before1" pointcut-ref="pointcut1"/>
<aop:after-returning method="after1" pointcut-ref="pointcut1"/>
<aop:around method="around1" pointcut-ref="pointcut1"/>
</aop:aspect>
</aop:config>
</beans>
package cn.aop;
public class Book {
public void add() {
System.out.println("add..");
}
}
package cn.aop;
import org.aspectj.lang.ProceedingJoinPoint;
public class MyBook {
public void before1() {
System.out.println("前置增强......");
}
public void after1() {
System.out.println("后置增强......");
}
public void around1(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("方法之前.....");
proceedingJoinPoint.proceed();
System.out.println("方法之后.....");
}
}
package cn.aop;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAnno {
@Test
public void testService() {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean3.xml");
Book book = (Book) context.getBean("book");
book.add();
}
}