Java EE – inject @ EJB beans according to conditions
A novice question: can I inject different beans according to the conditions I set in the properties file This is what I want to achieve:
I set some values in the properties file If it's true, I think
public class MyClass{ @EJB private MyBean bean; }
If it's false, then
public class MyClass{ @EJB private MyBean2 bean2; }
Is this feasible
Solution
As Gonzalo said, if you want to declare it as a class field and use its different implementation, you first need to specify the public interface of the bean
In addition, I think you can use CDI's @ produces method to achieve more elegance; Between these lines:
@Singleton @Startup public class Configuration { private boolean someCondition; @postconstruct private void init() { someCondition = ... // get a value from DB,JMS,XML,etc. } @EJB(lookup="java:comp/env/myParticularBean") MyBean myBean1; @EJB(beanName="anotherTypeOfBeanInjectedByName") MyBean myBean2; @Produces public MyBean produceMyBean() { if (someCondition) return myBean1; } else { return myBean2; } } }
Then in your code, you can use:
@Inject MyBean myBean;
And will fill you with appropriate beans according to your conditions
If you don't need class level fields, you can use the old methods and locate EJBs in JNDI – in this way, you can control what types and what beans should be located and used
Edit: I added @ EJB annotated beans to show where 'mybean1' and 'mybean2' instances may come from
This example shows that you can have a single location where you can define all dependencies on different EJB implementations and other components In one example, this can be implemented as a singleton EJB with @ EJB field, @ persistencecontext field, etc
Instead of performing this operation in a rendered manner, you can change return mybean1 to return context Lookup ("jndi_namespace_coordinates"), where context is an instance of initialcontext
I hope this makes it clearer