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

前端之家收集整理的这篇文章主要介绍了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

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

DataLoader">
    

我用@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相关文章