gpt4 book ai didi

spring-boot - Ldap查询-使用Spring Boot进行配置

转载 作者:行者123 更新时间:2023-12-03 14:10:34 25 4
gpt4 key购买 nike

我有一个需要执行LDAP查询的Spring Boot应用程序。我正在尝试从Spring引导文档中获取以下建议:

"Many Spring configuration examples have been published on the Internet that use XML configuration. Always try to use the equivalent Java-base configuration if possible."



在Spring XML配置文件中,我将使用:
 <ldap:context-source
url="ldap://localhost:389"
base="cn=Users,dc=test,dc=local"
username="cn=testUser"
password="testPass" />

<ldap:ldap-template id="ldapTemplate" />

<bean id="personRepo" class="com.llpf.ldap.PersonRepoImpl">
<property name="ldapTemplate" ref="ldapTemplate" />
</bean>

如何使用基于Java的配置进行配置?我需要无需更改代码即可更改ldap:context-source的URL,基本,用户名和密码属性。

最佳答案

<ldap:context-source> XML标记生成一个LdapContextSource bean,而<ldap:ldap-template> XML标记生成一个LdapTemplate bean,因此您需要在Java配置中执行以下操作:

@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties
public class Application {

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

@Bean
@ConfigurationProperties(prefix="ldap.contextSource")
public LdapContextSource contextSource() {
LdapContextSource contextSource = new LdapContextSource();
return contextSource;
}

@Bean
public LdapTemplate ldapTemplate(ContextSource contextSource) {
return new LdapTemplate(contextSource);
}

@Bean
public PersonRepoImpl personRepo(LdapTemplate ldapTemplate) {
PersonRepoImpl personRepo = new PersonRepoImpl();
personRepo.setLdapTemplate(ldapTemplate);
return personRepo;
}
}

为了使您无需重新构建代码即可更改配置,我使用了Spring Boot的 @ConfigurationProperties 。这将在您的应用程序环境中查找以 ldap.contextSource开头的属性,然后通过调用匹配的setter方法将其应用于 LdapContextSource Bean。要应用问题中的配置,可以使用具有四个属性的 application.properties文件:
ldap.contextSource.url=ldap://localhost:389
ldap.contextSource.base=cn=Users,dc=test,dc=local
ldap.contextSource.userDn=cn=testUser
ldap.contextSource.password=testPass

关于spring-boot - Ldap查询-使用Spring Boot进行配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26004062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com