admin管理员组

文章数量:1126458

What is the best way to go about creating and configuring an LdapTemplate dynamically at runtime?

This is not exactly my use-case, but to keep my business logic from confusing the issue, lets imagine a simple requirement. You want to create a web page where a user can enter and LDAP URL, service account, password and base DN and a user ID they wish to search for. What would be the best way to handle this in Spring Boot using an LdapTemplate?

For a single LDAP source we can just set the Spring Boot properties for the URL, service account, password and base DN. To handle multiple LDAP sources I have seen examples of creating configuration classes to provide different ContextSources. But that solution assumes you know the LDAP servers you will be using ahead of time. In my example above the user can enter anything they want.

I have seen a couple suggestions like the one below. But these are definitely not the right way to do it. It technically works, but changing the LdapContextSource associated to the singleton LdapTemplate has a number of issues. Any other beans that are using LdapTemplate would have no idea how it's configured at the moment they use it. Even if it's only used in this one service bean, the web page could be used by multiple users at the same time.

@Service
public class DirectoryService {

    @Autowired
    ApplicationContext applicationContext;

    public void lookupUser(String userId, String url,
                           String ldapServiceUsername, 
                           String password, String base) {
         
          // Get the LdapTemplate configured to query a server based
          // on information the user input.
          LdapTemplate ldapTemplate = getLdapTemplateForServer(url, ldapServiceUsername, password, base);

          // Lookup the user and do something...

     }
    
     private LdapTemplate getLdapTemplateForServer(String url,
                                                   String ldapServiceUsername,
                                                   String password,
                                                   String base) {

        LdapTemplate ldapTemplate = (LdapTemplate)applicationContext.getBean("ldapTemplate");
        LdapContextSource contextSource =  (LdapContextSource)ldapTemplate.getContextSource();

        contextSource.setUrl(url);
        contextSource.setUserDn(ldapServiceUsername);
        contextSource.setPassword(password);               
        contextSource.setBase(base);

        contextSource.afterPropertiesSet();

        return ldapTemplate;
    }
}

本文标签: javaDynamically configure LdapTemplate at runtime in Spring BootStack Overflow