一起来学Spring
本文主要写了Spring中AOP的一些常用配置
Spring中基于XML的AOP配置
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
- 把通知Bean交给Spring管理
- 使用aop:config标签表明AOP的配置
- 使用aop:aspect标签表明开始配置切面
<aop:config>
<!--配置切面-->
<aop:aspect id="指定唯一标识" ref="引用的Bean">
<!-- 通知类型配置 -->
</aop:aspect>
</aop:config>
- 在aop:aspect标签的内部使用对应标签来配置通知的类型
- 前置通知标签:aop:before
- 执行时机:在切入点方法之前执行
- 属性:
method:指定通知类中哪个类是前置通知
pointcut:指定切入点表达式,该表达式的含义指的是对业务中的哪些方法进行增强
pointcut-ref:引用切入点表达式
- 后置通知标签:aop:after-returning
- 执行时机:在切入点方法正常执行之后执行
- 属性:同上
- 异常通知标签:aop:after-throwing
- 执行时机:在切入点方法执行产生异常后执行
- 属性:同上
- 最终通知标签:aop:after
- 执行时机:不受切入点方法是否异常执行,最后一定会执行
- 属性:同上
- 环绕通知标签:aop:around
- 用途:使用了该标签可以在类中写通知。
- 属性:method:使用环绕通知的方法 pointcut:要增强的方法
- 切入点表达式标签:aop:pointcut
- 执行时机:给配置了pointcut-ref属性的通知标签使用
- 属性:
id:指定表达式的唯一标识
expression:表达式内容 - 作用位置:
配置在aop:aspect标签内只能在此标签内使用
配置在aop:config标签下,则所有的aop:aspect标签都可以使用。注意:必须配置在aop:config标签下的最前面,因为这是约束规定的。
- 切入点表达式的写法:
- 关键字:execution(表达式)
- 表达式语法:访问修饰符 返回值 包名.包名…类名.方法名(参数列表)
<aop:before method="printLog" pointcut="execution(public void com.saykuray.service.impl.AccountServiceImpl.deleteccount(int))"></aop:before>
- 通配符写法(*): ε=ε=ε=ε=ε=ε=┌(; ̄◇ ̄)┘可偷懒,慎用,需细心
- 使用通配符写法需要导入aspectjweaver包
- 访问修饰符可以省略不写
- 返回值可用使用通配符,表示任意返回值
- 包名可以使用通配符,表示任意包。注意:有几级包就要写几次通配符。可以使用*…来表示当前包及其子包
- 类名和方法名可以使用通配符
- 参数列表(可使用通配符表示任意类型,但是必须有参数,一个*代表一个参数。或者使用…来表示有无参数都可以,和表示任意参数)
- 基本类型直接写名称,如int,double,等
- 引用类型写包名+类名的方式,如java.lang.String
// 上面的表达式可以写成如下
"execution(* com.saykuray.service.impl.*.*(..))"注解
Spring中基于注解的AOP配置
- 需要导入的XML约束 及准备
<?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
</beans>
<!-- 扫描包 -->
<context:component-scan base-package="com.saykuray"></context:component-scan>
<!-- 使用AOP注解 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
- 相关的注解
- @EnableAspectAutoProxy:告诉配置类使用切面自动代理
- @Component(“指定Bean的唯一标识”)
- @Aspect:表示当前被注解的类是一个切面类,一般和@Component配合使用
- @Pointcut
- 作用位置:方法
- 参数:value:execution 表达式
- @Before:
- 作用位置:方法
- 参数:要增强的方法
- @AfterReturning:同上
- @AfterThrowing:同上
- @After:同上
- @Around:环绕通知
- 作用位置:方法
- 参数:要增强的方法