基于XML配置的AOP

    xiaoxiao2024-12-15  65

    AOP的基本操作 先引入jar包 :spring-context aspectjweaver 1.把通知Bean交给spring管理 2.使用aop:config标签表明开始aop配置 3.使用aop:aspect标签表明配置切面 (1)id属性为切面提供一个唯一表示 (2)ref属性来指向通知类bean的id 在aop:aspect标签内 使用aop:before表示前置通知(相应aop:after指定后置通知) (1) method属性表明该类哪个方法是前置通知 (2)pointcut属性指定切入点表达式,该表达式用来指定对哪个方法进行增强 aop:pointcut标签可用来指定方法,这样 具体的切面指定的时候直接引用aop:pointcut标签中的id即可 切入点表示式: 关键字 execution(表达式) 表达式:修饰符 返回类型 方法路径 (public void com.qst.service.impl.AccountService.saveAccount) 补充: 访问修饰符可以省略 返回值可以使用通配符*,表示任意返回值 包名也可使用通配符*,表示任意包,有几个包就需要写几个*. 包名可以使用.. 表示当前包及其子包 类名和包名都可以使用*来实现通配 *() 方法的参数列表 可以指定 基本类型直接写名称 引用类型包名.类名 java.lang.String 这里的*表示所有带参数的 如果想用无参的用(..) public void com.qst.service.impl.AccountService.saveAccount() 全通配写法 * *..*.*(..) <!--把service放入IOC容器中--> <bean id="accountService" class="com.qst.service.impl.AccountService"></bean> <!--把logger类放入IOC容器中--> <bean id="logger" class="com.qst.utils.Logger"></bean> <!--配置AOP--> <aop:config> <!--配置切面指定类--> <aop:aspect id="logAdvice" ref="logger"> <!--配置切面指定类的方法及要切入的类的方法(切入点)--> <aop:before method="beforelog" pointcut-ref="pt1"></aop:before> <aop:pointcut id="pt1" expression="execution(public void com.qst.service.impl.AccountService.*(..))"></aop:pointcut> </aop:aspect> </aop:config> </beans>

    四种常用的通知类型

     

    前置通知aop:before 指定切入点之前执行 后置通知aop:after-returning指定切入点之后执行 异常通知aop:after-throwing指定切入方法异常时执行 最终通知aop:after不管有无异常都必须执行 <!--配置AOP--> <aop:config> <!--配置切面指定类--> <aop:aspect id="logAdvice" ref="logger"> <!--配置切面指定类的方法及要切入的类的方法(切入点)--> <aop:before method="beforelog" pointcut-ref="pt1"></aop:before> <aop:after method="afterlog" pointcut-ref="pt1"></aop:after> <aop:after-returning method="afterReturnlog" pointcut-ref="pt1"></aop:after-returning> <aop:after-throwing method="throwtlog" pointcut-ref="pt1"></aop:after-throwing> <aop:pointcut id="pt1" expression="execution(public void com.qst.service.impl.AccountService.*(..))"></aop:pointcut> </aop:aspect> </aop:config>

     

    环绕通知

    最新回复(0)