[英]How to get transactions to a @PostConstruct CDI bean method
I'm experimenting with Java EE 7, CDI, JPA and JSF. 我正在尝试使用Java EE 7,CDI,JPA和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..). 当webapp启动时,我想在我的CDI bean(标有@PostConstruct)中运行一个初始化方法,该方法可以对数据库进行一些操作(插入一些行等等)。 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. 我已经尝试将@Transactional注释添加到我的方法中,但显然它只适用于EJB。 I actually tried converting my bean to EJB instead of CDI bean, but I still didn't get transaction to my @PostConstruct method. 我实际上尝试将我的bean转换为EJB而不是CDI bean,但我仍然没有得到我的@PostConstruct方法的事务。 It worked with other methods in the bean, but not with my @PostConstruct initialization method. 它适用于bean中的其他方法,但不适用于我的@PostConstruct初始化方法。
Then I read about creating method interceptor to get transactions to CDI beans: 然后我读到了创建方法拦截器来获取CDI bean的事务:
http://eubauer.de/kingsware/2012/01/16/cdi-and-transactions-eg-in-jboss-7-0-2/ http://eubauer.de/kingsware/2012/01/16/cdi-and-transactions-eg-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? 那么如何在CDI bean中获取@PostConstruct初始化方法的事务呢?
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. 在@PostConstruct中(与InitializingBean接口中的afterPropertiesSet一样),无法确保所有后期处理都已完成,因此(实际上)可能没有事务。 The only way to ensure that that is working is by using a TransactionTemplate. 确保其正常工作的唯一方法是使用TransactionTemplate。
So the only way to do something with the database from the @PostConstruct is to do something like this: 因此,从@PostConstruct对数据库执行某些操作的唯一方法是执行以下操作:
@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 注意:类似的线程,但在@PostConstruct方法上引用Spring框架@Transactional
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.