aop实践实现spring aop有三种方式,aop schema,也就是基于xml的配置;基于@AspectJ注解的实现;基于bean proxy creator的实现,现在分别讲解
由javacoder.cn整理,转载请注明出处,附件test_spring_aop.zip:
一、测试工程介绍
demo工程见附件,主要功能是统计@TimeElapse标注的方法的耗时。
二、基于xml的配置
1 2 3 4 5 6 7 8 9 |
<bean id="test" class="cn.javacoder.test_spring_aop.TestServiceImpl"></bean> <bean id="TimeElapseRecordingAdvice" class="cn.javacoder.test_spring_aop.TimeElapseRecordingAdvice"></bean> <!-- using schema--> <aop:config> <aop:aspect ref="TimeElapseRecordingAdvice"> <aop:pointcut id = "performance2" expression="@annotation(cn.javacoder.test_spring_aop.TimeElapse)" /> <aop:around pointcut-ref="performance2" method="recordTimeElapsed" /> </aop:aspect> </aop:config> |
三、基于@AspectJ注解的实现
1 2 3 4 5 |
<aop:aspectj-autoproxy/> <bean id="test" class="cn.javacoder.test_spring_aop.TestServiceImpl"> </bean> <bean id="TimeElapseRecordingAdvice" class="cn.javacoder.test_spring_aop.TimeElapseRecordingAdvice"> </bean> |
在TimeElapseRecordingAdvice类中
1 2 3 4 5 6 7 8 9 |
@Aspect public class TimeElapseRecordingAdvice implements MethodInterceptor { @Pointcut("@annotation(cn.javacoder.test_spring_aop.TimeElapse)") public void pointcut(){ } @Around("pointcut()") public void recordTimeElapsed(ProceedingJoinPoint joinpoint) throws IOException { //具体实现见代码 } } |
在类上添加了@Aspect标注,添加了一个使用@Pointcut标注的空方法来定义point cut, 在recordTimeElapsed方法上添加了@Around标注
四、基于bean proxy creator的实现
声明的DefaultAdvisorAutoProxyCreator bean会扫描同一个上下文(applicationContext)中所有的Advisor定义,为pointcut表达式配置的类产生aop代理配置如下
1 2 3 4 5 6 7 8 |
<bean id="test" class="cn.javacoder.test_spring_aop.TestServiceImpl"></bean> <bean id="TimeElapseRecordingAdvice" class="cn.javacoder.test_spring_aop.TimeElapseRecordingAdvice"></bean> <!-- using bean proxy --> <bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" /> <bean id="methodCallTimeElapseAdvisor" class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor"> <property name="advice" ref="TimeElapseRecordingAdvice"/> <property name="expression"> <value><![CDATA[@annotation(cn.javacoder.test_spring_aop.TimeElapse)]]></value> </property> </bean> |
TimeElapseRecordingAdvice类实现MethodInterceptor接口
1 2 3 4 5 |
public class TimeElapseRecordingAdvice implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { //实现和前面的recordTimeElapsed基本一致,除了获取被调用方法的是否不一样而已 } } |
Posted in: spring practise
Comments are closed.