AOP

什么是AOP

面向切面编程,通过预编译方式和运行期动态代理,实现程序功能的统一维护的一种技术

AOP在spring中的作用

提供声明式事务;允许用户自定义切面

使用spring实现AOP

【重点】使用AOP,需要导入一个依赖包

<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

方式一:使用spring的API接口 【主要spring API接口实现】

<!--方式一:使用原生spring API接口-->
<!--配置aop:需要导入AOP的约束-->
    <aop:config>
<!--切入点:   expression:表达式,execution(要执行的位置)-->
        <aop:pointcut id="pointcut" expression="execution(* com.god.service.UserServiceImpl.*(..))"/>

<!--执行环绕增强-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
    </aop:config>

execution(<修饰符模式>? <返回类型模式> <方法名模式>(<参数模式>) <异常模式>?)

  • execution(): 表达式的主体。
  • 第一个 * 号: 表示返回类型,* 号表示所有的类型。
  • 包名: 表示需要拦截的包名,后面的两个句点表示当前包和当前包的所有子包。
  • 第二个 * 号: 表示类名,* 号表示所有的类。
  • (..): 最后这个星号表示方法名, 号表示所有的方法,后面括弧里面表示方法的参数,两个句点表示任何参数。

方式二:自定义类实现AOP【主要是切面定义】

<!--方式二:自定义类-->
    <bean id="diy" class="com.god.diy.DiyPointCut"/>
    <aop:config>
<!-- 自定义切面,ref要引用的类-->
        <aop:aspect ref="diy">
<!--切入点-->
            <aop:pointcut id="pointcut" expression="execution(* com.god.service.UserServiceImpl.*(..))"/>
<!--通知-->
            <aop:before method="before" pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

方式三:使用注解实现

//使用注解方式实现AOP
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.god.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("===方==法=执=行==器===");
    }
    @After("execution(* com.god.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("===方==法=执=行==后===");
    }
    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        //执行方法
        Object proceed = jp.proceed();
        System.out.println("环绕后");
    }
}
<!--方式三:注解-->
    <bean id="annotationPointCut" class="com.god.diy.AnnotationPointCut"/>
<!--开启注解支持-->
    <aop:aspectj-autoproxy/>
posted @ 2026-02-22 16:15  Dominus  阅读(1)  评论(0)    收藏  举报