Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

java - How to get transactions to a @PostConstruct CDI bean method

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...