我有一個小小的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