spring基於註解的宣告式事務

2021-10-19 08:00:08 字數 3610 閱讀 9058

<

!-- 配置事務管理器 --

>

"transactionmanager"

class

="org.springframework.jdbc.datasource.datasourcetransactionmanager"

>

"datasource" ref=

"datasource"

>

<

/property>

<

/bean>

package com.service.impl;

import com.dao.iaccountdao;

import com.domain.account;

import com.service.iaccountservice;

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.stereotype.service;

import org.springframework.transaction.annotation.propagation;

import org.springframework.transaction.annotation.transactional;

/** * 賬戶的業務層實現類

* * 事務控制應該都是在業務層

*/@service

("accountservice"

)@transactional

(readonly=

true

,propagation= propagation.supports)

public

class

accountserviceimpl

implements

iaccountservice

public account findaccountbyid

(integer accountid)

@transactional

(readonly=

false

,propagation=propagation.required)

public

void

transfer

(string sourcename, string targetname, float money)

}

該註解的屬性和 xml 中的屬性含義一致。該註解可以出現在介面上,類上和方法上。

出現介面上,表示該介面的所有實現類都有事務支援。

出現在類上,表示類中所有方法有事務支援

出現在方法上,表示方法有事務支援。

以上三個位置的優先順序:方法》類》介面

<

!-- 開啟 spring 對註解事務的支援 --

!-- 配置spring建立容器時要掃瞄的包--

>

package

="com"

>

<

/context:component-scan>

<

!-- 配置jdbctemplate--

>

"jdbctemplate"

class

="org.springframework.jdbc.core.jdbctemplate"

>

"datasource" ref=

"datasource"

>

<

/property>

<

/bean>

<

!-- 配置資料來源--

>

"datasource"

class

="org.springframework.jdbc.datasource.drivermanagerdatasource"

>

"driverclassname" value=

"com.mysql.jdbc.driver"

>

<

/property>

"url" value=

"jdbc:mysql://localhost:3306/eesy_spring"

>

<

/property>

"username" value=

"root"

>

<

/property>

"password" value=

"root"

>

<

/property>

<

/bean>

<

!-- spring中基於註解 的宣告式事務控制配置步驟

1、配置事務管理器

2、開啟spring對註解事務的支援

3、在需要事務支援的地方使用@transactional註解

-->

<

!-- 配置事務管理器 --

>

"transactionmanager"

class

="org.springframework.jdbc.datasource.datasourcetransactionmanager"

>

"datasource" ref=

"datasource"

>

<

/property>

<

/bean>

<

!-- 開啟spring對註解事務的支援--

>

"transactionmanager"

>

<

/tx:annotation-driven>

<

/beans>

這樣也控制事務的出錯問題

資料庫沒有變化

spring基於註解 的宣告式事務控制(配置方式)

配置事務管理器 transactionmanager class org.springframework.jdbc.datasource.datasourcetransactionmanager datasource ref datasource property bean service acco...

Spring 基於XML和註解的宣告式事務控制

配置事務管理器 配置事務通知 配置切入點表示式 配置切入點與事務通知的依賴關係 配置事務的屬性 context component scan base package com.demo context component scan jdbcutils class com.demo.utils.jdb...

Spring註解宣告式事務配置

一 引入命名空間 二 具有 transactional 註解的bean 自動配置為宣告式事務支援 bean id transactionmanager class org.springframework.orm.hibernate3.hibernatetransactionmanager prope...