How to get transactions to a @PostConstruct CDI bean method

℡╲_俬逩灬. 提交于 2019-12-18 09:03:37

问题


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) that does some work with the database (inserts some rows etc..). For this I need a transaction, but this wasn't as easy as I expected.

I have tried adding @Transactional annotation to my method, but apparently it only works with EJB. I actually tried converting my bean to EJB instead of CDI bean, but I still didn't get transaction to my @PostConstruct method. It worked with other methods in the bean, but not with my @PostConstruct initialization method.

Then I read about creating method interceptor to get transactions to CDI beans:

http://eubauer.de/kingsware/2012/01/16/cdi-and-transactions-e-g-in-jboss-7-0-2/

I tried this too, but no luck. It doesnt work either.

So how does one get transactions to a @PostConstruct initialization method in a CDI bean?


回答1:


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



来源:https://stackoverflow.com/questions/19876637/how-to-get-transactions-to-a-postconstruct-cdi-bean-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!