使用 Spring LDAP 读取数据并映射到 Java Bean 中
写此小文总结一下平时工作的收获。
入正题,工作涉及到了对 LDAP 的 CRUD 操作,不忍同事用 JLDAP 写的冗长代码(主要并不是 JLDAP 的错。冗长代码问题可以通过代码重构和 Java 反射去解决)。后发现 Spring LDAP 是用来写 LDAP 相关程序的一个不错的选择之一(并没有深入了解别的框架)。直接上代码,希望能给同样需要操作 LDAP 的朋友一些帮助:
LdapTemplate ldapTemplate = buildLdapTemplate();AndFilter filter = new AndFilter();filter.and(new EqualsFilter("oacAttrMsisdn", "1"));filter.and(new EqualsFilter("oacAttrCategory", "UserProfileRule"));List list = ldapTemplate.search("oacAttrCategory=UserProfileRule",filter.encode(), new BeanAttributesMapper(new UserProfileRule()));private static LdapTemplate buildLdapTemplate() throws Exception {LdapContextSource contextSource = new LdapContextSource();contextSource.setUrl("ldap://localhost:389");contextSource.setBase("dc=example,dc=com");contextSource.setUserDn("cn=Directory Manage");contextSource.setPassword("ds");contextSource.afterPropertiesSet();LdapTemplate ldapTemplate = new LdapTemplate();ldapTemplate.setContextSource(contextSource);return ldapTemplate;}public class BeanAttributesMapper implements AttributesMapper {private List<String> skipAttrs;private Object bean;public Object mapFromAttributes(Attributes attributes)throws NamingException {NamingEnumeration attrEnumeration = attributes.getAll();while (attrEnumeration.hasMore()) {Attribute attr = (Attribute) attrEnumeration.next();System.out.println(attr.getID() + " : " + attr.get());String ldapAttr = attr.getID().replace("oacAttr", "");if (!skipAttrs.contains(ldapAttr))setProperty(bean, attr.getID().replace("oacAttr", ""),attr.get());}return bean;}public void setProperty(Object bean, String name, Object value) {String setterName = "set" + StringUtils.capitalize(name);Method setter;try {setter = bean.getClass().getMethod(setterName, value.getClass());setter.invoke(bean, value);} catch (Exception e) {throw new RuntimeException(e);}}}