我正在嘗試讀取屬性檔案中的值。為什么我在輸出中得到值:[]?
abc.env[0].envname=test
abc.env[0].grant_type=password
abc.env[1].envname=dev
abc.env[1].grant_type=password
下面是我正在嘗試執行的課程
@SpringBootApplication
public class AbcApplication implements CommandLineRunner{
private static Logger LOG = LoggerFactory.getLogger(AbcApplication.class);
@Autowired
ReadAbcApplicationProperties readAbcApplicationProperties;
public static void main(String[] args) {
SpringApplication.run(AbcApplication.class, args);
}
@Override
public void run(String... args) {
LOG.info("values: {}", readAbcApplicationProperties.getAbcSources());
}
}
@Component
@ConfigurationProperties(prefix = "abc")
public class ReadAbcApplicationProperties {
private List<AbcProperties> abcSources = new ArrayList<AbcProperties>();
@Autowired
ReadAbcApplicationProperties readAbcApplicationProperties;
public List<AbcProperties> getAbcSources() {
return abcSources;
}
public void setAbcSources(List<AbcProperties> abcSources) {
this.abcSources = abcSources;
}
}
public class AbcProperties {
private String envname;
private String tokenGrantType;
public String getEnvname() {
return envname;
}
public void setEnvname(String envname) {
this.envname = envname;
}
public String getTokenGrantType() {
return tokenGrantType;
}
}
有人可以幫我解決缺失的部分嗎?
uj5u.com熱心網友回復:
您的代碼中存在一些不一致之處..
ReadAbcApplicationProperties- 你為什么把自己注射進去?@Autowired ReadAbcApplicationProperties readAbcApplicationProperties;必須洗掉此行。
欄位
private String tokenGrantType與abc.env[0].grant_type屬性檔案中的不一致private List<AbcProperties> abcSources與屬性檔案中的abc.env[0]andabc.env[1]和 ...不一致abc.env[X]
這些課程應該是:
屬性
public class AbcProperties {
private String envname;
private String grantType; //to match `grant_type` in .properties file
//getters setters
}
讀取應用程式屬性
@ConfigurationProperties(prefix = "abc")
public class ReadAbcApplicationProperties {
private List<AbcProperties> env = new ArrayList<>(); //to match abc.env[X] in properties file
// getters setters
}
我在 spring-boot 示例專案中嘗試了上述方法并且它有效

uj5u.com熱心網友回復:
您在屬性檔案和相應的 bean 類中有不同的屬性名稱AbcProperties。見tokenGrantType和grant_type。
理想的配置是:
抱歉使用 yml 檔案而不是屬性,但它的行為都是一樣的。它只是yml會給我們更多的可讀性。
myapp: # this can be your prefix
abc:
-
envname: test
grant_type: password
-
envname: dev
grant_type: password
將“myapp”作為前綴(頂級鍵),woudl 使您能夠在單個類中添加任意數量的屬性,如下面的“ConfigPropertiesBinder”。
@Data // If not, include getter and setters, with cons.
@RefreshScope
@Configuration
@ConfigurationProperties(prefix = "myapp")
public class ConfigPropertiesBinder {
private List<AbcProperties> abc; // Should match with myapp.abc
// Other properties
}
@Data
public class AbcProperties{
private String envname; // Match with myapp.abc[x].envname
private String grantType; // '-' and '_' converts to camelcase
}
看看它是否有幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314175.html
