标签:after nts intercept ram com 类型 tor odi print
之前在另外一篇博文里介绍过AOP的概念, 这边不在赘述, 可以参考 AOP与动态代理
本文主要介绍Spring中AOP的应用.
切入点: 具体实现类的方法
连接点: 接口中的方法
1 public class MyServiceBeforeAdvice implements MethodBeforeAdvice{ 2 @Override 3 public void before(Method method, Object[] args, Object target) throws Throwable { 4 System.out.println("MyServiceBeforeAdvice"); 5 } 6 } 7 8 public class MyServiceAfterService implements AfterReturningAdvice{ 9 @Override 10 public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { 11 System.out.println("MyServiceAfterService"); 12 } 13 } 14 15 16 public class MyMethodInterceptor implements MethodInterceptor{ 17 @Override 18 public Object invoke(MethodInvocation invocation) throws Throwable { 19 System.out.println("before"); 20 Object result = invocation.proceed(); 21 System.out.println("after"); 22 return result; 23 } 24 }
对应的xml写法
1 <bean id="someService" class="day1207.ServiceImpl"/> 2 3 <bean id="myAdvice" class="day1207.MyServiceBeforeAdvice"/> 4 <bean id="myAdvice2" class="day1207.MyServiceAfterService"/> 5 <bean id="myAdvice3" class="day1207.MyMethodInterceptor"/> 6 7 <bean id="serviceProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> 8 <property name="target" ref="someService"/> 9 <property name="interceptorNames" value="myAdvice, myAdvice2, myAdvice3"/> 10 </bean>
Spring中默认有接口的对象直接用的jdk动态代理实现的AOP, 无接口的对象用CGlib实现的.
如果想要强制都用CGlib实现, 则可以通过以下配置
1 <property name="optimize" value="true"/>
或者
1 <property name="proxyTargetClass" value="true"/>
PointcutAdvisor: 可以指定具体切入点位置.
NameMatchMethodPointcutAdvisor 名称匹配
1 <bean id="myAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor"> 2 <property name="advice" ref="myAdvice2"/> 3 <!-- 匹配对象是简单方法名 --> 4 <property name="mappedNames" value="doFirst, doSecond"/> 5 </bean>
RegexpMethodPointcutAdvisor 正则匹配
1 <bean id="myAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> 2 <property name="advice" ref="myAdvice2"/> 3 <!--匹配全限定性方法路径--> 4 <property name="pattern" value=".*S.*"/> 5 </bean>
用于解决多个Bean需要对应多个代理的问题.
Advisor代理生成器
1 <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
缺点: 范围太广, 无法指定差异化Bean处理, 不能选择切面类型, 只能Advisor. 内部实现是用的BeanPostProcessor.
Bean名称自动代理生成器
1 <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> 2 <property name="beanNames" value="someService"/> 3 <property name="interceptorNames" value="myAdvisor"/> 4 </bean>
标签:after nts intercept ram com 类型 tor odi print
原文地址:http://www.cnblogs.com/xdecode/p/8001522.html