分享

Spring: @Transactional中的propagation属性

 yan的图书41 2017-07-11

spring的事务管理中,我们可以使用@Transactional这一annotation来对事务进行声明式的设定。具体而言,就是在类或者方法前添加@Transactional并传入属性参数以获取所需要的Transaction特性。Spring中的@Transactional有5个属性:Propagation、Isolation、Rollback Rules、Timeout和Read-Only,其中Propagation属性定义了Transaction的边界 — 是否使用Transaction、在Transaction已存在的情况下如何表现等。

在service类前加上@Transactional,声明这个service所有方法需要事务管理。每一个业务方法开始时都会打开一个事务。 


Spring默认情况下会对运行期例外(RunTimeException)进行事务回滚。这个例外是unchecked 

如果遇到checked意外就不回滚。 

如何改变默认规则: 

1 让checked例外也回滚:在整个方法前加上 @Transactional(rollbackFor=Exception.class) 

2 让unchecked例外不回滚: @Transactional(notRollbackFor=RunTimeException.class) 

3 不需要事务管理的(只查询的)方法:@Transactional(propagation=Propagation.NOT_SUPPORTED) 

在整个方法运行前就不会开启事务 

       还可以加上:@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true),这样就做成一个只读事务,可以提高效率。 

       各种属性的意义: 

       REQUIRED:业务方法需要在一个容器里运行。如果方法运行时,已经处在一个事务中,那么加入到这个事务,否则自己新建一个新的事务。 

       NOT_SUPPORTED:声明方法不需要事务。如果方法没有关联到一个事务,容器不会为他开启事务,如果方法在一个事务中被调用,该事务会被挂起,调用结束后,原先的事务会恢复执行。 

       REQUIRESNEW:不管是否存在事务,该方法总汇为自己发起一个新的事务。如果方法已经运行在一个事务中,则原有事务挂起,新的事务被创建。 

       MANDATORY:该方法只能在一个已经存在的事务中执行,业务方法不能发起自己的事务。如果在没有事务的环境下被调用,容器抛出例外。 

       SUPPORTS:该方法在某个事务范围内被调用,则方法成为该事务的一部分。如果方法在该事务范围外被调用,该方法就在没有事务的环境下执行。 

       NEVER:该方法绝对不能在事务范围内执行。如果在就抛例外。只有该方法没有关联到任何事务,才正常执行。 

       NESTED:如果一个活动的事务存在,则运行在一个嵌套的事务中。如果没有活动事务,则按REQUIRED属性执行。它使用了一个单独的事务,这个事务拥有多个可以回滚的保存点。内部事务的回滚不会对外部事务造成影响。它只对DataSourceTransactionManager事务管理器起效。 

观察以下两个定义了@Transactional的方法,innerMethod()模拟了Transaction已经存在的情况,outMethod()则模拟了不存在已定义Transaction的情况:

@Transactional
public void outMethod() {
    exampleDAO.doSomething();
    innerMethod();
}

@Transactional
public void innerMethod() {
    exampleDAO.doElse();
}

对于这两个方法,定义不同的Propagation属性值所产生的效果如下(Propagation.NESTED的情况较为复杂,在此忽略): 

Propagation属性 outMethod innerMethod
Propagation.MANDATORY .抛出异常 .在outMethod的Transaction中运行
Propagation.NEVER .不在Transaction中运行 .抛出异常
Propagation.NOT_SUPPORTED .不在Transaction中运行 .outMethod的Transaction暂停直至innerMethod执行完毕
Propagation.REQUIRED ( 默认值 ) .新开一个Transaction并在其中运行 .在outMethod的Transaction中运行
Propagation.REQUIRES_NEW .新开一个Transaction并在其中运行 .outMethod的Transaction暂停直至innerMethod中新开的Transaction执行完毕
Propagation.SUPPORTS .不在Transaction中运行 .在outMethod的Transaction中运行


