Skip to content

Commit 5a47c64

Browse files
authored
Update spring-transaction.md
1 parent 1781487 commit 5a47c64

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

docs/system-design/framework/spring/spring-transaction.md

+16-5
Original file line numberDiff line numberDiff line change
@@ -276,15 +276,18 @@ public interface TransactionStatus{
276276
举个例子:我们在 A 类的`aMethod()`方法中调用了 B 类的 `bMethod()` 方法。这个时候就涉及到业务层方法之间互相调用的事务问题。如果我们的 `bMethod()`如果发生异常需要回滚,如何配置事务传播行为才能让 `aMethod()`也跟着回滚呢?这个时候就需要事务传播行为的知识了,如果你不知道的话一定要好好看一下。
277277

278278
```java
279+
@Service
279280
Class A {
281+
@Autowired
282+
B b;
280283
@Transactional(propagation = Propagation.xxx)
281284
public void aMethod {
282285
//do something
283-
B b = new B();
284286
b.bMethod();
285287
}
286288
}
287289

290+
@Service
288291
Class B {
289292
@Transactional(propagation = Propagation.xxx)
290293
public void bMethod {
@@ -357,15 +360,17 @@ public enum Propagation {
357360
举个例子:如果我们上面的`aMethod()``bMethod()`使用的都是`PROPAGATION_REQUIRED`传播行为的话,两者使用的就是同一个事务,只要其中一个方法回滚,整个事务均回滚。
358361

359362
```java
363+
@Service
360364
Class A {
365+
@Autowired
366+
B b;
361367
@Transactional(propagation = Propagation.REQUIRED)
362368
public void aMethod {
363369
//do something
364-
B b = new B();
365370
b.bMethod();
366371
}
367372
}
368-
373+
@Service
369374
Class B {
370375
@Transactional(propagation = Propagation.REQUIRED)
371376
public void bMethod {
@@ -381,15 +386,18 @@ Class B {
381386
举个例子:如果我们上面的`bMethod()`使用`PROPAGATION_REQUIRES_NEW`事务传播行为修饰,`aMethod`还是用`PROPAGATION_REQUIRED`修饰的话。如果`aMethod()`发生异常回滚,`bMethod()`不会跟着回滚,因为 `bMethod()`开启了独立的事务。但是,如果 `bMethod()`抛出了未被捕获的异常并且这个异常满足事务回滚规则的话,`aMethod()`同样也会回滚,因为这个异常被 `aMethod()`的事务管理机制检测到了。
382387

383388
```java
389+
@Service
384390
Class A {
391+
@Autowired
392+
B b;
385393
@Transactional(propagation = Propagation.REQUIRED)
386394
public void aMethod {
387395
//do something
388-
B b = new B();
389396
b.bMethod();
390397
}
391398
}
392399

400+
@Service
393401
Class B {
394402
@Transactional(propagation = Propagation.REQUIRES_NEW)
395403
public void bMethod {
@@ -408,15 +416,18 @@ Class B {
408416
这里还是简单举个例子:如果 `bMethod()` 回滚的话,`aMethod()`也会回滚。
409417

410418
```java
419+
@Service
411420
Class A {
421+
@Autowired
422+
B b;
412423
@Transactional(propagation = Propagation.REQUIRED)
413424
public void aMethod {
414425
//do something
415-
B b = new B();
416426
b.bMethod();
417427
}
418428
}
419429

430+
@Service
420431
Class B {
421432
@Transactional(propagation = Propagation.NESTED)
422433
public void bMethod {

0 commit comments

Comments
 (0)