2011-07-15 64 views
2

我想在我的Web应用程序(由Spring MVC 3提供支持)中设置一个TransactionManager,因为我需要一个注释为@Transactional的组件方法。TransactionManager和注解弹簧3问题

这是我的情况:

  • web.xml中:为Spring的ContextLoaderListener(applicationContext.xml中和database.xml)
  • applicationContext.xml的负载2 XML文件:包含一些豆类,我可以” t通过注释定义,加上注解的标签,加上通常的上下文:注释配置和上下文:组件扫描(这个组件扫描包括包含@Transactional方法的包)
  • database.xml:包含数据源(我使用commons-dbcp的BasicDataSource),事务管理器定义和tx:annotat离子驱动。

我有一个@Component(DeleteComponent),它有一个接口和一个实现(DeleteComponentImpl)。实现类用@Component注释,并且有一个公共方法用@Transactional注解(我注释了具体类而不是接口,如Spring文档所述)。对于@Transactional我没有提出任何参数,因为默认情况很好。这个类有一些DAO(用@Repository注解)通过@Autowired注入。我只使用普通的JDBC(没有Hibernate或其他ORM)。这个@Component被注入一个@Controller(在spring-servlet.xml中定义)。

但是,如果注解为@Transactional的方法抛出异常(未选中,如RuntimeException),则不会回滚任何内容。数据库在异常之前保留更改。我使用Jetty Web服务器在本地测试我的应用程序。我注意到的事实是,似乎没有设置事务管理器。实际上,我的事务管理器被命名为“transactionManager”。该XML行成立注解驱动的事务是

<tx:annotation-driven transaction-manager="transactionManager"/> 

<bean id="transactionManager" 
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
    <property name="dataSource" ref="dataSource"/> 
</bean> 

如果我改变它使用一个不存在的bean的名字一样

<tx:annotation-driven transaction-manager="fake"/> 

应用程序仍然部署正确,不抱怨。

我应该检查哪些技巧以使其工作?

谢谢。

+0

为什么不从您的主appcontext.xml导入database.xml?如何在spring-servlet.xml中定义appcontext?组件扫描基础包与您的impl类的包相匹配? – abalogh

回答

2

我用@Transactional解决(的rollbackFor = RuntimeException.class)和开关BasicDataSource转换为c3p0库中的ComboPooled。谢谢你的建议。

1

要获得回滚时,抛出一个异常补充一点:

@Transactional(rollbackFor=Exception.class) 

您还需要建立transactionManger豆(这里是我的,使用Hibernate):

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" 
       p:sessionFactory-ref="sessionFactory" /> 

我发现这tutorial信息。

+1

感谢您的答案,无论如何,我没有使用Hibernate,只有普通的JDBC,我已经配置了我的TransactionManager(现在添加了问题中的代码) – manub

+2

@Transactional回滚默认情况下,RuntimeExceptions,所以你需要指定仅当您想要在已检查的异常上进行回滚时,或者您需要更精细的控制(例如,回滚自定义异常)时,才使用rollbackFor属性。海报说这个方法抛出一个RuntimeException。 –

-2

我相信@Autowired和@Resource在@Component上不会被Spring扫描。 尝试使用ContextHolder类来获取上下文和DAO

@Component 
public class ContextHolder implements ApplicationContextAware { 

    /** 
    * Spring context which will directly be injected by Spring itself 
    */ 
    private static ApplicationContext context = null; 

    /** 
    * Overridden method of ApplicationContextAware, which will automatically be called by the container 
    */ 
    public void setApplicationContext(ApplicationContext context) throws BeansException { 
     this.context = context; 
    } 

    /** 

    /** 
    * Static method used to get the context 
    */ 
    public static ApplicationContext getApplicationContext() { 
     return context; 
    } 
} 

,并打电话给你的道:

ContextHolder.getApplicationContext().getBean("MyDAO"); 
+1

至少@Autowired注释在使用@Component注释的类上工作正常。我用过很多次。 –

+0

-1我还多次使用了@ @ Component和@ Autowired ... – Betlista