我有一个小小的SpringBoot应用程序,它可以通过OpenLdap执行不同的功能。SpringBoot Configuration with application.yml
getUser
createUser
deleteUser
etc.
这工作正常。现在我想创建一个application.Yml,我可以用不同的凭据来管理不同的环境。我阅读了一些教程,但我仍然有一些理解问题。其实我的代码看起来像这样:
UserController中:
...
protected static String serverURL = "xxxxx:90xx";
protected static String LdapBindDn = "cn=admin, xxxxx";
protected static String LdapPassword = "xxxx";
...
@RequestMapping(value = "/{userid:.+}",method = RequestMethod.GET,consumes="application/json",produces = "application/json")
public UserData getUser(@PathVariable String userid) {
DirContext context = connectToLdap();
//some operations...
context.close();
return user;
}
... // same for the other functions
我的计划是现在,我想在一个额外的application.yml而不是在UserController中的开始(见上文)指定的凭据。
以后,我在src /主/资源创建的application.yml:
# Actual environment
spring:
profiles.actives: development
---
# Dev Profile
spring:
profiles: dev
datasource:
serverUrl: ldaps://xxxxxx:90xx
AdminName: xxxx
AdminPassword: xxxxxx
BaseDN: xxxxx
---
# Production Profile
spring:
profiles: prod
datasource:
serverUrl: ldaps://xxxx2:90xx
AdminName: xxxxx2
AdminPassword: xxxxx2
BaseDN: xxxxxx
现在我需要调用此配置。我已经阅读过一篇教程(http://therealdanvega.com/blog/2017/06/26/spring-boot-configuration-using-yaml),我必须为.yml文件的属性创建额外的类“ApplicationProperties”。
@Component
@ConfigurationProperties("datasource")
public class ApplicationProperties {
private String serverURL;
private String adminName;
private String adminPassword;
private String baseDN;
// Getter-/Setter-Methods
}
现在,我需要从从.yml值开始定义我的变量,对不对?我回到我的UserController并尝试类似这样的:
private String serverURL;
private String adminName;
private String adminPassword;
private String baseDN;
@Autowired
ApplicationProperties appProp;
@RequestMapping(value = "/{userid:.+}",method = RequestMethod.GET,consumes="application/json",produces = "application/json")
public UserData getUser(@PathVariable String userid) {
DirContext context = connectToLdap();
//some operations...
context.close();
return user;
}
... // same for the other functions
private DirContext connectToLdap(){
System.out.prinln(appProp.getServerURL());
System.out.prinln(appProp.getAdminName());
System.out.prinln(appProp.getAdminPassword());
.... // Code for the Ldap connection
}
但变量“appProp”仍为空。我知道,这是一个很大的理解问题。我不知道如何从.yml文件调用这些属性。
感谢您提前给予的帮助!
[spring-boot config](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config。HTML)你可以在这里的详细信息像配置文件特定的配置,如何在你的班级使用,等 – fiskra
感谢您的链接。但我已经读过这个。 有人可以告诉我,我在代码中的错误理解是哪里? – InfoEngi
首先,您可以创建基于配置文件的属性,因为spring boot会自动选择它们,比如'application- {profile}。{properties | yml}' – fiskra