Spring 2.X中AOP的操纵浅析[Java编程]
本文“Spring 2.X中AOP的操纵浅析[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
和Spring1.X相比,Spring2.X利用AspectJ的语法来声明AOP,这使得它更“尺度”,更机动了.还是那句话,假如你不理解AspectJ并且打算利用Spring2.X的AspectJ式AOP,那就学学AspectJ吧,这方面的书还是很多了.
Spring2.X下的切面有两种实现方法,一种是以Java文件定义切面(其只是普通的Java类),然后在配置文件中声明定义的切面;另一种是在Java类中引入和AOP相关的元数据(注释).
先介绍第一种配置方法.需求指出的是,Spring2.X的beans名称空间和Spring1.X有所差别,它采取了Schema而不是DTD(也可采取DTD方法,具体的请参考文档).还是引入毫无意义的日记切面,定义的切面类LogingAspect 以下:
public class LogingAspect {
public void logMethod(JoinPoint jp){
System.err.println(jp.getTarget().getClass());
System.err.println(jp.getSignature().getName());
}
}
同时在配置文件中以下配置:
< bean id = " logAspectTarget " class = " hibernatesample.service.util.LogingAspect " >
</ bean >
< aop:config >
< aop:aspect id = " logAspect " ref = " logAspectTarget " >
< aop:pointcut id = " businessService " expression = " execution(* hibernatesample.service.*.*(..)) " />
< aop:after pointcut - ref = " businessService " method = " logMethod " />
</ aop:aspect >
</ aop:config >
关于上面的切面,切入点businessService是在配置文件中声明的,其表达式采取了 AspectJ的语法,LogingAspect 类中logMethod(JoinPoint jp)办法按照配置文件信息可知其是after告诉,办法的JoinPoint参数不是必须的,它是来自于AspectJ的实用类,这里用它不过输出一些和衔接点有关的信息.当然,在Spring2.X中,切入点和告诉能更机动的利用,我们可以如AspectJ一样传送参数给告诉.假如需求在Service中引入事件功效,需求以下配置事件告诉:
< tx:advice id = " txAdvice " transaction - manager = " transactionManager " >
< tx:attributes >
< tx:method name = " get* " read - only = " true " />
< tx:method name = " find* " read - only = " true " />
< tx:method name = " * " />
</ tx:attributes >
</ tx:advice >
< aop:config >
< aop:pointcut id = " demoServiceMethods " expression = " execution(* hibernatesample.service.*.*(..)) " />
< aop:advisor advice - ref = " txAdvice " pointcut - ref = " demoServiceMethods " />
< aop:aspect id = " logAspect " ref = " logAspectTarget " >
< aop:pointcut id = " businessService " expression = " execution(* hibernatesample.service.*.*(..)) " />
< aop:after pointcut - ref = " businessService " method = " logMethod " />
</ aop:aspect >
</ aop:config >
完成上面的工作相当于完成了 Spring1.X 的 自动代理. 我们接下来需求定义的任何 Service Bean 都可以很纯粹很纯粹了:
< bean id ="accountService" class ="hibernatesample.service.impl.AccountServiceImpl" >
< property name ="accountDAO" ref ="accountDAO" ></ property >
</ bean >
以上是“Spring 2.X中AOP的操纵浅析[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |