I want to write this piece of code :
@Stateless
public class MyEjb
{
@EJB
private static MyOtherEjbWhichIWantStatic myOtherEjb;
}
It makes sense to me, that I want to inject an EJB in my class, as a static element, for various reason.
Java is not very happy with that unfortunately
com.sun.enterprise.container.common.spi.util.InjectionException: Illegal use of static field private static MyOtherEjbWhichIWantStatic myOtherEjb on class that only supports instance-based injection
I don’t get it, why can’t I inject a static EJB into another EJB ?
As others pointed out, this is not allowed by the specification, and the short version is that the
@EJBannotation is only supported for static members in classes with amain()function (see the EJB 3.0 specification and the app client container).Why is it so? First of all, read/write static fields are totally forbidden in EJBs (this is part of the EJB restriction). From Why can’t I use nonfinal static fields in my enterprise bean?
But while using read-only static fields is allowed, this wouldn’t be appropriate for EJBs. Stateless EJBs may be pooled, a container may decide to destroy them (this is implementation specific) and you want to let the container choose which instance you’re going to use, especially in distributed environments. In other words, never assume you are tied to a particular instance.
So at the end, yes, this is a nonsense.