2013-10-17 127 views

回答

5

是的,這是可能的。下面的代碼工作中的JBoss AS 7.1.1.Final:

@Stateless 
public class JndiEjb { 
    private static final Logger LOGGER = LoggerFactory.getLogger(JndiEjb.class); 

    public void registerInJndi() { 
     try { 
      Context context = new InitialContext(); 
      context.bind("java:global/JndiEjb", this); 
     } catch (NamingException e) { 
      LOGGER.error(String.format("Failed to register bean in jndi: %s", e.getMessage())); 
     } 
    } 

    public void retrieveFromJndi() { 
     try { 
      Context context = new InitialContext(); 
      Object lookup = context.lookup("java:global/JndiEjb"); 
      if(lookup != null && lookup instanceof JndiEjb) { 
       LOGGER.debug("Retrieval successful."); 
       JndiEjb jndiEjb = (JndiEjb)lookup; 
       jndiEjb.helloWorld(); 
      } 
     } catch (NamingException e) { 
      LOGGER.error(String.format("Failed to register bean in jndi: %s", e.getMessage())); 
     } 
    } 

    public void helloWorld() { 
     LOGGER.info("Hello world!"); 
    } 
} 

如果你先打電話registerInJndi()事後retrieveFromJndi()的對象將擡頭一看,該方法helloWorld()被調用。

你會找到更多的信息here

+0

並且registerInJndi()應該在servlet中用load-on-startup = 0(也許從啓動ejb服務)被調用。在這裏,我們可以毫無例外地編輯jndi。 – user2889981