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;
}
}
***********