![](/img/trans.png)
[英]Spring is not creating the bean for @service annotated class when one of its method is annotated with @transactional
[英]Spring @Transactional doesn't work for an annotated method when called from within service class
在下面的代码中,当从methodOuter中调用methodInner()时,应该在事务边界下。 但事实并非如此。 但是当直接从MyController类调用methodInner()时,它受到事务的约束。 有什么解释吗?
这是控制器类。
@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();
}
}
这是服务类 。
@Service("abcService")
public class MyService {
public void methodOuter() {
methodInner();
}
@Transactional
public void methodInner() {
.....
//does db operation.
.....
}
}
Spring默认使用Java代理来包装bean并实现带注释的行为。 在服务中进行调用时,您可以直接绕过代理和运行方法,因此不会触发带注释的行为。
可能的解决方案:
将所有@Transactional
代码移动到单独的服务,并始终从外部调用事务方法
即使在服务中,也可以使用AspectJ和编织来触发带注释的行为
将@Transactional
添加到methodOuter()
并且它可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.