正文
Spring @Trasactionl 失效, JDK,CGLIB动态代理
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
@Transaction: http://blog.csdn.net/bao19901210/article/details/41724355
Spring上下文: http://blog.csdn.net/yang123111/article/details/32099329
情况是这样的:
@Transactional
public void test(){
System.out.println("1 insert db...");
try {
((XxxService)AopContext.currentProxy()).add2();
} catch (Exception e) {
e.printStackTrace();
}
} @Transactional(propagation=Propagation.REQUIRES_NEW)
public void add2() throws Exception{
System.out.println("2 insert db...");
int i = 1;
if(i ==1 )
throw new RuntimeException("保存add2错误");
}
出现错误: com.sun.proxy.$Proxy27 cannot be cast to xxxService
Spring的文档中这么写的:
Spring AOP部分使用JDK动态代理或者CGLIB来为目标对象创建代理。如果被代理的目标实现了至少一个接口,则会使用JDK动态代理。所有该目标类型实现的接口都将被代理。若该目标对象没有实现任何接口,则创建一个CGLIB代理
解决办法2种:
1:JDK方式 新建一个Service调用add2方法.
1.1创建获取Spring上下文的工具类
package com.utils; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; public class ContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; // Spring应用上下文环境 /*
* 实现了ApplicationContextAware 接口,必须实现该方法;
* 通过传递applicationContext参数初始化成员变量applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
ContextUtil.applicationContext = applicationContext;
} public static ApplicationContext getApplicationContext() {
return applicationContext;
} @SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
} }
1.2 配置xml
<bean id="contextUtil" class="com.utils.ContextUtil" scope="singleton" />
1.3 调用
// IXxxService 接口类
IBoxStatusService iBoxStatusService = (IBoxStatusService)ContextUtil.getBean("boxStatusService");
iBoxStatusService.add2();
注意,此处的IBoxStatusService 是接口类
2 Cglib方式
1.1 导入cglib包
1.2 配置xml
<aop:config proxy-target-class="true" expose-proxy="true">
proxy-target-class="true" 默认是false 表示使用Cglib代理
expose-proxy="true" 默认是false 表示 目标对象内部的自我调用将无法实施切面中的增强1.3
((BoxStatusService)AopContext.currentProxy()).add2();