![](/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.