Search code examples
jbossjndi

jboss 7.1 jndi binding programmatically


How to bind to jndi custom object programmatically on jboss 7.1? Context.bind throws exception indicating that jndi context is read-only. Is it possible at all?


Solution

  • Yes, it is possible at all. The following code works in 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!");
        }
    }
    

    If you call first registerInJndi() and afterwards retrieveFromJndi() the object will be looked up and the method helloWorld()is called.

    You will find more information here.