Monday, June 16, 2008

Spring & LDAP

Just like you have JDBC/Hibernate/iBatis templates in Spring, we also have an LDAPTemplate. You can download the spring LDAP library from I like this template approach simply because it lets us avoid common pitfalls such as not cleaning up resources after using an API (in JDBC its the connection, statement and resultset). Why bother when the template can do this for you. Same holds true for LDAP queries.
For this example I had the following setup:

  • Apache Directory Server 1.5.2. I decided to use the sample directory data.
  • Installed the Apache Directory Studio eclipse plugin.
To confirm your setup. Open eclipse and go to the LDAP perspective. Create a new connection with following information:
  • hostname - localhost
  • port - 10389
  • Bind DN or user - uid=admin,ou=system
  • password - secret (this is the default password for apache ds)
This should let you into the directory. Under dc=example,dc=com I added two organizations (asia and americas).

Now for the Spring stuff. 

package trial;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
public class LDAPSampleImpl implements LDAPSample {

private LdapTemplate ldapTemplate;

public List getOrgNames() {
return ldapTemplate.list("");

The spring XML file looks like:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=""

<context:annotation-config />
<context:component-scan base-package="trial" />

<bean id="ldapContextSource"
<property name="url" value="ldap://localhost:10389" />
<property name="base" value="dc=example,dc=com" />
<property name="userDn" value="uid=admin,ou=system" />
<property name="password" value="secret" />

<bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg ref="ldapContextSource" />

Everything above is self explanatory. Now for the test case to execute all of this.

package trial;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = { "classpath:spring-context.xml" })
public class DriverTestCase {

private LDAPSample ldap;
public void testGreeting() {

Running this unit test results in output
>> [ou=asia, ou=americas]

No comments: