使用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());
}
}版权声明:本文为A_bad_horse原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。