spring 环绕通知怎么用

fiy 其他 65

回复

共3条回复 我来回复
  • worktile的头像
    worktile
    Worktile官方账号
    评论

    使用Spring的环绕通知可以在目标方法的前后插入自定义的逻辑,对方法进行增强处理。下面我将介绍环绕通知的使用步骤:

    1. 创建一个切面类,该类需要实现MethodInterceptor接口,并重写invoke方法。在invoke方法中编写前置逻辑、调用目标方法以及后置逻辑。
    import org.aopalliance.intercept.MethodInterceptor;
    import org.aopalliance.intercept.MethodInvocation;
    
    public class AroundAdvice implements MethodInterceptor {
        
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            // 前置逻辑
            System.out.println("前置逻辑");
            
            // 调用目标方法
            Object result = invocation.proceed();
            
            // 后置逻辑
            System.out.println("后置逻辑");
            
            return result;
        }
    }
    
    1. 配置切面类,在Spring配置文件中使用aop:config元素进行切面配置。在aop:config元素内部使用aop:aspect元素定义切面,并使用aop:around元素配置环绕通知。
    <aop:config>
        <aop:aspect ref="aroundAdvice">
            <aop:around method="invoke" pointcut="execution(* com.example.service.*.*(..))"/>
        </aop:aspect>
    </aop:config>
    
    1. 将切面类实例化并注入到Spring容器中。
    <bean id="aroundAdvice" class="com.example.aspect.AroundAdvice"/>
    
    1. 在需要使用环绕通知的类或方法上加上切入点表达式,以告诉Spring在何处切入。
    package com.example.service;
    
    public class UserService {
        
        public void addUser(String name) {
            System.out.println("添加用户:" + name);
        }
    }
    
    <aop:config>
        <aop:aspect ref="aroundAdvice">
            <aop:around method="invoke" pointcut="execution(* com.example.service.UserService.addUser(..))"/>
        </aop:aspect>
    </aop:config>
    

    通过以上步骤,就可以使用Spring的环绕通知来对方法进行增强处理了。在目标方法执行之前和之后,可以插入自定义的逻辑。

    1年前 0条评论
  • fiy的头像
    fiy
    Worktile&PingCode市场小伙伴
    评论

    Spring的环绕通知是一种AOP(面向切面编程)中的通知类型,它可以在目标方法的前后执行额外的逻辑。使用环绕通知可以灵活地控制方法的执行,并且可以获取方法的返回结果。

    要使用Spring的环绕通知,需要按照以下步骤进行操作:

    1. 配置AOP切面:首先,在Spring的配置文件中配置AOP切面,定义切点和通知类型。可以使用XML配置文件或者使用注解方式。

    2. 实现通知逻辑:创建一个通知类,实现org.aspectj.lang.ProceedingJoinPoint接口,并在类中编写通知逻辑。在通知逻辑中,可以编写在目标方法执行前、执行后以及异常发生时的额外逻辑。

    3. 注入切面和目标类:在Spring的配置文件中,通过<aop:aspect>标签将切面和目标类进行关联,并将切面类和目标类进行注入。

    4. 测试:编写测试类,使用Spring的IoC容器获取目标类的实例,并调用目标方法,观察环绕通知的执行情况。

    下面是一个示例代码,演示了如何使用Spring的环绕通知:

    // 1.配置AOP切面
    @Aspect
    @Component
    public class LoggingAspect {
    
        @Around("execution(* com.example.sample.SampleClass.sampleMethod(..))")
        public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
            System.out.println("Before method execution");
    
            Object result = null;
            try {
                // 在目标方法执行前执行的逻辑
                result = joinPoint.proceed();
                // 在目标方法执行后执行的逻辑
                System.out.println("After method execution");
            } catch (Exception e) {
                // 在异常发生时执行的逻辑
                System.out.println("Exception occurred: " + e.getMessage());
            }
    
            return result;
        }
    }
    
    // 2.目标类
    @Component
    public class SampleClass {
    
        public void sampleMethod() {
            System.out.println("Executing sampleMethod");
        }
    }
    
    // 3.配置文件
    @Configuration
    @ComponentScan(basePackages = "com.example.sample")
    @EnableAspectJAutoProxy
    public class AppConfig {
    
    }
    
    // 4.测试类
    public class Main {
        public static void main(String[] args) {
            ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
            SampleClass sampleClass = context.getBean(SampleClass.class);
            sampleClass.sampleMethod();
            context.close();
        }
    }
    

    以上示例代码中,LoggingAspect是一个切面类,使用@Aspect注解标注,并在类中定义了aroundAdvice方法,该方法是环绕通知的实现逻辑。SampleClass是一个目标类,用于演示环绕通知的使用。AppConfig是Spring的配置类,配置了AOP切面和目标类的扫描。在Main测试类中,使用AnnotationConfigApplicationContext获取Spring的IoC容器,并从容器中获取目标类的实例,并调用目标方法。在控制台输出中,可以观察到环绕通知的执行结果。

    1年前 0条评论
  • 不及物动词的头像
    不及物动词
    这个人很懒,什么都没有留下~
    评论

    Spring环绕通知是一种AOP(面向切面编程)的技术,它允许我们在方法的前后添加自定义的逻辑。在Spring框架中,我们可以使用注解或XML配置来使用环绕通知。

    下面是使用注解和XML配置的示例:

    1. 使用注解配置环绕通知
      首先,在你的Spring配置文件中启用注解配置:
    <!-- 启用注解配置 -->
    <context:annotation-config />
    

    接下来,创建一个切面类,该类使用注解来定义环绕通知。示例代码如下所示:

    @Aspect
    @Component
    public class LoggingAspect {
       @Around("execution(* com.example.myapp.MyService.*(..))")
       public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
           // 在方法执行之前添加自定义逻辑
           System.out.println("Before method execution");
           
           // 执行目标方法
           Object result = joinPoint.proceed();
           
           // 在方法执行之后添加自定义逻辑
           System.out.println("After method execution");
           
           return result;
       }
    }
    

    在上面的代码中,@Aspect注解标识这是一个切面类,@Around注解标识这是一个环绕通知。括号中的表达式execution(* com.example.myapp.MyService.*(..))表示匹配com.example.myapp.MyService类中的所有方法。

    1. 使用XML配置环绕通知
      首先,在你的Spring配置文件中添加AOP命名空间:
    <!-- 添加AOP命名空间 -->
    <beans xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
        <!-- ...其他配置... -->
    </beans>
    

    然后,在Spring配置文件中配置切面和环绕通知:

    <bean id="loggingAspect" class="com.example.myapp.LoggingAspect"/>
    <aop:config>
        <aop:aspect ref="loggingAspect">
            <aop:around pointcut="execution(* com.example.myapp.MyService.*(..))" method="aroundAdvice"/>
        </aop:aspect>
    </aop:config>
    

    在上面的配置中,我们首先创建了一个名为loggingAspect的切面类的实例,并使用ref属性将其引用到<aop:aspect>元素中。然后,使用<aop:around>元素来配置环绕通知,pointcut属性指定了匹配的方法表达式,而method属性指定了环绕通知的方法。

    无论是使用注解还是XML配置环绕通知,都需要确保你的切面类被Spring的组件扫描机制所扫描到,以确保Spring能够实例化和管理它。

    1年前 0条评论
注册PingCode 在线客服
站长微信
站长微信
电话联系

400-800-1024

工作日9:30-21:00在线

分享本页
返回顶部