目录
问题描述
在service类中有个a方法调用内部b方法时,无法拦截到b方法。
示例
例如如下示例代码,当访问controller的hello方法时,无法拦截service层testA方法中调用到的内部testB方法。
package com.example.test.controller;
import com.example.test.service.Service;
================================================controller层========
@RestController
public class TestController{
@Autowired
Service service;
@RequestMapping("")
public void hello(String name)
{
service.testA(name);
}
}
================================================Service层========
package com.example.test.service;
public class Service{
public void testA(String name);
}
================================================Service实现类========
package com.example.test.service.impl;
public class ServiceImpl impl Service{
@Override
@Transactional
public void testA(String name) {
testB(name);
}
public void testB(String name){
}
}
==========================ASPECT=============
@Component
@Aspect
@Order(1)
public class ServiceAspect {
@Before("execution(* com.example.test..*.testA(..))")
public void approve(JoinPoint joinPoint)
{
Object[] args = joinPoint.getArgs();
}
}
解决方法
1.修改Service层的testA方法:
package com.example.test.service.impl;
public class ServiceImpl impl Service{
@Override
@Transactional
public void testA(String name) {
ServiceImpl service = AopContext.currentProxy() != null
? (ServiceImpl)AopContext.currentProxy() : this;
service.testB(name);
}
public void testB(String name){
System.out.println(name);
}
}
2.在springboot启动类上开启aop代理
@EnableAspectJAutoProxy(exposeProxy = true)
3.重新启动后,aop就能拦截到testB方法。