【spring学习笔记一】AOP简介

首先罗列一些AOP的概念

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

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

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

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

target(目标对象):代理的目标对象

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

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

 

 

基于代理的AOP实现(基于java反射机制)

1:创建实现类bean

<bean id="studentDaoImpl" class="dao.impl.StudentDaoImpl"/>

 

2:创建代理类

实现MethodBeforeAdvice AfterRunningAdivce这两个接口

 

3:定义切入点

<bean id="studentDaoPointCut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">

<property name="pattern" value=".*Student"/>

</bean>

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

 

4:定义通知

<bean id="studentDaoAdvice" class="org.springframework.aop.support.DefaultPointcutAdvisor">

<property name="advice" ref="studentDaoProxy"/>

<property name="pointcut" ref="studentDaoPointCut"/>

</bean>

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

 

 5:定义代理工厂 

<bean id="studentProxyFacory" class="org.springframework.aop.framework.ProxyFactoryBean">

<property name="target" ref="studentDaoImpl"/>

<property name="interceptorNames" ref="studentDaoAdvice"/>

<property name="proxyInterfaces" value="com.mihe.dao.StudentDao"/>

</bean>

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

 

 自动代理的AOP实现(基于cglib)

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

<bean id="studentDaoAdvice" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">

<property name="advice" ref="studentDaoProxy" />

<property name="pattern" value=".*Student" />

</bean>

需声明支持自动代理

<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>

 

 AspectJ的AOP实现(基于注解)

1:增加xml支持

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

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

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

<context:annotation-config/>

<context:component-scan base-package="com.mihe"/>

<aop:aspectj-autoproxy/>

3:编写切面类

@Aspect//声明为切面

@Component//声明为组件

 在方法上加

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

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值