this是当前对象,调用当前对象因为不是从IOC托管对象中
获取所以自然也是不能被AOP捕获。所有AOP的必须用代理对象执行。在同一个类中使用@Transaction,@Async并不能实现事务和异步,道理就是这样的。
新建一个类:
@Component
public class HelloComponent {
@Autowired
ApplicationContext applicationContext;
/**
* 设置了helloMessJoinPoint切入点
*/
public void helloMessJoinPoint() {
System.out.println("helloMess执行");
helloPrintJoinPoint("我是helloMessJoinPoint");
}
/**
* 未设置切入点,但是从SpringBoot容器访问对象
*/
public void helloMessNoJoinPointExt() {
System.out.println("helloMessNoJoinPointExt执行");
applicationContext.getBean(HelloComponent.class).helloPrintJoinPoint("我是helloMessNoJoinPointExt");
}
}
新建一个切面类并增加切入点:
@Aspect
@Component
public class CustomAspect {
@Before(value = "execution(* com.lx.bootaop.component.HelloComponent.helloPrintJoinPoint(*))")
public void doBefore(JoinPoint joinPoint) {
System.out.println("AOP拦截==执行before:" + joinPoint.getSignature());
}
}
新建一个测试类:
@SpringBootTest
class HelloComponentTest {
@Autowired
HelloComponent helloComponent;
@Test
public void helloMessJoinPoint() {
helloComponent.helloMessJoinPoint();
}
@Test
public void helloMessNoJoinPointExt() {
helloComponent.helloMessNoJoinPointExt();
}
}
当我们调用helloMessJoinPoint方法,因为helloMessJoinPoint中调用helloPrintJoinPoint是使用this方式,所以AOP并为切入到。

调用helloMessNoJoinPointExt,因为helloPrintJoinPoint使用IOC托管中获取的对象实例,所以可以正常的拦截。

本文探讨了Spring AOP在方法调用中的应用,解释了为何在同一个类内使用`@Transactional`和`@Async`注解无法生效的原因。通过示例展示了当直接使用`this`关键字调用方法时,AOP无法介入,而通过Spring容器获取对象则能正常拦截。同时,提供了配置切面和测试用例来进一步说明AOP的工作原理。

641

被折叠的 条评论
为什么被折叠?



