AOP的相关术语
1、Joinpoint(连接点) --- 所谓连接点是指哪些被拦截到的点。在Spring中,这些点指的是方法,因为Spring只支持方法类型的连接点
2、Pointcut(切入点) --- 所谓切入点是指对哪些Joinpoint进行拦截的定义
3、Advice(通知/增强) --- 所谓通知是指拦截到Joinpoint之后所要做的事情就是通知。通知分为前置通知、后置通知、异常通知、最终通知,环绕通知(切面要完成的功能)
4、Introducation(引介) --- 引介是一种特殊的通知在不修改类代码的前提下,Introduction可以在运行期为类动态地添加一些方法或字段
5、Target(目标对象) --- 代理的目标对象
6、Weaving(织入) --- 是指把增强应用到目标对象来创建新的代理对象的过程
7、Proxy(代理) --- 一个类被AOP织入增强后,就产生一个结果代理类
8、Aspect(切面) --- 是切入点和通知的结合,自己来编写和配置的
AspectJ的XML方式完成AOP的开发
步骤一:创建JavaWEB项目,引入具体的开发jar包
* 先引入Spring框架开发的基本开发包
* 再引入Spring框架的AOP的开发包
> Spring的传统AOP的开发包
> AspectJ的开发包
步骤二:创建Spring的配置文件,引入具体的AOP的schema约束
<?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">
</beans>
步骤三:创建包结构,编写具体的接口和实现类
* com.jadan.demo3
> CustomerDao --- 接口
> CustomerDaoImpl --- 实现类
public interface UserDao {
public void save();
public void update();
}
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("保存客户...");
}
public void update() {
System.out.println("修改客户...");
}
}
步骤四:将目标类配置到Spring中
<bean id="customerDao" class="com.jadan.demo3.CustomerDaoImpl"></bean>
步骤五:定义切面类
/**
* 切面类: 切入点 + 通知
*/
public class MyAspectXml {
/**
* 通知(具体的增强)
*/
public void log() {
System.out.println("记录日志...");
}
}
步骤六:在配置文件中定义切面类
<bean id="myAspectXml" class="com.jadan.demo3.MyAspectXml"></bean>
步骤七:在配置文件中完成AOP的配置
<!-- 配置AOP -->
<aop:config>
<aop:aspect ref="myAspectXml">
<!-- 配置通知 -->
<aop:after method="log" pointcut="execution(public void com.jadan.demo3.CustomerDaoImpl.save())"/>
</aop:aspect>
</aop:config>
步骤八:测试
/**
* 测试AOP功能
* @author Administrator
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext3.xml")
public class Demo3 {
@Resource(name="customerDao")
private CustomerDao customerDao;
@Test
public void run1() {
customerDao.save();
customerDao.update();
}
}