Using DirContextSource with Spring LDAP

DirContextSource nicely intergrates with Spring LDAP by providing a thin wrapper around DirContextSource.Builder exposed as a ContextSource implementation: net.sf.michaelo.dirctxsrc.spring.DirContextSource.

Attention
Contrary to previous statements, this library has to reside in the webapp classpath along with its dependencies (spring-ldap-core 2.3.1.RELEASE+ and spring-beans 4.3.22.RELEASE+) to work properly.

In the first step, you have to tell Spring to create a bean and in the second step, let Spring autowire this bean to your class.

Add this to your beans.xml, e.g., root-context.xml or servlet-context.xml:

<beans …>
[…]
  <!-- Add this -->
  <beans:bean class="net.sf.michaelo.dirctxsrc.spring.DirContextSource">
    <beans:constructor-arg>
      <beans:array>
        <beans:value>ldap://hostname</beans:value>
      </beans:array>
    </beans:constructor-arg>
  </beans:bean>
[…]
</beans>

Now wire this to your class of choice:

[…]
  @Autowired
  private ContextSource contextSource;
  // Alternatively, you can use setter injection
[…]
  public void myMethod() {
    // Now use the context source as same as in a regular webapp along with the LdapTemplate
  }
[…]