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上下文的工具类

 1 package com.utils;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.ApplicationContextAware;
 6 
 7 public class ContextUtil implements ApplicationContextAware {
 8 
 9     private static ApplicationContext applicationContext; // Spring应用上下文环境
10 
11     /*
12      * 实现了ApplicationContextAware 接口,必须实现该方法;
13      * 通过传递applicationContext参数初始化成员变量applicationContext
14      */
15     public void setApplicationContext(ApplicationContext applicationContext)
16             throws BeansException {
17         ContextUtil.applicationContext = applicationContext;
18     }
19 
20     public static ApplicationContext getApplicationContext() {
21         return applicationContext;
22     }
23 
24     @SuppressWarnings("unchecked")
25     public static <T> T getBean(String name) throws BeansException {
26         return (T) applicationContext.getBean(name);
27     }
28 
29 }
View Code

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();


原文地址:https://www.cnblogs.com/eason-d/p/7840558.html