前言
在开始分析AOP之前,大家可以参考我的前2篇博客。
Java动态代理(https://www.jianshu.com/p/e6914f48f2a9)
Spring IOC(https://www.jianshu.com/p/3c70f548481d)
AOP即面向切面编程,其本质上就是把大多数接口都要做或者必须做的事情委托给代理类来做。比如所有人都要买房子,那么大家可以把这件事交给房产交易平台。网上博客翻了个底朝天也没有找到哪个博客把AOP源码解析部分讲的比较透彻的,大多数都让人摸不着头脑,即便给了aop入口说的也不是很清晰。本篇博客将以赵本山和宋丹丹的经典小品钟点工为例,讲讲把大象装冰箱的故事,来详细的描述下面向切面编程。
所用代码地址:https://github.com/KouLouYiMaSi/SpringDecode
一、Spring配置面向切面编程
1、ApplicationContext.xml配置
除了两个bean:zhaobenshan和adviceElephantTools,其他bean可以忽略。Aop配置中配置了切面myaop(切面想象成大象装冰箱服务公司),待切入的切入点logPointcut(这里使用了aspectj表达式,看看就行),切入的两个方法before和after。
值得注意的是本xml头部信息里需要有aop的相关声明!
<?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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean id="springHelloWorld"
class="com.yiibai.tutorial.spring.helloworld.impl.SpringHelloWorld"></bean>
<bean id="strutsHelloWorld"
class="com.yiibai.tutorial.spring.helloworld.impl.StrutsHelloWorld"></bean>
<bean id="helloWorldService" class="com.yiibai.tutorial.spring.helloworld.HelloWorldService">
<property name="helloWorld" ref="strutsHelloWorld" />
</bean>
<bean id="zhaobenshan" class="com.yiibai.tutorial.spring.aop.Zhaobenshan" />
<bean id="adviceElephantTools" class="com.yiibai.tutorial.spring.aop.AdviceElephantTools" />
<aop:config>
<aop:aspect id="myaop" ref="adviceElephantTools"> <!--切面名称-->
<aop:pointcut id="logPointcut"
expression="execution(* com.yiibai.tutorial.spring.aop.*.*(..))" /> <!--切入点-->
<aop:before method="before" pointcut-ref="logPointcut" /> <!--前置方法-->
<aop:after method="after" pointcut-ref="logPointcut" /> <!--后置方法-->
</aop:aspect>
</aop:config>
</beans>
2、两个bean配置
这里为了使用JDK动态代理而设计了一个接口,spring aop会默认使用jdk动态代理,在没有接口的情况下会使用cglib动态代理。
赵本山需要实现大象工具接口来把大象装冰箱里,但是大象工具切面类还提供了打开冰箱门和关闭冰箱门等操作。如果世界上有1000个赵本山那么只需要一个大象切面类就能为所有赵本山提供打开冰箱门和关闭冰箱门操作。
public interface PuttingTool {
public abstract void putElephantToRefrigerator();
}
public class Zhaobenshan implements PuttingTool {
publ