Vu NG
Vu NG

Reputation: 290

Can Inject (@EJB) Bean in method of other Bean Session(Remote or Local) class

I'm a newbie to EJB. I want to know is can inject EJB in method of other bean session, if not why? as code below:

@Local
interface car {
    public void drive();
}

@Stateless
public class Toyota implements Car {
   @Override
   public void drive() {
       @EJB 
       Color color;
       ...
   }
}

The code example is welcome.

Upvotes: 1

Views: 2173

Answers (2)

Alex K.
Alex K.

Reputation: 3304

You can't. @EJB @Target is defined like this:

@Target({TYPE, METHOD, FIELD})

and @Inject @Target is defined like this:

@Target({ METHOD, CONSTRUCTOR, FIELD })

That means that annotation can only be used with listed element types. From Javadoc of @Target annotation:

Indicates the kinds of program element to which an annotation type is applicable.

You should have LOCAL_VARIABLE as an ElementType in order to be able to inject it as a local variable of a method.

If you read more about EJBs you will actually find out, that there is a reason for that, as it would be impossible for a container to manage local variables.

Upvotes: 1

Gas
Gas

Reputation: 18020

No, you cant inject into method. You may only use @EJB at class level, field or setter like this:

@Stateless
@EJB(name="myBeanRef", beanInterface=MyBean.class)   // this creates only reference - you will need to initialize it for example via initialConetxt.lookup()
public class EJBTests{
    @EJB (name=”ejb/bean1”)  // this injects bean named ejb/bean1
    MyBean1 bean1;

    MyBean2 bean2;

    ....
    @EJB (name="ejb/bean2")   // this injects bean using setter method
    public void setEcho(MyBean2 bean2) {
       this.bean2 = bean2;
    }
}

For more details check 7.1 @EJB – injecting an EJB from the EJB 3.1 specification.

Upvotes: 2

Related Questions