Java Spring 3 TransactionManager和注释的问题

Java Spring 3 TransactionManager和注释的问题,java,spring,transactions,spring-transactions,Java,Spring,Transactions,Spring Transactions,我正试图在我的Web应用程序(由Spring MVC 3支持)中设置一个TransactionManager,因为我需要一个组件的方法,该组件被注释为@Transactional 这就是我的情况: web.xml:为SpringContextLoaderListener(applicationContext.xml和database.xml)加载2个xml文件 applicationContext.xml:包含一些我无法通过注释定义的bean,加上注释的标记,再加上通常的context:ann

我正试图在我的Web应用程序(由Spring MVC 3支持)中设置一个
TransactionManager
,因为我需要一个组件的方法,该组件被注释为
@Transactional

这就是我的情况:

  • web.xml
    :为Spring
    ContextLoaderListener
    applicationContext.xml
    database.xml
    )加载2个xml文件
  • applicationContext.xml:包含一些我无法通过注释定义的bean,加上注释的标记,再加上通常的context:annotation-config和context:component-scan(此组件扫描包括包含
    @Transactional
    方法的包)
  • database.xml
    :包含数据源(我正在使用commons dbcp中的
    BasicDataSource
    )、事务管理器定义和tx:annotation驱动
我有一个
@Component
(DeleteComponent
),它有一个接口和一个实现(
deletecomponentmpl
)。实现类用
@Component
注释,有一个公共方法用
@Transactional
注释(正如Spring文档所述,我注释了具体类而不是接口)。对于
@Transactional
,我没有输入任何参数,因为默认值是可以的。此类有一些DAO(用
@Repository
注释)通过
@Autowired
注入。我只使用普通的JDBC(没有Hibernate或其他ORM)。这个
@组件
被注入到
@控制器
(在spring-
servlet.xml中定义)

但是,如果注释为
@Transactional
的方法抛出异常(未选中,如
RuntimeException
),则不会回滚任何内容。数据库保留在异常发生之前所做的更改。我正在使用JettyWeb服务器在本地测试我的应用程序。我注意到,实际上似乎没有设置事务管理器。实际上,我的事务管理器名为
transactionManager
。设置注释驱动事务的xml行是


如果我将其更改为使用不存在的bean名称,如


应用程序仍然可以正确部署,并且不会抱怨

关于我应该检查什么使其工作的任何提示


谢谢。

要在引发异常时获得回滚,请添加以下内容:

@Transactional(rollboor=Exception.class)
您还需要设置transactionManger bean(这是我的,使用hibernate):



我发现这很有帮助。

我相信
@Autowired
@Resource
不会被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;
    }
}
并用以下命令调用您的dao:

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

我通过使用
@Transactional(rollboor=RuntimeException.class)
并从
BasicDataSource
切换到c3p0库中存在的
combopoolled
来解决这个问题。谢谢你的建议。

谢谢你的回答,反正我没有使用Hibernate,只有普通JDBC,我已经配置了TransactionManager(现在添加了问题中的代码)@默认情况下运行时异常的事务回滚,因此,仅当您还希望回滚已检查的异常,或者需要更细粒度的控件(例如,回滚自定义异常)时,才需要指定rollback属性。海报上说该方法引发了RuntimeException。为什么不从主appcontext.xml导入database.xml?如何在spring-servlet.xml中定义appcontext?组件扫描基本包与impl类的包匹配?至少@Autowired注释在用@component注释的类上工作良好。我已经用过很多次了。