jboss 7.1 jndi以编程方式绑定

时间:2013-10-17 14:14:19

标签: jboss jndi

如何在jboss 7.1上以编程方式绑定到jndi自定义对象? Context.bind抛出异常,指示jndi上下文是只读的。 它有可能吗?

1 个答案:

答案 0 :(得分: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