Spring配置访问JNDI

通过创建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注入,记以备忘。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值