用途:
为接口的实现类提供解耦合的功能,如日志功能,事务功能,安全功能;其功能跟拦截器相似,但是spring 只能提供对方法的拦截:我们将来主要遇到的是面向接口的编程,所以要掌握spring推荐的动态代理模式了,其实springj就是通过bean配置或者JAVA的注释来实现关注类的功能的增加了。
原理自解:
一般就是拦截一个类(关注类)的对象在其方法在被调用的某个时机,插入其他类(通知类)的方法的运行,从表面上看就是关注类增加了一些方法和功能。
好处:
解耦合,没有破坏对象的封装性,提高对象的可重用性
一般构成:
1.接口:
2.接口的实现类:(主要专注类)
3.实现spring 的xxxxxadivce接口-------增加功能的类(通知类)
4.beans-config.xml文件(利用spring Ioc ,spring 提供的类来注入代理对象)
两种代理:
JDK动态代理:使用接口于实现分离,面向接口编程是spring推荐的方式。
CGLIB代理: 主要适用于改造遗留系统,这些系统一般不会继承特定的接口
三种实现的配置来实现:
1. bean配置:
<beans>
<bean id="aaaTargetObject" class="AAA"/> // 目标类 , 这是一个实现某个接口的类
<bean id="welcomeAdvice" class="WelcomeAdvice"/> // 通知类
<bean id="proxyobject" //要调用的代理对象
class="org.springframework.aop.framework.proxyFactoryBean">
<property name=”proxyInterfaces” value=”IAAA”/>
<property name="interceptorNames">
<list>
<value>welcomAdvice</value>
</list>
</property>
<property name="target">
<ref bean="aaaTargetObject"/>
</property>
</bean>
</beans>
2. 基于Annotation
@aspect --------加在通知类的外面
下面要根据需求来选择其中的若干个用来通知类内部的要增加的功能的方法的上面
@Around(“execution(* xx.xx.IHello.*(..))”)
@After(“execution(* xx.xx.IHello.*(..))”)
@Before(“execution(* xx.xx.IHello.*(..))”)
@Thorws(“execution(* xx.xx.IHello.*(..))”)
3. 基于XML schema
// pointcut 切入点 (id
//aspect 切面(包含通知的方式,切点的引用,增加的功能的方法名字)
<aop: config>
<aop:pointcut id=” ” expression=”execution(* )”/>
<aop:aspect id=” ” ref=” ”>
<aop:before pointcut-ref=” ” method=” ”/>
</aop:aspect>
</aop:config>
四种通知: 通知类要实现的spring提供的接口并要实现其中的方法。
1 Around org.aopalliance.intercept.MethodInterceptor 栏截对目标对象方法的调用
2 Before org.springframework.aop.MethodBeforAdvice 在目标方法被调用之前调用
3 After org.springframework.aop.AfterReturningAdvice 当目标方法被调用之后调用
4 Thorws org.springframework.aop.ThrowsAdvice 当目标方法抛出异常时调用
Spring aop 讨论
最新推荐文章于 2024-07-24 14:18:45 发布