Spring boot Ldap查询-使用Spring引导进行配置
我有一个Spring引导应用程序,需要执行LDAP查询。我试图从Spring boot文档中获得以下建议: “许多Spring配置示例已发布在 使用XML配置的Internet。请始终尝试使用等效配置 Java基本配置(如果可能)。” 在Spring XML配置文件中,我会使用:Spring boot Ldap查询-使用Spring引导进行配置,spring-boot,spring-ldap,Spring Boot,Spring Ldap,我有一个Spring引导应用程序,需要执行LDAP查询。我试图从Spring boot文档中获得以下建议: “许多Spring配置示例已发布在 使用XML配置的Internet。请始终尝试使用等效配置 Java基本配置(如果可能)。” 在Spring XML配置文件中,我会使用: <ldap:context-source url="ldap://localhost:389" base="cn=Users,dc=test,dc=local"
<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、base、username和password属性。
XML标记生成一个LdapContextSource
bean,
XML标记生成一个LdapTemplate
bean,这就是您在Java配置中需要做的:
@配置
@启用自动配置
@EnableConfigurationProperties
公共类应用程序{
公共静态void main(字符串[]args){
SpringApplication.run(Application.class,args);
}
@豆子
@ConfigurationProperties(前缀=“ldap.contextSource”)
公共LdapContextSource上下文源(){
LdapContextSource contextSource=新的LdapContextSource();
返回contextSource;
}
@豆子
公共LdapTemplate LdapTemplate(ContextSource ContextSource){
返回新的LdapTemplate(contextSource);
}
@豆子
public PersonRepoImpl personRepo(LdapTemplate LdapTemplate){
PersonRepoImpl personRepo=新的PersonRepoImpl();
personRepo.setLdapTemplate(ldapTemplate);
归还人回购;
}
}
为了允许您在不重建代码的情况下更改配置,我使用了SpringBoot的。这将在应用程序的环境中查找前缀为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
在XML中,您可以使用:
<bean id="ldapContextSource"
class="org.springframework.ldap.core.support.LdapContextSource">
<property name="url" value="<URL>" />
<property name="base" value="<BASE>" />
<property name="userDn" value="CN=Bla,OU=com" />
<property name="password" value="<PASS>" />
<property name="referral" value="follow" />
</bean>
<bean id="ldapTemplate"
class="org.springframework.ldap.core.LdapTemplate"
depends-on="ldapContextSource">
<constructor-arg index="0" ref="ldapContextSource" />
<property name="ignorePartialResultException" value="true"/>
</bean>
<bean id="personRepo" class="com.llpf.ldap.PersonRepoImpl">
<property name="ldapTemplate" ref="ldapTemplate" />
</bean>
我希望有帮助 奇数-如果我创建一个yaml配置文件,我无法让它工作-当我创建一个属性配置时,它可以正常工作。它也可以与yaml配置文件一起工作<代码>ldap.contextSource:url:ldap://localhost:389 base:cn=Users,dc=test,dc=localuserdn:cn=testUser password:testPass不需要第三个bean,如果不使用它,repo不需要公共修饰符,但可以保留在包范围内(更适合域驱动设计)如果没有上面的第三个
@bean
方法,如何创建问题XML配置中的personRepo
bean?这没有帮助。这完全不是他想要的。