AOP是Aspect Oriented Programming的简称,中文一般叫做面向切面编程,是通过实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。
以往我们正常编写程序和执行程序的时候一般都是纵向的,即程序从上往下执行,例如:
例如上面的Demo,我们创建一个Demo类对象,然后调用它的三个方法,这三个方法依次执行。
而AOP则是需要在不改变原有代码的情况下,可以在拓展程序的功能,例如我们可以在function2调用的前后增加其他功能形成一个“横切面”。
在AOP中,function2就叫做“切点(pointcut)”,在切点之前拓展增强的功能叫“前置通知(before advice)”,在切点之后拓展的功能叫“后置通知(after advice)”,它们一起组成了“切面”,把切面嵌入到原有功能的过程叫“织入”。
AOP的重要作用是在不修改源代码的情况下给程序动态拓展功能,同时使原功能更加单一,逻辑更加明确(低耦合,高内聚)。
Spring AOP
Spring提供了两种AOP实现方式,SpringAOP和AspectJ AOP。Spring AOP 属于运行时增强,而 AspectJ 是编译时增强。 Spring AOP 基于代理(Proxying)(JDK动态代理或Cglib代理),而 AspectJ 基于字节码操作(Bytecode Manipulation)。
Spring AOP就是基于动态代理的,如果要代理的对象,实现了某个接口,那么Spring AOP会使用JDK Proxy,去创建代理对象,而对于没有实现接口的对象,就无法使用 JDK Proxy 去进行代理了,这时候Spring AOP会使用Cglib ,这时候Spring AOP会使用 Cglib 生成一个被代理对象的子类来作为代理。
使用Spring框架AOP功能需要依赖相关的包:aopalliance.jar和aspectjweaver.jar。
SpringAOP(Schema-based AOP)实现前、后置通知
还是以上面的例子为例来实现AOP功能,实现AOP需要“前置通知”和“后置通知”,所以我们首先需要新建作为功能拓展的“通知类”。
前置通知类需要实现MethodBeforeAdvice接口,后置通知类需要实现AfterReturningAdvice接口。
package com.test.advice;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyBeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
System.out.println("before advice");
}
}
package com.test.advice;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class MyAfterAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
System.out.println("after advice");
}
}
创建完通知类后就需要进行织入,编写Spring配置文件。
在Spring配置文件中引入AOP命名空间,
在Spring配置文件中编写所需bean标签管理对象。
随后配置AOP切面。
完整的Spring配置文件如下:
<?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="com.test.Demo"></bean>
<bean id="myBeforeAdvice" class="com.test.advice.MyBeforeAdvice"></bean>
<bean id="myAfterAdvice" class="com.test.advice.MyAfterAdvice"></bean>
<aop:config>
<aop:pointcut expression="execution(* com.test.Demo.function2())" id="mypointcut"/>
<aop:advisor advice-ref="myBeforeAdvice" pointcut-ref="mypointcut"/>
<aop:advisor advice-ref="myAfterAdvice" pointcut-ref="mypointcut"/>
</aop:config>
</beans>
运行结果:
可见在function2方法之前执行了MyBeforeAdvice,在function2方法之后执行了MyAfterAdvice。
通配符
前面在配置<aop:pointcut>
标签的expression属性时使用到了通配符“*
”,前面那个“*
”表示返回值可以是任意类型,如果想将类所有方法设为切点,可以写为:
将方法名用通配符“*
”代替。
同理,通配符“*
”还可以替代任意类、任意包,语法如下,修饰符一般省略:
语法:execution(修饰符 返回值 包.类.方法名(参数) throws异常)
如果需要匹配任意参数类型的方法可以用“..
”表示:
这样function2()和function2(String str)都变成了切点,增加了通知。
如果只需要将带参数的方法设为切点,则可以写为:
这样就可以将参数为String类型的function2方法定义为切点了。
通知方法参数
SpringAOP前置通知和后置通知都需要实现接口和特定方法,实现的方法中有多个与切点相关的参数。
其中前置通知方法的参数中:
第一个参数method表示切点方法,是java.lang.reflect.Method类型的;第二个参数是切点方法的参数;第三个参数是调用切点方法的切点类对象。
后置通知方法的参数中:
后置通知方法就比前置通知方法多了第一个参数“返回值”。
例如,我们把参数打印出来:
注意:Object类的默认toString方法是打印对象的地址的hash码。
SpringAOP(Schema-based AOP)实现异常通知
实现异常通知也需要新建一个类来实现一个接口ThrowsAdvice,ThrowsAdvice是一个没有声明任何方法的标记接口,但是我们需要自己书写符合规则的异常通知方法,在ThrowsAdvice的注释中提供了几种方法示例。
那我们就写一个实现ThrowsAdvice接口的异常通知类:
package com.test.advice;
import org.springframework.aop.ThrowsAdvice;
public class MyThrowsAdvice implements ThrowsAdvice {
public void afterThrowing(Exception ex) {
System.out.println("throws advice");
}
}
然后再在Spring配置文件中配置<bean>
标签和<aop:config>
标签。
<bean id="myThrowsAdvice" class="com.test.advice.MyThrowsAdvice"></bean>
<aop:config>
<aop:pointcut expression="execution(* com.test.Demo.function4())" id="mypointcut1"/>
<aop:advisor advice-ref="myThrowsAdvice" pointcut-ref="mypointcut1" />
</aop:config>
在Demo类中添加方法function4(),将其配置为切点并在其中编写除0的异常。
然后再在main方法调用查看运行结果:
从结果看成功的执行了异常通知方法并抛出了异常,因为function4方法中在打印语句前出现了异常所以没有打印“function4”。
注意不要在切点方法中try-catch处理异常,如果在切点方法中进行了异常的捕获处理,则切点方法不会抛出异常就不会执行到异常通知方法,例如:
程序正常执行,没有执行异常通知。所以我们如果想要异常通知生效,就不应该在切点方法中进行异常处理,而是应该抛出异常,在方法调用的时候进行异常处理。
这样就即执行了异常通知,又处理了异常。
SpringAOP(Schema-based AOP)实现环绕通知
环绕通知同时具有前置通知和后置通知的作用。
Schema-based AOP实现环绕通知需要新建通知类实现接口MethodInterceptor并实现invoke方法。
package com.test.advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MyArroundAdvice implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation arg0) throws Throwable {
System.out.println("arround advice - before");
Object result = arg0.proceed();
System.out.println("arround advice - after");
return result;
}
}
然后再配置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="com.test.Demo"></bean>
<bean id="myArroundAdvice" class="com.test.advice.MyArroundAdvice"></bean>
<aop:config>
<aop:pointcut expression="execution(* com.test.Demo.function2())" id="mypointcut1"/>
<aop:advisor advice-ref="myArroundAdvice" pointcut-ref="mypointcut1" />
</aop:config>
</beans>
再在main方法中调用切点方法看一下结果。
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Demo demo = ac.getBean("demo",Demo.class);
demo.function1();
demo.function2();
demo.function3();
}
}
JDK动态代理还是Cglib动态代理
在Spring AOP中默认使用的是JDK动态代理,但也有一个前提是被代理类实现了接口(可以是任意接口),且切点方法是通过接口引用(向上转型)调用的。
例如,我们声明一个接口;
package com.test;
public interface DemoInterface {
public void function1();
public void function2();
public void function3();
}
然后让被代理的Demo类实现该接口。
配置文件applicationContext.xml不需要改动,再通过接口类来获取Demo类的实例。
然后我们通过断点调试,会发现demo对象使用的是JDK动态代理。
注意是必须被代理类实现接口,且通过接口获取ApplicationContext容器中的实例,如果不是使用接口获取实例,则会报错:无法代理。
Exception in thread "main" org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'demo' must be of type [com.test.Demo], but was actually of type [com.sun.proxy.$Proxy2]
如果被代理类实现了接口仍然想要使用Cglib动态代理,可以在Spring配置文件applicationContext.xml中使用 <aop:aspectj-autoproxy proxy-target-class="true"/>
标签来配置,proxy-target-class默认值为false,即默认使用JDK动态代理。
此时通过端点调试可以看到,尽管Demo类实现了接口,但demo对象使用的是Cglib动态代理。
如果被代理类没有实现接口,不配置<aop:aspectj-autoproxy proxy-target-class="true"/>
也会走Cglib动态代理。
Spring AOP就是基于动态代理的,如果要代理的对象,实现了某个接口,那么Spring AOP会使用JDK Proxy,去创建代理对象,而对于没有实现接口的对象,就无法使用 JDK Proxy 去进行代理了,这时候Spring AOP会使用Cglib ,这时候Spring AOP会使用 Cglib 生成一个被代理对象的子类来作为代理。