spring Aop

来源:互联网 发布:mac os 照片 存放位置 编辑:程序博客网 时间:2024/06/04 18:40

前面一篇文章讲到了 annotation+aop完成日志记录。这篇文章主要讲解aop的用法。例如我想为login动作增强下,在login动作执行之前和之后都输出一下。

1 首先新建一个方法login方法:

@RequestMapping("loginIn")public String loginIn(){DataSourceUtils ds = (DataSourceUtils)ApplicationContextUtils.getBean("DataSourceUtilsBean");System.out.println(ds.getDataSource().getActiveCount());return "index/index";}

2 为login方法创建一个切面

@Aspect//标注切面类@Componentpublic class TestAspect {/** * 注册切入点 (login方法) */@Pointcut("execution(* *.loginIn())")public void loginInPointCut(){}//一些常见的切入点的例子 //execution(public * * (. .)) 任意公共方法被执行时,执行切入点函数。 //execution( * set* (. .)) 任何以一个“set”开始的方法被执行时,执行切入点函数。 //execution( * com.demo.service.AccountService.* (. .)) 当接口AccountService 中的任意方法被执行时,执行切入点函数。 //execution( * com.demo.service.. (. .)) 当service 包中的任意方法被执行时,执行切入点函数。 //within(com.demo.service.) 在service 包里的任意连接点。 //within(com.demo.service. .) 在service 包或子包的任意连接点。 //this(com.demo.service.AccountService) 实现了AccountService 接口的代理对象的任意连接点。 //target(com.demo.service.AccountService) 实现了AccountService 接口的目标对象的任意连接点。 //args(Java.io.Serializable) 任何一个只接受一个参数,且在运行时传入参数实现了 Serializable 接口的连接点 @Before(value = "loginInPointCut()")public void before(){System.out.println("before loginInPointCut()");}@AfterReturning(value = "loginInPointCut()")public void afterReturning(){System.out.println("afterReturning loginInPointCut()");}@AfterThrowing(value = "loginInPointCut()")public void afterThrowing(){System.out.println("afterThrowing loginInPointCut()");}//增强的方式: //@Before:方法前执行 //@AfterReturning:运行方法后执行 //@AfterThrowing:Throw后执行 //@After:无论方法以何种方式结束,都会执行(类似于finally) //@Around:环绕执行}

3  在spring-mvc.xml文件中配置@Aspect切面的扫描

<!-- 有了这个Spring就能够自动扫描被@Aspect标注的切面了 --><aop:aspectj-autoproxy proxy-target-class="true" />
需要注意的是需要将 下面三句代码 粘贴到 <beans > 标签中

xmlns:aop="http://www.springframework.org/schema/aop"

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

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd