How to get transactions to a @PostConstruct CDI bean method

后端 未结 1 1847
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 06:03

I\'m experimenting with Java EE 7, CDI, JPA and JSF.

When the webapp starts, I would like to run an initialization method in my CDI bean (marked with @PostConstruct)

相关标签:
1条回答
  • 2020-12-21 06:50

    Apparently it seems that:

    In the @PostConstruct (as with the afterPropertiesSet from the InitializingBean interface) there is no way to ensure that all the post processing is already done, so (indeed) there can be no Transactions. The only way to ensure that that is working is by using a TransactionTemplate.

    So the only way to do something with the database from the @PostConstruct is to do something like this:

    @Service("something")
    public class Something 
    {
    
        @Autowired
        @Qualifier("transactionManager")
        protected PlatformTransactionManager txManager;
    
        @PostConstruct
        private void init(){
            TransactionTemplate tmpl = new TransactionTemplate(txManager);
            tmpl.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    //PUT YOUR CALL TO SERVICE HERE
                }
            });
       }
    }
    

    NOTE: similar thread but referencing Spring framework @Transactional on @PostConstruct method

    0 讨论(0)
提交回复
热议问题