这个答案有点晚了,但可能对其他用户有用。它基于EJP 的回答。
以下解决方案在Apache Tomcat 7上进行了测试。
如果需要,可以替换LdapContext
为DirContext
.
创建对象工厂
创建一个实现ObjectFactory
实例化 a的类LdapContext
:
public class LdapContextFactory implements ObjectFactory {
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable<?, ?> environment) throws Exception {
Hashtable<Object, Object> env = new Hashtable<Object, Object>();
Reference reference = (Reference) obj;
Enumeration<RefAddr> references = reference.getAll();
while (references.hasMoreElements()) {
RefAddr address = references.nextElement();
String type = address.getType();
String content = (String) address.getContent();
switch (type) {
case Context.INITIAL_CONTEXT_FACTORY:
env.put(Context.INITIAL_CONTEXT_FACTORY, content);
break;
case Context.PROVIDER_URL:
env.put(Context.PROVIDER_URL, content);
break;
case Context.SECURITY_AUTHENTICATION:
env.put(Context.SECURITY_AUTHENTICATION, content);
break;
case Context.SECURITY_PRINCIPAL:
env.put(Context.SECURITY_PRINCIPAL, content);
break;
case Context.SECURITY_CREDENTIALS:
env.put(Context.SECURITY_CREDENTIALS, content);
break;
default:
break;
}
}
LdapContext context = new InitialLdapContext(env, null);
return context;
}
}
定义你的资源
将以下内容添加到您的context.xml
中,引用工厂并定义值以创建LdapContext
实例:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
...
<Resource name="ldap/LdapResource" auth="Container"
type="javax.naming.ldap.LdapContext"
factory="com.company.LdapContextFactory"
singleton="false"
java.naming.factory.initial="com.sun.jndi.ldap.LdapCtxFactory"
java.naming.provider.url="ldap://127.0.0.1:389"
java.naming.security.authentication="simple"
java.naming.security.principal="username"
java.naming.security.credentials="password" />
</Context>
如果您需要向资源添加更多属性/值,请考虑更新您ObjectFactory
在上面创建的以读取这些新属性/值。
使用你的资源
在需要的地方注入资源:
@Resource(name = "ldap/LdapResource")
private LdapContext bean;
或者查一下:
Context initialContext = new InitialContext();
LdapContext ldapContext = (LdapContext)
initialContext.lookup("java:comp/env/ldap/LdapResource");
看更多
Apache Tomcat 的文档解释了如何添加自定义资源工厂。