Can a spring ldap repository project access two different ldap directories?

╄→гoц情女王★ 提交于 2019-12-12 03:04:16

问题


I am trying to create a spring rest application to return values that may come from two different ldap directory servers. Is this possible using spring ldap repositories? Is it possible to create more than one ldaptemplate and contextsource so I can query both directories?


回答1:


You can configure separate ldapTemplate and contextSource beans for each LDAP directory.

You can refer to the following basic configuration (JavaConfig);

@Configuration
@EnableLdapRepositories(basePackages = "com.foo.ldap1.repositories", ldapTemplateRef="ldapTemplate1")
public class Ldap1Configuration {

    @Autowired
    Environment env;

    @Bean
    public LdapContextSource contextSource1() {
        LdapContextSource contextSource= new LdapContextSource();
        contextSource.setUrl(env.getRequiredProperty("ldap1.url"));
        contextSource.setBase(env.getRequiredProperty("ldap1.base"));
        contextSource.setUserDn(env.getRequiredProperty("ldap1.user"));
        contextSource.setPassword(env.getRequiredProperty("ldap1.password"));
        return contextSource;
    }

    @Bean(name="ldapTemplate1")
    public LdapTemplate ldapTemplate1() {
        return new LdapTemplate(contextSource1());        
    }
}
@Configuration
@EnableLdapRepositories(basePackages = "com.foo.ldap2.repositories", ldapTemplateRef="ldapTemplate2")
public class Ldap2Configuration {
    @Bean
    public LdapContextSource contextSource2() {
        LdapContextSource contextSource= new LdapContextSource();
        contextSource.setUrl(env.getRequiredProperty("ldap2.url"));
        contextSource.setBase(env.getRequiredProperty("ldap2.base"));
        contextSource.setUserDn(env.getRequiredProperty("ldap2.user"));
        contextSource.setPassword(env.getRequiredProperty("ldap2.password"));
        return contextSource;
    }

    @Bean(name="ldapTemplate2")
    public LdapTemplate ldapTemplate2() {
        return new LdapTemplate(contextSource2());        
    }

}

Then you can refer to each instance in your application as per following;

@Autowired
@Qualifier("ldapTemplate1")
private LdapTemplate ldapTemplate1;
@Autowired
@Qualifier("ldapTemplate2")
private LdapTemplate ldapTemplate2;

Side note; If the number of LDAP directories increases then it will be better to implement a ldaptemplate factory which takes connection details and returns ldaptemplate instances (example).



来源:https://stackoverflow.com/questions/37735585/can-a-spring-ldap-repository-project-access-two-different-ldap-directories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!