如何在jboss 7.1上以编程方式绑定到jndi自定义对象?
Context.bind引发异常,指示jndi上下文是只读的。
有可能吗?
最佳答案
是的,有可能。以下代码可在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。