@Transactional的代码定义:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. @Target({ElementType.METHOD, ElementType.TYPE})  
  2. @Retention(RetentionPolicy.RUNTIME)  
  3. @Inherited  
  4. @Documented  
  5. public @interface Transactional {  
  6.   
  7.     /**  
  8.      * A qualifier value for the specified transaction.  
  9.      * <p>May be used to determine the target transaction manager,  
  10.      * matching the qualifier value (or the bean name) of a specific  
  11.      * {@link org.springframework.transaction.PlatformTransactionManager}  
  12.      * bean definition.  
  13.      */  
  14.     String value() default "";  
  15.   
  16.     /**  
  17.      * The transaction propagation type.  
  18.      * Defaults to {@link Propagation#REQUIRED}.  
  19.      * @see org.springframework.transaction.interceptor.TransactionAttribute#getPropagationBehavior()  
  20.      */  
  21.     Propagation propagation() default Propagation.REQUIRED;  
  22.   
  23.     /**  
  24.      * The transaction isolation level.  
  25.      * Defaults to {@link Isolation#DEFAULT}.  
  26.      * @see org.springframework.transaction.interceptor.TransactionAttribute#getIsolationLevel()  
  27.      */  
  28.     Isolation isolation() default Isolation.DEFAULT;  
  29.   
  30.     /**  
  31.      * The timeout for this transaction.  
  32.      * Defaults to the default timeout of the underlying transaction system.  
  33.      * @see org.springframework.transaction.interceptor.TransactionAttribute#getTimeout()  
  34.      */  
  35.     int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;  
  36.   
  37.     /**  
  38.      * {@code true} if the transaction is read-only.  
  39.      * Defaults to {@code false}.  
  40.      * <p>This just serves as a hint for the actual transaction subsystem;  
  41.      * it will <i>not necessarily</i> cause failure of write access attempts.  
  42.      * A transaction manager which cannot interpret the read-only hint will  
  43.      * <i>not</i> throw an exception when asked for a read-only transaction.  
  44.      * @see org.springframework.transaction.interceptor.TransactionAttribute#isReadOnly()  
  45.      */  
  46.     boolean readOnly() default false;  
  47.   
  48.     /**  
  49.      * Defines zero (0) or more exception {@link Class classes}, which must be a  
  50.      * subclass of {@link Throwable}, indicating which exception types must cause  
  51.      * a transaction rollback.  
  52.      * <p>This is the preferred way to construct a rollback rule, matching the  
  53.      * exception class and subclasses.  
  54.      * <p>Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(Class clazz)}  
  55.      */  
  56.     Class<? extends Throwable>[] rollbackFor() default {};  
  57.   
  58.     /**  
  59.      * Defines zero (0) or more exception names (for exceptions which must be a  
  60.      * subclass of {@link Throwable}), indicating which exception types must cause  
  61.      * a transaction rollback.  
  62.      * <p>This can be a substring, with no wildcard support at present.  
  63.      * A value of "ServletException" would match  
  64.      * {@link javax.servlet.ServletException} and subclasses, for example.  
  65.      * <p><b>NB: </b>Consider carefully how specific the pattern is, and whether  
  66.      * to include package information (which isn't mandatory). For example,  
  67.      * "Exception" will match nearly anything, and will probably hide other rules.  
  68.      * "java.lang.Exception" would be correct if "Exception" was meant to define  
  69.      * a rule for all checked exceptions. With more unusual {@link Exception}  
  70.      * names such as "BaseBusinessException" there is no need to use a FQN.  
  71.      * <p>Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(String exceptionName)}  
  72.      */  
  73.     String[] rollbackForClassName() default {};  
  74.   
  75.     /**  
  76.      * Defines zero (0) or more exception {@link Class Classes}, which must be a  
  77.      * subclass of {@link Throwable}, indicating which exception types must <b>not</b>  
  78.      * cause a transaction rollback.  
  79.      * <p>This is the preferred way to construct a rollback rule, matching the  
  80.      * exception class and subclasses.  
  81.      * <p>Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(Class clazz)}  
  82.      */  
  83.     Class<? extends Throwable>[] noRollbackFor() default {};  
  84.   
  85.     /**  
  86.      * Defines zero (0) or more exception names (for exceptions which must be a  
  87.      * subclass of {@link Throwable}) indicating which exception types must <b>not</b>  
  88.      * cause a transaction rollback.  
  89.      * <p>See the description of {@link #rollbackForClassName()} for more info on how  
  90.      * the specified names are treated.  
  91.      * <p>Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(String exceptionName)}  
  92.      */  
  93.     String[] noRollbackForClassName() default {};  
  94.   
  95. }  
  基于源代码,我们可以发现在@Transactional,原来有这么多的属性可以进行配置,从而达到复杂应用控制的目的。


http://www./articles/6rEjAv

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多