使用AopContext,获取当前代理对象。
案例分析
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
public void test() {
UserDepartmentService userDepartmentService = (UserDepartmentService) AopContext.currentProxy();
userDepartmentService.createUserDepartment(userDepartment);
}
}
执行上述代码时,报错如下:
UserDepartmentService userDepartmentService = (UserDepartmentService) AopContext.currentProxy();
Cannot cast 'com.xx.impl.LoginServiceImpl--EnhancerBySpringCGLIB--bdfdb805' to 'com.xx.UserDepartmentService'
原因:
AopContext.currentProxy();获取当前被代理的对象。LoginServiceImpl被spring代理了。UserDepartmentService没被代理所以报这个异常。
结论:AopContext只能获取当前Service对象,可使用BeanFactory获取其他代理对象。
正确使用实例如下:
@Service
public class A {
public void action(){
((A) AopContext.currentProxy()).dosome();
}
@Transactional
public void dosome(){
doa.insert(new Object());
}
}