---
title: "【spring学习笔记一】AOP简介"
author: "零度弥合"
date: "2014-02-27T18:52:23Z"
tags: []
categories: ["编程语言"]
slug: "spring-aop"
draft: false
lastmod: "2014-02-27T18:20:55Z"
id: 2022445
url: "https://zdr99.iteye.com/blog/2022445"
---

首先罗列一些AOP的概念

**Aspect(切面)**：横切性关注点的抽象即为切面，它与类相似只是两者的关注点不一样，类是对物体特征的抽象，而切面是横切性关注的抽象。

**joinpoint(连接点)**：所谓连接点是指那些被连接到的点，在spring中这些点指的是方法，因为spring只支持方法类型的连接点，实际上joinpoint还可以是field或类的构造器

**pointcut(切入点)**：所谓切入点是指我们要对那些joinpoint进行拦截的定义

**advice(通知)**：拦截到joinpoint之后要做的事情就是通知，通知分为前置通知，后置通知，异常通知，最终通知，环绕通知。

**target(目标对象)**：代理的目标对象

**weave(织入)**：将Aspect应用到target对象并导致proxy对象创建的过程称为织入

**introduction(引入)**：在不修改代码的前提下，introduction可以在运行期为类动态的添加一些方法或field

 

 

**基于代理的AOP实现（基于java反射机制）**

1：创建实现类bean

&lt;bean id="studentDaoImpl" class="dao.impl.StudentDaoImpl"/&gt;

 

2：创建代理类

实现MethodBeforeAdvice AfterRunningAdivce这两个接口

 

3：定义切入点

&lt;bean id="studentDaoPointCut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"&gt;

&lt;property name="pattern" value=".\*Student"/&gt;

&lt;/bean&gt;

pattern指定正则表达式，匹配以Student结尾的方法 

 

4：定义通知

&lt;bean id="studentDaoAdvice" class="org.springframework.aop.support.DefaultPointcutAdvisor"&gt;

&lt;property name="advice" ref="studentDaoProxy"/&gt;

&lt;property name="pointcut" ref="studentDaoPointCut"/&gt;

&lt;/bean&gt;

这里面属性的名字是固定的advice：代理类，pointcut：切入点

 

 5：定义代理工厂 

&lt;bean id="studentProxyFacory" class="org.springframework.aop.framework.ProxyFactoryBean"&gt;

&lt;property name="target" ref="studentDaoImpl"/&gt;

&lt;property name="interceptorNames" ref="studentDaoAdvice"/&gt;

&lt;property name="proxyInterfaces" value="com.mihe.dao.StudentDao"/&gt;

&lt;/bean&gt;

三个property的name也是固定的，分别是目标对象，拦截器，和实现了哪些接口

 

 **自动代理的AOP实现（基于cglib）**

只需要声明通知就可以，注意两个property都是固定的，第一个指向代理类，第二个使用正则表达式匹配目标对象

&lt;bean id="studentDaoAdvice" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"&gt;

&lt;property name="advice" ref="studentDaoProxy" /&gt;

&lt;property name="pattern" value=".\*Student" /&gt;

&lt;/bean&gt;

需声明支持自动代理

&lt;bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/&gt;

 

 AspectJ的AOP实现(基于注解)

1：增加xml支持

http://www.srpingframework.org/schema/aop

http://www.srpingframework.org/schema/aop/spring-aop-2.5.xsd

2：自动扫面注解和声明使用AspectJ自动代理

&lt;context:annotation-config/&gt;

&lt;context:component-scan base-package="com.mihe"/&gt;

&lt;aop:aspectj-autoproxy/&gt;

3：编写切面类

@Aspect//声明为切面

@Component//声明为组件

 在方法上加

@Before(value = "execution(public void com.mihe.dao.impl.StudentDaoImpl.\*Student())")

表示StudentDaoImpl类中的所有以Student结尾的方法