Spring boot 如何在子方法(方法嵌套)中使用事务。

伪代码阐述下问题。

  public class impl{
// 方法A
public void a(){
this.b
}

//方法B
@Transactional
public void b(){
//入库操作
}
}

如上所述,在方法B中使用了@Transactional进行事务操控,但是无法进行事务的使用。
正确的做法应该是在方法A中使用@Transactional才能进入切面开启事务,但是,事务应该只专注于操作数据库的连贯性操作,而且非业务带,如果业务代码中加入事务会大大影响性能。所以要解决上面的问题需要进行下面的操作。

第一步:在启动方法中加入

@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class StartUp{

   public static void main(String[] args) {
      SpringApplication.run(StartUp.class, args);
   }
}

第二步:修改调用的方式

public class impl{
// 方法A
public void a(){
impl service = (impl )AopContext.currentProxy();
service .b()
}

//方法B
@Transactional
public void b(){
//入库操作
}
}

如果出现
Cannot find current proxy: Set ‘exposeProxy’ property on Advised to ‘true’ to make it available.的错误,说明你第一步没做。

总结:
个人任务方法嵌套中的事务不能处罚是因为SpringAOP没有扫描到该切面,通过获取到当前类的代理对象AopContext.currentProxy()的方法加入到切面中被扫描解决了上述问题。

你可能感兴趣的:(SpringBoot)