I'm working on a large Java EE 6 application that is deployed on JBoss 6 Final. My current tasks involve using @Inject consistently instead of @EJB, but I'm running into some problems on some types of beans, specifically @MessageDriven beans and beans with @Scheduled methods.
What happens is that if I'm unlucky with the timing (for @Sch开发者_StackOverflow中文版edule) or if there are messages in the MDBs' queues at startup, instantiation of the beans will fail because the injected resources (which are EJBs themselves) are not bound yet.
Because I use @Inject, I'm guessing that the EJB container considers my beans to be ready, since the container itself does not care about @Inject; it probably simply assumes that since there are no @EJB injections, the beans are ready for use. The injected CDI proxies will then fail because the resources to inject aren't actually bound yet.
Tiny example:
@Stateless
@LocalBean
public class MySupportingBean {
public void doSomething() {
...
}
}
@Singleton
public class MyScheduledBean {
@Inject
private MySupportingBean supportingBean;
@Schedule(second = "*/1", hour = "*", minute = "*", persistent = false)
public void onTimeout() {
supportingBean.doSomething();
}
}
The above example will probably not fail often because there are only two beans, but the project I'm working on binds lots of EJBs, which will amplify the problem. But it might fail because there is no guarantee that MySupportingBean is bound first, and if onTimeout is invoked before MySupportingBean is bound, then instantiation of MyScheduledBean will fail. If I used @EJB instead, MyScheduledBean wouldn't be bound until the dependency to MySupportingBean was satisfied.
Note that the example will not fail in onTimeout itself, but when CDI attempts to inject MySupportingBean.
I've read a lot of posts on different forums where many people argue that @Inject is always better. Generally, I agree, but how do they handle @Schedule or @MessageDriven combined with @Inject? In my experience, it comes down to dumb luck whether the beans will work or not in those cases, and the beans will fail arbitrarily, depending on which order the EJBs are deployed in, and when @Schedule or onMessage are invoked.
It might help to explicitly define the dependencies using the JBoss proprietary annotation @Depends
or using the jboss.xml file.
See this for a somewhat similar question: How to order deployment of EJBs and JMS queue config in JBoss 5?
精彩评论