AOP

AOP(面向切面编程)*超级重点

06af8cf39d6ec44d0d79d553827f0764

image-20260320134613568

引用狂神说Spring07:AOP就这么简单 (qq.com)

  1. 什么是AOP

    AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。image-20260320164546912

  2. AOP的用例

    • 使用Spring的API接口

      <!--配置aop-->
              <aop:config>
      <!--切入点:expression:表达式,execution(要执行的位置: * * * * *)修饰词 返回值  类名 方法名 参数-->
                  <aop:pointcut id="pointcut" expression="execution(* com.wjj.service.UserServiceImpl.*(..))"/>
                  <aop:advisor advice-ref="after" pointcut-ref="pointcut"/>
                  <aop:advisor advice-ref="before" pointcut-ref="pointcut"/>
              </aop:config>
      
    • 自定义来实现AOP

              <bean id="diy" class="com.wjj.diy.DiyPointcut" />
      
          <aop:config>
      <!--        自定义切面,ref映入类-->
              <aop:aspect ref="diy">
      <!--            切入点-->
                  <aop:pointcut id="pointcut" expression="execution(* com.wjj.diy.DiyPointcut.*(..))"/>
      <!--            通知-->
                  <aop:before method="before" pointcut-ref="pointcut"/>
                  <aop:after method="after" pointcut-ref="pointcut"/>
              </aop:aspect>
          </aop:config>
      
  3. 注解实现AOP

public class AnnotationPinot {
    @Before("execution(* com.wjj.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("Before============");
    }
    @After("execution(* com.wjj.service.UserServiceImpl.*(..) )")
    public void after() {
        System.out.println("================后");
    }
    @Around("execution(* com.wjj.service.UserServiceImpl.*(..) )")
    public void around(ProceedingJoinPoint pjp)  throws Throwable {
        System.out.println("环绕前");
        Object proceed = pjp.proceed();

        System.out.println("环绕后");
    }
<!-- 开启驱动支持   JDK(默认为 proxy-target-class="false") cglib(proxy-target-class="true" 不写默认为proxy-target-class="false")-->
        <aop:aspectj-autoproxy proxy-target-class="false"/>
<!--  方式三  -->
        <bean id="annotationPinot" class="com.wjj.diy.AnnotationPinot"/>

image-20260320204512257

posted @ 2026-03-20 21:13  三咲肘击王  阅读(38)  评论(0)    收藏  举报