AOP
AOP(Aspect Oriented Programing),面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,利用AOP可以对业务逻辑的各个部分进行隔离,从而使业务逻辑各部分之间的耦合降低,提高程序的可重用性。
1、Aop在Spring中的作用
==提供声明式事务;允许用户自定义切面==
- 横切关注点:跨越应用程序多个模块的方法或功能,即:与业务逻辑无关,但需要关注的部分就是横切关注点,如:日志、缓存、事务等
- 切面(Aspect):横切关注点被模块化的都特殊对象,具体为一个类
- 通知(Advice):切面必须要完成的工作,类中的一个方法
- 目标(Target):被通知对象
- 代理(Proxy):向目标对象应用通知之后创建的对象
- 切入点(PointCut):需要执行切面通知的”地点“
- 连接点(JoinPoint):与切入点匹配的执行点
在SpringAop中,通过Advice定义横切逻辑,Spring中支持5中类型的Advice:
通知类型 | 连接点 | 实现接口 |
---|---|---|
前置通知 | 方法前 | org.springframework.aop.MethodBeforeAdvice |
后置通知 | 方法后 | org.springframework.aop.AfterReturningAdvice |
环绕通知 | 方法前后 | org.springframework.aop.MethodInterceptor |
异常抛出通知 | 方法抛出异常 | org.springframework.aop.ThrowsAdvice |
引介通知 | 类中增加新的方法属性 | org.springframework.aop.IntroductionInterceptor |
2、使用Spring实现AOP
在pom.xml中导入依赖
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
3、使用Spring实现Aop
方式一:使用Spring的API接口
方式二:自定义实现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">
<!--注册bean-->
<bean id="userService" class="com.sw.service.UserServiceImpl"/>
<bean id="log" class="com.sw.log.Log"/>
<bean id="afterLog" class="com.sw.log.AfterLog"/>
<!--方式一:使用原生Spring API配置-->
<!--配置aop:需导入AOP约束-->
<aop:config>
<!--切入点:execution(要执行的位置)-->
<aop:pointcut id="pointcut" expression="execution(* com.sw.service.UserServiceImpl.*(..))"/>
<!--执行环绕增强-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
<!--方式二:自定义-->
<bean id="diy" class="com.sw.diy.DiyLog"/>
<aop:config>
<!--自定义切面,ref:要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.sw.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
<!--方式三:通过注解-->
<bean id="annotationPointCut" class="com.sw.diy.AnnotationPointCut"/>
<!--开启注解
JDK:expose-proxy="false"(默认)
cglib:expose-proxy="true"
-->
<aop:aspectj-autoproxy />
</beans>
评论 (0)