什么是AOP?
- 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,是通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态添加功能的一种技术。
- 经典应用:事务管理、性能监视、安全检查、缓存 、日志等。
- Spring AOP使用纯Java实现,不需要专门的编译过程和类加载器,在运行期通过代理方式向目标类织入增强代码。
- AspectJ是一个基于Java语言的AOP框架,Spring2.0开始,Spring AOP引入对Aspect的支持,AspectJ扩展了Java语言,提供了一个专门的编译器,在编译时提供横向代码的织入。
AOP术语
- Target(目标对象):代理的目标对象
- Joinpoint(连接点):所谓连接点是指那些被拦截到的点。在Spring中,这些点指的是方法,因为Spring只支持方法类型的连接点.
- Pointcut(切入点):所谓切入点是指我们要对哪些Joinpoint进行拦截的定义.
- Advice(通知/增强):所谓通知是指拦截到Joinpoint之后所要做的事情就是通知。通知分为前置通知,后置通知,异常通知,最终通知,环绕通知(切面要完成的功能)
- Introduction(引介):引介是一种特殊的通知在不修改类代码的前提下, Introduction可以在运行期为类动态地添加一些方法或Field.
- Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程.
- Spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入
- Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类
- Aspect(切面):是切入点和通知(引介)的结合
AOP基础——代理
- Spring在运行期,生成动态代理对象,不需要特殊的编译器
- Spring AOP的底层就是通过JDK动态代理或CGLIB动态代理技术为目标Bean执行横向织入
- 1.若目标对象实现了若干接口,Spring使用JDK的java.lang.reflect.Proxy类代理。
- 2.若目标对象没有实现任何接口,Spring使用CGLIB库生成目标对象的子类。
- 程序中应优先对接口创建代理,便于程序解耦维护
- 标记为final的方法,不能被代理,因为无法进行覆盖
- JDK动态代理,是针对接口生成子类,接口中方法不能使用final修饰
- CGLIB是针对目标类生产子类,因此类或方法不能是final的
- Spring只支持方法连接点,不提供属性连接
JDK动态代理
- JDK动态代理是对“装饰者”设计模式的简化。使用前提:必须有接口。
- 目标类:接口 + 实现类
- 切面类:用于存通知 MyAspect
- 工厂类:编写工厂生成代理
测试
public interface UserService { public void addUser(); public void updateUser(); public void deleteUser(); } public class UserServiceImpl implements UserService { @Override public void addUser() { System.out.println("a_proxy.a_jdk addUser"); } @Override public void updateUser() { System.out.println("a_proxy.a_jdk updateUser"); } @Override public void deleteUser() { System.out.println("a_proxy.a_jdk deleteUser"); } } public class MyAspect { public void before(){ System.out.println("鸡首"); } public void after(){ System.out.println("牛后"); } } public class MyBeanFactory { public static UserService createService(){ //1 目标类 final UserService userService = new UserServiceImpl(); //2切面类 final MyAspect myAspect = new MyAspect(); /* 3 代理类:将目标类(切入点)和 切面类(通知) 结合 --> 切面 * Proxy.newProxyInstance * 参数1:loader ,类加载器,动态代理类 运行时创建,任何类都需要类加载器将其加载到内存。 * 一般情况:当前类.class.getClassLoader(); * 目标类实例.getClass().get... * 参数2:Class[] interfaces 代理类需要实现的所有接口 * 方式1:目标类实例.getClass().getInterfaces() ;注意:只能获得自己接口,不能获得父元素接口 * 方式2:new Class[]{UserService.class} * 例如:jdbc 驱动 --> DriverManager 获得接口 Connection * 参数3:InvocationHandler 处理类,接口,必须进行实现类,一般采用匿名内部类 * 提供 invoke 方法,代理类的每一个方法执行时,都将调用一次invoke * 参数31:Object proxy :代理对象 * 参数32:Method method : 代理对象当前执行的方法的描述对象(反射) * 执行方法名:method.getName() * 执行方法:method.invoke(对象,实际参数) * 参数33:Object[] args :方法实际参数 * */ UserService proxService = (UserService)Proxy.newProxyInstance( MyBeanFactory.class.getClassLoader(), userService.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //前执行 myAspect.before(); //执行目标类的方法 Object obj = method.invoke(userService, args); //后执行 myAspect.after(); return obj; } }); return proxService; } } public class TestJDK { @Test public void test(){ UserService userService = MyBeanFactory.createService(); userService.addUser(); userService.updateUser(); userService.deleteUser(); } } 结果: 鸡首 a_proxy.a_jdk addUser 牛后 鸡首 a_proxy.a_jdk updateUser 牛后 鸡首 a_proxy.a_jdk deleteUser 牛后
CGLIB动态代理
- 对于不使用接口的业务类,无法使用JDK动态代理
CGLIB采用增强底层字节码技术,可以为一个类创建子类,解决无接口代理问题
public class UserServiceImpl { public void addUser() { System.out.println("a_proxy.b_cglib addUser"); } public void updateUser() { System.out.println("a_proxy.b_cglib updateUser"); } public void deleteUser() { System.out.println("a_proxy.b_cglib deleteUser"); } } public class MyAspect { public void before(){ System.out.println("鸡首2"); } public void after(){ System.out.println("牛后2"); } } public class MyBeanFactory { public static UserServiceImpl createService(){ //1 目标类 final UserServiceImpl userService = new UserServiceImpl(); //2切面类 final MyAspect myAspect = new MyAspect(); // 3.代理类 ,采用cglib,底层创建目标类的子类 //3.1 核心类 Enhancer enhancer = new Enhancer(); //3.2 确定父类 enhancer.setSuperclass(userService.getClass()); /* 3.3 设置回调函数 , MethodInterceptor接口 等效 jdk InvocationHandler接口 * intercept() 等效 jdk invoke() * 参数1、参数2、参数3:以invoke一样 * 参数4:methodProxy 方法的代理 * * */ enhancer.setCallback(new MethodInterceptor(){ @Override public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { //前 myAspect.before(); //执行目标类的方法 Object obj = method.invoke(userService, args); // 或者,执行代理类的父类,也就是执行目标类 (目标类和代理类是父子关系) //methodProxy.invokeSuper(proxy, args); //后 myAspect.after(); return obj; } }); //3.4 创建代理 UserServiceImpl proxService = (UserServiceImpl) enhancer.create(); return proxService; } } public class TestCglib { @Test public void test(){ UserServiceImpl userService = MyBeanFactory.createService(); userService.addUser(); userService.updateUser(); userService.deleteUser(); } } 结果: 鸡首2 a_proxy.b_cglib addUser a_proxy.b_cglib addUser 牛后2 鸡首2 a_proxy.b_cglib updateUser a_proxy.b_cglib updateUser 牛后2 鸡首2 a_proxy.b_cglib deleteUser a_proxy.b_cglib deleteUser 牛后2
AOP联盟通知(增强)类型
AOP联盟为通知Advice定义了org.aopalliance.aop.Advice。Spring按照通知Advice在目标类方法的连接点位置,可以分为5类:
- 前置通知 org.springframework.aop.MethodBeforeAdvice
- 在目标方法执行前实施增强
- 后置通知 org.springframework.aop.AfterReturningAdvice
- 在目标方法执行后实施增强
- 环绕通知 org.aopalliance.intercept.MethodInterceptor
- 在目标方法执行前后实施增强
- 异常抛出通知 org.springframework.aop.ThrowsAdvice
- 在方法抛出异常后实施增强
- 引介通知 org.springframework.aop.IntroductionInterceptor
- 在目标类中添加一些新的方法和属性
Spring编写代理:半自动
让Spring 创建代理对象,从Spring容器中手动的获取代理对象。
public interface UserService {
public void addUser();
public void updateUser();
public void deleteUser();
}
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("b_factory_bean addUser");
}
@Override
public void updateUser() {
System.out.println("b_factory_bean updateUser");
}
@Override
public void deleteUser() {
System.out.println("b_factory_bean deleteUser");
}
}
/**
* 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
* * 采用“环绕通知” MethodInterceptor
*/
public class MyAspect implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
System.out.println("前3");
//手动执行目标方法
Object obj = mi.proceed();
System.out.println("后3");
return obj;
}
}
public class TestFactoryBean {
@Test
public void test(){
String xmlPath = "org/i/aop/proxy_factorybean/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//获得代理类
UserService userService = (UserService) applicationContext.getBean("proxyServiceId");
userService.addUser();
userService.updateUser();
userService.deleteUser();
}
}
<beans>
<!-- 1 创建目标类 -->
<bean id="userServiceId" class="org.i.aop.proxy_factorybean.UserServiceImpl"></bean>
<!-- 2 创建切面类 -->
<bean id="myAspectId" class="org.i.aop.proxy_factorybean.MyAspect"></bean>
<!-- 3 创建代理类
* 使用工厂bean FactoryBean ,底层调用 getObject() 返回特殊bean
* ProxyFactoryBean 用于创建代理工厂bean,生成特殊代理对象
interfaces : 确定接口们
通过<array>可以设置多个值
只有一个值时,value=""
target : 确定目标类
interceptorNames : 通知 切面类的名称,类型String[],如果设置一个值 value=""
optimize :强制使用cglib
<property name="optimize" value="true"></property>
底层机制
如果目标类有接口,采用jdk动态代理
如果没有接口,采用cglib 字节码增强
如果声明 optimize = true ,无论是否有接口,都采用cglib
-->
<bean id="proxyServiceId" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interfaces" value="org.i.aop.proxy_factorybean.UserService"></property>
<property name="target" ref="userServiceId"></property>
<property name="interceptorNames" value="myAspectId"></property>
</bean>
</beans>
结果:
前3
b_factory_bean addUser
后3
前3
b_factory_bean updateUser
后3
前3
b_factory_bean deleteUser
后3
Spring AOP编程:全自动
- 从Spring容器获得目标类,如果配置AOP,Spring将自动生成代理。
导包
public interface UserService { public void addUser(); public void updateUser(); public void deleteUser(); } public class UserServiceImpl implements UserService { @Override public void addUser() { System.out.println("c_spring_aop addUser"); } @Override public void updateUser() { System.out.println("c_spring_aop updateUser"); } @Override public void deleteUser() { System.out.println("c_spring_aop deleteUser"); } } public class MyAspect implements MethodInterceptor { @Override public Object invoke(MethodInvocation mi) throws Throwable { System.out.println("前4"); //手动执行目标方法 Object obj = mi.proceed(); System.out.println("后4"); return obj; } } public class TestSpringAOP { @Test public void test(){ String xmlPath = "org/i/aop/spring_aop/beans.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); //获得目标类 UserService userService = (UserService) applicationContext.getBean("userServiceId"); userService.addUser(); userService.updateUser(); userService.deleteUser(); } } <beans> <!-- 1 创建目标类 --> <bean id="userServiceId" class="org.i.aop.spring_aop.UserServiceImpl"></bean> <!-- 2 创建切面类(通知) --> <bean id="myAspectId" class="org.i.aop.spring_aop.MyAspect"></bean> <!-- 3 aop编程 3.1 导入命名空间 3.2 使用 <aop:config>进行配置 proxy-target-class="true" 声明时使用cglib代理 如果不声明: 目标类有接口,采用jdk动态代理 没有接口,采用cglib 字节码增强 <aop:pointcut> 切入点 ,从目标对象获得具体方法 <aop:advisor> 特殊的切面,只有一个通知 和 一个切入点 advice-ref 通知引用 pointcut-ref 切入点引用 3.3 切入点表达式 execution(* com.itheima.c_spring_aop.*.*(..)) 选择方法 返回值任意 包 类名任意 方法名任意 参数任意 --> <aop:config proxy-target-class="true"> <aop:pointcut expression="execution(* org.i.aop.spring_aop.*.*(..))" id="myPointCut"/> <aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut"/> </aop:config> </beans> 结果: 前4 c_spring_aop addUser 后4 前4 c_spring_aop updateUser 后4 前4 c_spring_aop deleteUser 后4
AspectJ
AspectJ是一个基于Java语言的AOP框架,Spring2.0以后新增了对AspectJ切点表达式支持。
@AspectJ 是AspectJ1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面。新版本Spring框架,建议使用AspectJ方式来开发AOP。
主要用途:自定义开发
切入点表达式
execution():用于描述方法 。
语法:execution(修饰符 返回值 包.类.方法名(参数) throws异常)
修饰符,一般省略
public 公共方法
* 任意
返回值,不能省略
void 返回没有值
String 返回值字符串
* 任意
包,[省略]
com.it.crm 固定包
com.it.crm.*.service crm包下面子包任意 (例如:com.itheima.crm.staff.service)
com.it.crm.. crm包下面的所有子包(含自己)
com.it.crm.*.service.. crm包下面任意子包,固定目录service,service目录任意包
类,[省略]
UserServiceImpl 指定类
*Impl 以Impl结尾
User* 以User开头
* 任意
方法名,不能省略
addUser 固定方法
add* 以add开头
*Do 以Do结尾
* 任意
(参数)
() 无参
(int) 一个整型
(int ,int) 两个
(..) 参数任意
throws ,可省略,一般不写。
综合1
execution(* com.it.crm.*.service..*.*(..))
综合2
<aop:pointcut expression="execution(* com.it.*WithCommit.*(..)) ||
execution(* com.it.*Service.*(..))" id="myPointCut"/>
AspectJ 通知类型
- AOP联盟定义通知类型,具有特性接口,必须实现,从而确定方法名称。
- AspectJ 通知类型,只定义类型名称。
个数:6种,知道5种,掌握1种。
- before:前置通知(应用:各种校验)
- 在方法执行前执行,如果通知抛出异常,阻止方法运行
- afterReturning:后置通知(应用:常规数据处理)
- 方法正常返回后执行,如果方法中抛出异常,通知无法执行
- 必须在方法执行后才执行,所以可以获得方法的返回值。
- around:环绕通知(应用:十分强大,可以做任何事情)
- 方法执行前后分别执行,可以阻止方法的执行
- 必须手动执行目标方法
- afterThrowing:抛出异常通知(应用:包装异常信息)
- 方法抛出异常后执行,如果方法没有抛出异常,无法执行
after:最终通知(应用:清理现场)
方法执行完毕后执行,无论方法中是否出现异常
环绕 try{ //前置:before //手动执行目标方法 //后置:afterRetruning } catch(){ //抛出异常 afterThrowing } finally{ //最终 after }
- before:前置通知(应用:各种校验)
实例——基于xml
- 目标类:接口 + 实现
- 切面类:编写多个通知,采用AspectJ 通知名称任意(方法名任意)
- AOP编程,将通知应用到目标类
测试
public interface UserService { public void addUser(); public String updateUser(); public void deleteUser(); } public class UserServiceImpl implements UserService { @Override public void addUser() { System.out.println("d_aspect.a_xml addUser"); } @Override public String updateUser() { System.out.println("d_aspect.a_xml updateUser"); // int i = 1/ 0; //用于抛出异常 return "I am Tyshawn"; } @Override public void deleteUser() { System.out.println("d_aspect.a_xml deleteUser"); } } /** * 切面类,含有多个通知 */ public class MyAspect { public void myBefore(JoinPoint joinPoint){ System.out.println("前置通知 : " + joinPoint.getSignature().getName()); } public void myAfterReturning(JoinPoint joinPoint,Object ret){ System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret); } public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{ System.out.println("前"); //手动执行目标方法 Object obj = joinPoint.proceed(); System.out.println("后"); return obj; } public void myAfterThrowing(JoinPoint joinPoint,Throwable e){ System.out.println("抛出异常通知 : " + e.getMessage()); } public void myAfter(JoinPoint joinPoint){ System.out.println("最终通知"); } } public class TestAspectXml { @Test public void test(){ String xmlPath = "org/j/aspect/xml/beans.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); //获得目标类 UserService userService = (UserService) applicationContext.getBean("userServiceId"); userService.addUser(); userService.updateUser(); userService.deleteUser(); } } <beans> <!-- 1 创建目标类 --> <bean id="userServiceId" class="org.j.aspect.xml.UserServiceImpl"></bean> <!-- 2 创建切面类(通知) --> <bean id="myAspectId" class="org.j.aspect.xml.MyAspect"></bean> <!-- 3 aop编程 <aop:aspect> 将切面类 声明“切面”,从而获得通知(方法) ref 切面类引用 <aop:pointcut> 声明一个切入点,所有的通知都可以使用。 expression 切入点表达式 id 名称,用于其它通知引用 --> <aop:config> <aop:aspect ref="myAspectId"> <aop:pointcut expression="execution(* org.j.aspect.xml.UserServiceImpl.*(..))" id="myPointCut"/> <!-- 3.1 前置通知 <aop:before method="" pointcut="" pointcut-ref=""/> method : 通知,及方法名 pointcut :切入点表达式,此表达式只能当前通知使用。 pointcut-ref : 切入点引用,可以与其他通知共享切入点。 通知方法格式:public void myBefore(JoinPoint joinPoint){ 参数1:org.aspectj.lang.JoinPoint 用于描述连接点(目标方法),获得目标方法名等 例如: --> <aop:before method="myBefore" pointcut-ref="myPointCut"/> <!-- 3.2后置通知 ,目标方法后执行,获得返回值 <aop:after-returning method="" pointcut-ref="" returning=""/> returning 通知方法第二个参数的名称 通知方法格式:public void myAfterReturning(JoinPoint joinPoint,Object ret){ 参数1:连接点描述 参数2:类型Object,参数名 returning="ret" 配置的 例如: --> <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" /> <!-- 3.3 环绕通知 <aop:around method="" pointcut-ref=""/> 通知方法格式:public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{ 返回值类型:Object 方法名:任意 参数:org.aspectj.lang.ProceedingJoinPoint 抛出异常 执行目标方法:Object obj = joinPoint.proceed(); 例如: --> <aop:around method="myAround" pointcut-ref="myPointCut"/> <!-- 3.4 抛出异常 <aop:after-throwing method="" pointcut-ref="" throwing=""/> throwing :通知方法的第二个参数名称 通知方法格式:public void myAfterThrowing(JoinPoint joinPoint,Throwable e){ 参数1:连接点描述对象 参数2:获得异常信息,类型Throwable ,参数名由throwing="e" 配置 例如: --> <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/> <!-- 3.5 最终通知 --> <aop:after method="myAfter" pointcut-ref="myPointCut"/> </aop:aspect> </aop:config> </beans>
实例——基于注解
- @Aspect:声明切面,修饰切面类,从而获得通知。
- 通知
- @Before 前置
- @AfterReturning 后置
- @Around 环绕
- @AfterThrowing 抛出异常
- @After 最终
切入点
@PointCut:修饰方法 private void xxx(){},之后通过“方法名”获得切入点引用
public interface UserService { public void addUser(); public String updateUser(); public void deleteUser(); } public class UserServiceImpl implements UserService { @Override public void addUser() { System.out.println("d_aspect.a_xml addUser"); } @Override public String updateUser() { System.out.println("d_aspect.a_xml updateUser"); // int i = 1/ 0; //用于抛出异常 return "I am Tyshawn"; } @Override public void deleteUser() { System.out.println("d_aspect.a_xml deleteUser"); } } /** * 切面类,含有多个通知 */ @Component @Aspect public class MyAspect { //切入点 @Pointcut("execution(* org.j.aspect.annotation.UserServiceImpl.*(..))") private void pointCut(){}; @Before("pointCut()") public void myBefore(JoinPoint joinPoint){ System.out.println("前置通知 : " + joinPoint.getSignature().getName()); } @AfterReturning(value = "pointCut()", returning = "ret" ) public void myAfterReturning(JoinPoint joinPoint,Object ret){ System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret); } @Around("pointCut()") public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{ System.out.println("前"); //手动执行目标方法 Object obj = joinPoint.proceed(); System.out.println("后"); return obj; } @AfterThrowing(value = "pointCut()",throwing = "e") public void myAfterThrowing(JoinPoint joinPoint,Throwable e){ System.out.println("抛出异常通知 : " + e.getMessage()); } @After("pointCut()") public void myAfter(JoinPoint joinPoint){ System.out.println("最终通知"); } } public class TestAspectAnno { @Test public void test(){ String xmlPath = "org/j/aspect/annotation/beans.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); //获得目标类 UserService userService = (UserService) applicationContext.getBean("userServiceId"); userService.addUser(); userService.updateUser(); userService.deleteUser(); } } <beans> <!-- 1.扫描 注解类 --> <context:component-scan base-package="org.j.aspect.annotation"></context:component-scan> <!-- 2.确定 aop注解生效 --> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>