---
title: "spring+hibernate 声明式事务管理"
author: "William_Third"
date: "2013-03-01T21:24:48Z"
tags: []
categories: ["数据库"]
slug: "spring-hibernate"
draft: false
lastmod: "2013-03-01T21:24:48Z"
id: 1820122
url: "https://william-third.iteye.com/blog/1820122"
---

之前在使用 spring+hibernate 声明式事务管理时，总是出错，无法进行事务管理，摸索了很久，终于明白。

既然使用 srping管理事务，那么所有的 bean都要在 springIoC中进行管理，否则何谈 spring声明式事务，包括 Dao层，service层和 controller层

在 controller层中

```java
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
FooService defaultFooService = (FooService) ctx.getBean("fooService");
```


通过getBean来得到 service层对象，并进行操作。
注意，FooService是接口，而fooService在 applicationContext.xml中为实现该接口的对象，这是因为使用代理模式

之前我出错在，对 defaultFooService 采用单例模式

```java
DefaultFooService defaultFooService = DefaultFooService.getInstance();
```

如此管理操作 service层
这里获得的 defaultFooService并不是由 spring注入的那个对象，进而无法使用声明式事务管理

spring管理的默认是单例模式