ApacheDS 是基於 LDAP 的目錄服務器,通過 JNDI 暴露操作接口。本文通過 3 個遞進示例,詳細演示 Java 對象在 ApacheDS 中的三種存儲形態:標準序列化、帶屬性綁定、編組對象。
ApacheDS.properties(外部化配置,支援多目錄服務切換):
java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory
java.naming.provider.url=ldap://localhost:389/ou=system
java.naming.security.authentication=simple
java.naming.security.principal=uid=admin,ou=system
代碼中載入屬性並設置憑證:
Properties props = new Properties();
props.load(new FileInputStream("ApacheDS.properties"));
props.setProperty("java.naming.security.credentials", "secret");
DirContext ctx = new InitialDirContext(props);
DirContext 接口:繼承 Context,增加屬性操作能力,是目錄服務核心操作句柄。
領域類需實現 Serializable 並定義 serialVersionUID(使用 serialver 工具生成):
public class MessagingPreferences extends Preferences implements Serializable {
static final long serialVersionUID = -1240113639782150930L;
// 業務字段與方法
}
存儲代碼:
MessagingPreferences prefs = new MessagingPreferences();
// 綁定上下文:cn=preferences,uid=alice,ou=users,ou=system
// 其中 uid=alice,ou=users,ou=system 為用戶 Alice 的現有 DN
ctx.bind("cn=preferences,uid=alice,ou=users", prefs);
底層機制:兩參數 bind() 會自動生成三個屬性:
javaClassName:完整類名javaClassNames:類名數組(含父類/接口)javaSerializedData:序列化二進制數據對象類為 javaContainer。
使用三參數 bind(String name, Object obj, Attributes attrs),同時創建用戶條目與偏好對象:
// 構建屬性集合
Attribute objclass = new BasicAttribute("objectClass");
objclass.add("person"); // 用戶條目標記為 person
Attributes attrs = new BasicAttributes(true);
attrs.put(objclass);
// 綁定上下文為用戶 DN:uid=Bob,ou=users
ctx.bind("uid=Bob,ou=users", preferences, attrs);
一步完成:創建用戶條目 (objectClass=person) 並存儲偏好對象作為子條目。
使用 java.rmi.MarshalledObject 封裝序列化數據,適用於 RMI 遠程傳輸場景:
MessagingPreferences prefs = new MessagingPreferences();
MarshalledObject mObj = new MarshalledObject(prefs); // 內部完成序列化
ctx.bind("cn=marshalledPreferences,uid=alice,ou=users", mObj);
存儲後對象類為 javaMarshalledObject,內部持有序列化字節流。
| 存儲方式 | API | 對象類 | 適用場景 |
|---|---|---|---|
| 標準序列化 | bind(name, obj) | javaContainer | 通用本地存儲 |
| 帶屬性綁定 | bind(name, obj, attrs) | javaContainer + 自定義 | 同時創建父條目與對象 |
| 編組對象 | bind(name, MarshalledObject) | javaMarshalledObject | RMI/遠程傳輸兼容 |
啟動 JXplorer 連接 ApacheDS,展開 ou=users → uid=alice 可直觀查看子條目結構與屬性值。
下篇將講解:基礎搜索、CN 模糊匹配、反序列化獲取對象、編組對象解編、更新操作,以及統一封裝類 LDAP4JavaObjects 的完整實現。