[英]Spring @Transactional doesn't work for an annotated method when called from within service class
In below code , when methodInner() is called from within methodOuter , should be under transaction bounds. 在下面的代码中,当从methodOuter中调用methodInner()时,应该在事务边界下。 But it is not.
但事实并非如此。 But when methodInner() is called directly from MyController class , it is bound by transaction.
但是当直接从MyController类调用methodInner()时,它受到事务的约束。 Any explanations?
有什么解释吗?
This is controller class. 这是控制器类。
@Controller
public class MyController {
@Autowired
@Qualifier("abcService")
private MyService serviceObj;
public void anymethod() {
// below call cause exception from methodInner as no transaction exists
serviceObj.methodOuter();
}
}
This is service class . 这是服务类 。
@Service("abcService")
public class MyService {
public void methodOuter() {
methodInner();
}
@Transactional
public void methodInner() {
.....
//does db operation.
.....
}
}
Spring uses Java proxies by default to wrap beans and implement annotated behavior. Spring默认使用Java代理来包装bean并实现带注释的行为。 When doing calls within a service you bypass proxy and run method directly, so annotated behavior is not triggered.
在服务中进行调用时,您可以直接绕过代理和运行方法,因此不会触发带注释的行为。
Possible solutions: 可能的解决方案:
Move all @Transactional
code to separate service and always do calls to transactional methods from outside 将所有
@Transactional
代码移动到单独的服务,并始终从外部调用事务方法
Use AspectJ and weaving to trigger annotated behavior even within a service 即使在服务中,也可以使用AspectJ和编织来触发带注释的行为
将@Transactional
添加到methodOuter()
并且它可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.