springboot 事务自调用失效


springboot 事务自调用失效

              

                                 

自调用失效

       

自调用失效:同一个类中,一个方法调用另一个方法,被调用方法上的事务不生效

失效原因:spring事务底层使用动态代理,若同一个类中的方法吊用另一个方法,则不存在对象之间的代理关系,被调用方法的事务失效

         

解决方法

接口:HelloService,
接口实现类:HelloServiceImpl
方法:fun、fun2,fun2调用fun

# 新建类实现fun调用fun2
新建类HelloServiceImpl2,方法fun2在HelloServiceImpl2中
在类中注入HelloServiceImpl对象实例,方法fun在HelloServiceImpl中,
在HelloServiceImpl2的fun2中,调用HelloServiceImpl的fun方法

# application.getBean
在fun2中使用application.getBean(HelloService.class)获取对象helloService,
然后使用helloService.fun实现方法调用

# AopUtils.currentProxy()
@EnableAspectJAutoProxy(exposeProxy = true),将exposeProxy = true
在fun2中使用((HelloService)AopContext.currentProxy()).fun()实现方法调用

        

             

                                 

自调用失效示例

        

                          

             

***********

pojo

          

Person

@Getter
@Setter
@ApiModel(value = "Person对象", description = "")
public class Person extends Model<Person> {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String name;

    private Integer age;


    @Override
    public Serializable pkVal() {
        return this.id;
    }

}

              
***********

config 层

           

DataConfig

@Configuration
@MapperScan("com.example.demo.dao")
public class DataConfig {

    @Bean
    public MybatisPlusInterceptor initMybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();

        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);

        OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor =new OptimisticLockerInnerInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(optimisticLockerInnerInterceptor);

        return mybatisPlusInterceptor;
    }
}

           

***********

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值