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
版权声明:本文标题:java - Dynamically configure LdapTemplate at runtime in Spring Boot - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736686414a1947688.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论