1、依赖,引入此依赖后,springboot会自动开启自动代理,相当于@EnableAspectJAutoProxy,故不需要再手动添加这个注解。

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
   </dependency>

2、创建切面类 (声明切面类:Aspect。交由ioc管理:Component)return的proceed为方法执行后的返回数据。


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {

    @Around("execution(* com.ljs.springbootplace.service.impl.MyServiceImpl.getUserNameById(..))")
    public Object roundAsp(ProceedingJoinPoint pj){
        System.out.println("前");

        Object proceed = null;
        try {
            Object[] args = pj.getArgs();
            System.out.println("原参数为:"+args[0]);
            args[0]=1;
            System.out.println("修改后入参参数为:"+ pj.getArgs()[0]);
            //如果需要重新设置参数,则调用proceed的有参方法,否则直接调用无参方法即可
            proceed = pj.proceed(args);
        } catch (Throwable throwable) {
            System.out.println("异常");
            throwable.printStackTrace();
        }

        System.out.println("后");

        return proceed;
    }
}

3、使用springboot单元测试进行测试

import com.ljs.springbootplace.service.MyService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringbootplaceApplication.class)
public class SpringbootplaceApplicationTests {

    @Autowired
    private MyService myService;
    
    @Test
    public void test() {
        String userNameById = myService.getUserNameById_testAspect(1);//测试aop
        System.out.println(userNameById);
    }

}

4、测试结果:(原参数1对应返回“yang”,修改为2后,返回“wang”)

注:如需要获取切面执行的方法的名称,类,包等数据,可以参考:环绕通知中,获取执行的方法、所属类名、包名等数据的方式


版权声明:本文为weixin_43421537原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_43421537/article/details/104778208