Aspect声明式事物解决Spring事物内部调用不生效
文章来源:芷雪 时间:2025-03-11
正在之前诠释Spring实物没有奏效时,枚举了好多圆里的准绳,细致参照
Spring实物没有奏效的缘故
http://www.javacui.com/framework/560.html
个中道到了1面:正在类里面挪用移用类里面@Transactional标注的办法。这类环境停也会致使工作没有开放。
假设犹如停真例类:
@ServicepublicclassT1ServiceImplextendsServiceImpl<T1EntityMapper,T1Entity>implementsT1Service{@AutowiredprivateT2Servicet2Service;@OverridepublicvoidinsertT1(){doInsert();}@Transactional(rollbackFor=Exception.class)publicvoiddoInsert(){T1Entityt1Entity=newT1Entity();t1Entity.setName("t1");T2Entityt2Entity=newT2Entity();t2Entity.setName("t2");save(t1Entity);System.out.println(1/0);t2Service.save(t2Entity);}}如上模仿了1个同常,原因是运转时同常,因而补充解说rollbackFor,缘故没有见效那篇内部也道过:
(6)解释为工作规模的办法中,事宜的归滚只是对unchecked的同常无效。对待checked同常失效。也便是道工作归滚只是发作正在呈现RuntimeException或者Error的时分。假如盼望普通的同常也能触收工作归滚,须要正在证明了@Transactional的办法上,将@Transactional归滚参数创立。
那末挪用insertT1()时,insertT1()挪用doInsert(),固然该办法符号了实物,然则实质上实物是没有起感化的。
假若要处理那个题目,要末便是再写1个Service,要末便是写到1个办法内部,便1定要应用Spring代办署理去移用那个办法,不然Spring没法助尔们处置实物。
然则即使您必定要如许写,并且要正在1个Service内里,那末能够经由过程以下体例处理:
起首拿到以后对于象的代办署理对于象,普通您正在哪一个ServiceImpl内中,便是哪一个Service,而后经由过程代办署理对于象停止挪用,比方:
packagecom.example.springboot.service.impl;importcom.baomidou.mybatisplus.extension.service.impl.ServiceImpl;importcom.example.springboot.entity.T1Entity;importcom.example.springboot.entity.T2Entity;importcom.example.springboot.mapper.T1EntityMapper;importcom.example.springboot.service.T1Service;importcom.example.springboot.service.T2Service;importorg.springframework.aop.framework.AopContext;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Transactional;@ServicepublicclassT1ServiceImplextendsServiceImpl<T1EntityMapper,T1Entity>implementsT1Service{@AutowiredprivateT2Servicet2Service;@OverridepublicvoidinsertT1(){T1Servicet1Service=(T1Service)AopContext.currentProxy();t1Service.doInsert();}@Transactional(rollbackFor=Exception.class)publicvoiddoInsert(){T1Entityt1Entity=newT1Entity();t1Entity.setName("t1");T2Entityt2Entity=newT2Entity();t2Entity.setName("t2");save(t1Entity);System.out.println(1/0);t2Service.save(t2Entity);}}POM引进
<dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId></dependency>SpringBoot开动的话,要填充1个评释
@EnableAspectJAutoProxy(exposeProxy=true)以下
packagecom.example.springboot;importorg.mybatis.spring.annotation.MapperScan;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.context.annotation.EnableAspectJAutoProxy;@EnableAspectJAutoProxy(exposeProxy=true)@MapperScan("com.example.springboot.mapper")@SpringBootApplicationpublicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}如许便成了,那个办法也是经由过程代办署理停止挪用的,实物才会平常收效。
END
推举您浏览更多相关于“ spring解释实物springbootAspect证明式 ”的作品
文章推荐
Copyright © 2024-2025 燿动吧 – 知识分享,快乐你我,燿动青春 http://www.yaodong8.com All Rights Reserved 网站地图