Spring LDAP Mapping Attributes to POJO with AttributesMapper Example

摘要: This tutorial demonstrates how to use spring LDAP to map attributes on a POJO using the AttributesMapper<T> class.

This tutorial demonstrates how to use spring LDAP to map attributes on a POJO using the AttributesMapper<T> class.

Maven Dependencies

We use Apache Maven to manage our project dependencies. Add the following dependencies to your project.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

    <name>Spring LDAP - ${project.artifactId}</name>





Configure Embedded LDAP Server using application.yml

We use spring boot to create and configure our embedded LDAP server. The following properties create an LDAP server running on port 12345 and populates the LDAP server using the schema.ldif which resides on the class-path.

# Spring LDAP Mapping Attributes to POJO with AttributesMapper  configuration application.yml


    # Spring LDAP
    # In this example we use an embedded ldap server. When using a real one,
    # you can configure the settings here.
    # urls: ldap://localhost:12345
    # base: dc=memorynotfound,dc=com
    # username: uid=admin
    # password: secret

    # Embedded Spring LDAP
      base-dn: dc=memorynotfound,dc=com
        username: uid=admin
        password: secret
      ldif: classpath:schema.ldif
      port: 12345
        enabled: false

Populate LDAP Server

The LDAP servers gets populated using the following schema.ldif file.

dn: dc=memorynotfound,dc=com
objectclass: top
objectclass: domain
objectclass: extensibleObject
dc: memorynotfound

# Organizational Units
dn: ou=groups,dc=memorynotfound,dc=com
objectclass: top
objectclass: organizationalUnit
ou: groups

dn: ou=people,dc=memorynotfound,dc=com
objectclass: top
objectclass: organizationalUnit
ou: people

# Create People
dn: uid=john,ou=people,dc=memorynotfound,dc=com
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: John Doe
sn: John
uid: john
password: secret

dn: uid=jihn,ou=people,dc=memorynotfound,dc=com
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Jihn Die
sn: Jihn
uid: jihn
password: secret

dn: uid=jahn,ou=people,dc=memorynotfound,dc=com
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Jahn Dae
sn: Jahn
uid: jahn
password: secret

# Create Groups
dn: cn=developers,ou=groups,dc=memorynotfound,dc=com
objectclass: top
objectclass: groupOfUniqueNames
cn: developers
ou: developer
uniqueMember: uid=john,ou=people,dc=memorynotfound,dc=com
uniqueMember: uid=jihn,ou=people,dc=memorynotfound,dc=com

dn: cn=managers,ou=groups,dc=memorynotfound,dc=com
objectclass: top
objectclass: groupOfUniqueNames
cn: managers
ou: manager
uniqueMember: uid=jahn,ou=people,dc=memorynotfound,dc=com

Bootstrap Spring Application

We bootstrap our application using spring boot. When the application is initialized, we invoke some methods that’ll query the LDAP server.

package com.memorynotfound.ldap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.annotation.PostConstruct;
import java.util.List;

public class Application {

    private static Logger log = LoggerFactory.getLogger(Application.class);

    private static final String BASE = "dc=memorynotfound,dc=com";

    private PersonRepository personRepository;

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);

    public void setup(){
        log.info("Spring LDAP Mapping Attributes to POJO with AttributesMapper Example");

        List names = personRepository.getAllPersonNames();
        log.info("names: " + names);

        List persons = personRepository.getAllPersons();
        log.info("persons: " + persons);

        Person person = personRepository.findPerson("uid=john,ou=people," + BASE);
        log.info("person: " + person);



Person POJO

A simple Person POJO which represents a person object in the LDAP server. We are using this POJO to map our person attributes from the LDAP server.

package com.memorynotfound.ldap;

public class Person {

    private String fullName;
    private String lastName;

    public Person() {

    public Person(String fullName, String lastName) {
        this.fullName = fullName;
        this.lastName = lastName;

    public String getFullName() {
        return fullName;

    public void setFullName(String fullName) {
        this.fullName = fullName;

    public String getLastName() {
        return lastName;

    public void setLastName(String lastName) {
        this.lastName = lastName;

    public String toString() {
        return "Person{" +
                "fullName='" + fullName + '\'' +
                ", lastName='" + lastName + '\'' +

Spring LDAP Mapping Attributes to POJO with AttributesMapper Example

The inline implementation of AttributesMapper in the getAllPersonNames() method just gets the desired attribute value from the Attributes and returns it. Internally, LdapTemplate iterates over all entries found, calling the given AttributesMapper for each entry, and collects the results in a list. The list is returned by the search method.

Note that the AttributesMapper implementation could be modified to return a full Person object.

Entries in LDAP are uniquely identified by their distinguished name (DN). If you have the DN of an entry, you can retrieve the entry directly without searching for it. This is called a lookup in Java LDAP. The findPerson() method demonstrates a lookup for a Person object.

package com.memorynotfound.ldap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.stereotype.Service;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import java.util.List;
import static org.springframework.ldap.query.LdapQueryBuilder.query;

public class PersonRepository {

    private LdapTemplate ldapTemplate;

     * Retrieves all the persons in the ldap server, but we need to map each attribute individually
     * @return list of person names
    public List getAllPersonNames() {
        return ldapTemplate.search(
                new AttributesMapper() {
                    public String mapFromAttributes(Attributes attrs)
                            throws NamingException {
                        return (String) attrs.get("cn").get();

     * Retrieves all the persons in the ldap server, using {@link PersonAttributesMapper}
     * @return list of persons
    public List getAllPersons() {
        return ldapTemplate.search(query()
                .where("objectclass").is("person"), new PersonAttributesMapper());

     * Searching for one person, using {@link PersonAttributesMapper}
     * @param dn distinguaged name for the person
     * @return person
    public Person findPerson(String dn) {
        return ldapTemplate.lookup(dn, new PersonAttributesMapper());

     * Custom person attributes mapper, maps the attributes to the person POJO
    private class PersonAttributesMapper implements AttributesMapper {
        public Person mapFromAttributes(Attributes attrs) throws NamingException {
            Person person = new Person();
            return person;


The previous application will print the following output to the console.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 :: Spring Boot ::        (v1.5.7.RELEASE)

2017-10-02 10:58:19.462  INFO 8760 --- [main] com.memorynotfound.ldap.Application: Spring LDAP - attributesMapper Example
2017-10-02 10:58:19.499  INFO 8760 --- [main] com.memorynotfound.ldap.Application: names: [Jahn Dae, Jihn Die, John Doe]
2017-10-02 10:58:19.502  INFO 8760 --- [main] com.memorynotfound.ldap.Application: persons: [Person{fullName='Jahn Dae', lastName='Jahn'}, Person{fullName='Jihn Die', lastName='Jihn'}, Person{fullName='John Doe', lastName='John'}]
2017-10-02 10:58:19.504  INFO 8760 --- [main] com.memorynotfound.ldap.Application: person: Person{fullName='John Doe', lastName='John'}


上一篇: Spring LDAP CRUD Operations Binding and Unbinding Example
下一篇: Spring LDAP + Spring Boot Embedded LDAP Configuration Example
 评论 ( What Do You Think )


  • 微信公众号

  • 我的微信


1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号