Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java ee6: override CDI alternative

I'm using Glassfish 3.1.2.2, java ee6.

I have a library in which a class uses CDI to get a helper class. I would like in one specific project where I use that library, to override that CDI dependency and force the library to use my own helper class, specific to that project instead. I can modify the library at will, but by default it should use its default helper class, so that behaviour doesn't change for other users of the library.

This should be the perfect application of the @Alternative CDI pattern. I made a java interface for the helper class API; There is a default implementation in the library, then I can use the <alternatives> tag in the beans.xml; in the project where I want to override the behaviour, I would specify my own implementation of the helper in the beans.xml of that specific project.

Except it doesn't work. It's apparently impossible to override the alternatives behaviour from the library outside of the library in CDI 1.0 (java ee6).

And so no matter what I specify in the beans.xml of my outer project, CDI keeps selecting the bean defined in the library.

I considered going through a producer but I didn't find how to get CDI to give to the producer the EntityManager as a parameter, so that I can pass it forward to the helper class. In this project, we normally inject the EntityManager using the @PersistenceContext annotation.

Any ideas on how to override that CDI injection from the outer project?

like image 417
Emmanuel Touzery Avatar asked Apr 19 '26 12:04

Emmanuel Touzery


1 Answers

You could write a Portable Extension to do this. Listen to the ProcessAnnotatedType event and replace the AnnotatedType with your own. You could use the Apache DeltaSpike BeanBuilder class to help with this.

like image 188
LightGuard Avatar answered Apr 21 '26 04:04

LightGuard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!