cannot find my bean using the InitialContext.looku

2019-02-20 09:29发布

I have tried to use struts 1.3 API to make a small application with EJB 3.0. Unfortunatelly i cannot use the @EJB annotation to call my bean object from inside my action class. I have solved this problem using different workarounds ( the first one is to use my global jndi name of my bean and the other is to call another class first and use the @EJB annotation from that class). Still these two workarounds have significant disadvantages. I would like to call my EJB directly from my action class. I have read plenty examples using the "java:comp/env/beanName" JNDI name but still haven't figure out how to do it and get name not found axception. Let the full name of the local EJB class be the com.ejb.myEjbPackage.MyEJBLocal, how can i call it using the context lookup? (can i do it without modifying any of the web.xml and sun-web.xml descriptors?) I am using glassfish server and Netbeans IDE.

Thank you in advance

2条回答
Summer. ? 凉城
2楼-- · 2019-02-20 10:09

I found the answer : If you cannot use the EJB annotation in the class you want to call the bean then : If you don't want to mess with XML descriptors to define your bean , you have to do it in the bean class itself. Hence i used the following annotation in the GameBean class

     @Stateless
     @EJB(name="ejb/GameBean",beanInterface=GameBeanLocal.class,beanName="GameBean")
     public class GameBean implements GameBeanLocal {.....

The beanName is optional. The annotation must be declared in the line ABOVE the declaration of the class. Then, in order to call the bean from the other class you can do

     InitialContext ic = new InitialContext();
     ic.lookup("java:comp/env/ejb/GameBean");
查看更多
做自己的国王
3楼-- · 2019-02-20 10:10

@EJB won't work in a standard pojo it can only be done in a managed object (i.e. another session bean)

So...

Here's your bean

@Stateless(mappedName="beanName")
public class beanName implements beanNameRemote {

Here's your lookup

Context context = new InitialContext();  //default lookup pulls from jndi properties file
context.lookup("beanName");

You can do some further reading on the mappedName to see if you want to use it or not.

查看更多
登录 后发表回答