sql – 为什么我不能在Spring中创建这个bean @Transactional?

我正在编写一个我想用表名配置的简单bean,一个包含一些数据的XML文件,这样如果在应用程序启动时表是空的,那么就会使用该数据进行初始化.我决定使用简单的SQL查询,但我无法从sessionfactory获取会话,因为它说:

Error creating bean with name 'vecchiOrdiniFiller' defined in ServletContext resource [/WEB-INF/spring/servlet-context.xml]: Invocation of init method Failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread,and configuration does not allow creation of non-transactional one here

但这是配置(非常类似于服务):

stemaLoader" class="it.jsoftware.jacciseweb.assistenza.common.ExcelXmlDataLoader">
    marco.xml">stemaLoader">venditore` VARCHAR(255) DEFAULT NULL,`cliente` VARCHAR(255) DEFAULT NULL,PRIMARY KEY (`ID`)) ENGINE=INNODB DEFAULT CHARSET=utf8">venditorevenditore

我用@Transactional注释了init()方法.但它没有启动事务,我得到了这个错误

@Transactional
public void init() throws Exception {
    logger.info("BaseTableFilter per tabella: " + table + ",usando: "
    + loader.getSourceName());

    Session session = dao.getSession();
    Transaction tx = session.beginTransaction();
    ...

为什么不工作?

最佳答案
init-method或@postconstruct注释方法未被代理,因此您将无法使用@Transactional.您应该在服务上使用@Transactional,为什么不适合您?
引自SpringSource Jira

This is as defined,actually: init methods (such as @postconstruct methods) are always called on the target instance itself. The proxy will only be generated once the target instance has been fully initialized… In other words,the @Transactional proxy isn’t even created at the point of the @postconstruct call yet.

Switching to mode=”aspectj” would help since it weaves the target class directly,in which case the init method will have been modified for transactional awareness at the time of the container init call already.

I guess at the very minimum,we should document the limitations of @Transactional on proxies more clearly – and point out where mode=”aspectj” might be a solution.

如上所述,您可以尝试mode =“aspectj”,但您应该在我看来检查您的设计.

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...