項目中需要用到異步線程,就用了spring的TaskExecutor。本service實現類是注入TaskExecutor的。結果在run方法中,進行數據庫操作的時候,出現: No Hibernate Session bound to thread, and configuration does not allow creation of non-transaction異常。百度出來的說沒有進行事務管理。然後查找spring的配置文件。
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 使用註解方式定義事務 -->
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />
<!-- 配置事務傳播特性 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="send*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="excute*" propagation="REQUIRED" />
<tx:method name="operate*" propagation="REQUIRED" />
<tx:method name="stop*" propagation="REQUIRED" />
<tx:method name="back*" propagation="REQUIRED" />
<tx:method name="get*" read-only="true" />
<tx:method name="load*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<!-- 配置哪些類的哪些方法參與事務 -->
<aop:config>
<aop:advisor pointcut="execution(* com.wingo.service..*.*(..))" advice-ref="transactionAdvice" />
</aop:config>
自己的事務已經配置且方法命名已經具備事務傳播性。接着嘗試在實現的方法上添加@Transactional註解。仍然沒有解決bug。
覺得TaskExecutor的run方法,不具備session,曲線救國方式如下:
備註:SMSService的實現類bean重命名爲SMSService。上下文不一定要用WebApplicationContext。