Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jakarta ee - Inject @EJB bean based on conditions

A newbie question: is there anyway that I can inject different beans based on a condition that I set in a properties file. Here's what I want to achieve:

I set some value in properties file. If it's true, then I want to

  public class MyClass{
    @EJB
    private MyBean bean;
  }

if it's false, then

public class MyClass{
  @EJB
  private MyBean2 bean2;
 }

Is this doable?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As Gonzalo said, you would firstly need to specify the common interface of the bean if you want to declare it as a class field and use different implementations of it.

Moreover, I think you could achieve it more elegant using the CDI's @Produces method; i.e. somewhat 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 just use:

@Inject
MyBean myBean;

and appropriate bean based on your condition will be injected for you.

If you don't need a field on class level you could use the old-way and locate the EJB in JNDI - in this way you have the control over what type and what bean should be located and used.

EDIT: I've added the @EJB annotated beans to show where the 'myBean1' and 'myBean2' instances might come from.

This example shows that you can have one, single place where you define all your dependencies on different EJB implementations and other components. In an examle, this could be realised as a singleton EJB with @EJB fields, @PersistenceContext fields, etc.

Instead of doing it in the presented way, you can change return myBean1 to something like return context.lookup("JNDI_NAMESPACE_COORDINATES") where context is an instance of InitialContext.

Hope this makes it more clear.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...