一步步的学习Spring(三)
这节来学习下AOP,常说的面向切面编程,面向切面编程能提取公用的业务组件做为切面,从而减少实际业务代码的工作量,AOP经常分离的几个切面有:日志管理模块,安全管理模块,事务管理模块。
?
下面来看下简单的一个日志记录切面(方法前置和后置通知):
?
先来定义下两个通知:
?
前置通知:
?
?
?
后置通知:
?
?
?
?
来看看通知是怎么实现通知拦截的:
?
?
??
改下xml配置:
?
?
0103/17:37:47 <INFO > [org.springframework.core.CollectionFactory 66] JDK 1.4+ collections available0103/17:37:47 <INFO > [org.springframework.core.CollectionFactory 71] Commons Collections 3.x available0103/17:37:47 <INFO > [org.springframework.beans.factory.xml.XmlBeanDefinitionReader 163] Loading XML bean definitions from file [G:\workspace\SpringStudy\beans.xml]0103/17:37:47 <INFO > [org.springframework.aop.framework.DefaultAopProxyFactory 64] CGLIB2 available: proxyTargetClass feature enabled0103/17:37:47 <INFO > [aop.LogBeforeAdvice 30] ioc.TaskImpl’s say invoked0103/17:37:47 <INFO > [ioc.TaskImpl 32] tt say :汪汪汪0103/17:37:47 <INFO > [aop.LogAfterAdvice 22] ioc.TaskImpl’s say invoked0103/17:37:47 <INFO > [aop.LogAdvice 17] ioc.TaskImpl’s before say invoked0103/17:37:47 <INFO > [ioc.TaskImpl 32] tt say :汪汪汪0103/17:37:47 <INFO > [aop.LogAdvice 19] ioc.TaskImpl’s after say invoked?
?
看效果差不多吧,呵呵
?
这样,我们就能拦截方法的调用了,做一些自己想做的限制或者业务了。比如实现每个用户只能买一个果酱(书上看的喽)
?
?
?
?
?
?
?
?
?
?
?
?