通过创建Properties对象可以实现JNDI的访问:
public static Object lookup(String name) throws NamingException {
Properties p = new Properties();
p.put("server", "tomcat");
p.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
p.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jpn.interfaces");
p.put(Context.PROVIDER_URL, "jnp://9.9.9.9:1099");
InitialContext ctx = new InitialContext(p);
return ctx.lookup(name);
}
但是由于项目需求,想要对lookup的接口配置程spring的bean,通过IOC注入,最早想到的是直接用PropertyPlaceholderConfigurer去加载jndi.properties,然后用JndiObjectFactoryBean去读取JNDI配置信息,没有成功。
通过查看JndiObjectFactoryBean创建JndiObject的源码考虑采用JndiTemplate的方式加载JNDI配置信息。
private static Object createJndiObjectProxy(JndiObjectFactoryBean jof) throws NamingException {
// Create a JndiObjectTargetSource that mirrors the JndiObjectFactoryBean's configuration.
JndiObjectTargetSource targetSource = new JndiObjectTargetSource();
targetSource.setJndiTemplate(jof.getJndiTemplate());
targetSource.setJndiName(jof.getJndiName());
targetSource.setExpectedType(jof.getExpectedType());
targetSource.setResourceRef(jof.isResourceRef());
targetSource.setLookupOnStartup(jof.lookupOnStartup);
targetSource.setCache(jof.cache);
targetSource.afterPropertiesSet();
...
}
JNDITemplate相关创建initialContext代码如下
/**
* Create a new JNDI initial context. Invoked by {@link #getContext}.
* <p>The default implementation use this template's environment settings.
* Can be subclassed for custom contexts, e.g. for testing.
* @return the initial Context instance
* @throws NamingException in case of initialization errors
*/
protected Context createInitialContext() throws NamingException {
Hashtable icEnv = null;
Properties env = getEnvironment();
if (env != null) {
icEnv = new Hashtable(env.size());
CollectionUtils.mergePropertiesIntoMap(env, icEnv);
}
return new InitialContext(icEnv);
}
配置如下:
<bean id="securityService" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jndiTemplate" />
<property name="jndiName">
<value>SecurityServiceRemote/remote</value>
</property>
</bean>
成功通过IOC注入,记以备忘。