spring简笔(三)

一、spring中基于xml的AOP配置

1、把通知bean也交给spring管理

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>        

2、使用aop:config标签标明开始AOP配置

<aop:config></aop:config>

3、实用aoc:aspect标签标明配置切面

  • id:给前面提供一个唯一标识
  • ref:制定通知类bean的id
<aop:aspect id="logAdvice" ref="logger">

4、在aop:aspect标签内部使用对应标签 来配置通知类型

  • aop:before:前置通知,在切入点方法执行之前执行
    • method属性:用于指定Logger类中哪一个方法是前置通知
    • pointcut属性:用于指定切入点表达式,含义是指对业务层中的哪些方法增强
<aop:before method="printLog" pointcut="execution(* *..*.*(..))"></aop:before>
  • aop:after-returning:后置通知,在切入点方法执行之后执行,和异常通知只能执行其一
<aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>
  • aop:after-throwing:异常通知,在切入点方法执行产生异常执行,和异常通知只能执行其一
<aop:after-throwing method="afterThrowingPointLog" pointcut-ref="pt1"></aop:after-throwing>
  • aop:after:最终通知,无论切入点方法是否异常都在其后执行
<aop:after method="afterPringLog" pointcut-ref="pt1"></aop:after>

  • aop:pointcut:配置切入点表达式,此标签在aop:aspect标签内只能当前切面使用
    此标签在aop:aspect标签外所有切面可用,但必须满足约束要求,在aop:aspect标签最前面
    • id属性:用于指定表达式的唯一标识
    • expression:指定表达式内容
<aop:pointcut id="pt1" expression=" execution(* *..*.*(..))"></aop:pointcut>
  • aop:around:环绕通知,它是spring框架提供的一种可以在代码中手动增强方法何时执行的方式不提供方法参数无法执行切入点方法
    spring框架提供了一个接口:ProceedingJoinPoint,该接口有一个方法proceed(),此方法相当于明确调用切入点方法,该接口可作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供接口的实现类供我们使用
<aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>

5、切入点表达式的写法:

  • 关键字:execution(表达式)
    访问修饰符 返回值 包名.包名…类名.方法名(参数列表)
  • 全通配写法:
 execution(* *..*.*(..))

访问修饰符可以省略,返回值可以使用通配符,表示任意返回值
包名可以使用通配符,表示任意包,但有几级包就需要几个包
可以使用..表示当前包及其子包,类名和方法名都可以使用星号通配
参数列表可以直接写数据类型:基本类型直接写名称,引用类型写包名.类名的方式
可以使用通配符表示任意类型,但必须有参数
可以使用..表示有无参数均可,有参数是任意类型
实际开发切入点表达式通常写法:切到业务层实现类下的所有方法

二、spring中基于注解的AOP配置

1、配置spring开启注解AOP的支持

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

2、

  • @Component(“通知类类名”)
    @Aspect//表示当前类是一个切面类

3、

@Pointcut("execution(*  execution(* *..*.*(..))")
private void pt1(){}

4、基于这四种方式的注解会出现执行顺序问题,慎用

@Before("pt1()")
@AfterReturning("pt1()")
@AfterThrowing("pt1()")
@After("pt1()")

5、基于环绕通知的注解,不会出现顺序问题,因为方法是我们自己写的

@Around("pt1()")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值