亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法使用@Bean 和@ConfigurationProperties 綁定屬性

無法使用@Bean 和@ConfigurationProperties 綁定屬性

UYOU 2023-04-26 10:45:27
我正在從屬性文件中讀取配置?,F在我有一個錯誤,我認為它與 spring bean 的初始化順序有關。如果我這樣做 private Map name = new HashMap<>(); 它可以從屬性文件中成功加載。但現在我無法將屬性綁定到 ServiceNameConfig我不知道為什么會發生這種情況以及如何處理它。@ConfigurationProperties(prefix = "amazon.service")@Configuration@EnableConfigurationProperties(ServiceNameConfig.class)public class ServiceNameConfig {   //If I do private Map<String, String> name = new HashMap<>(); It can be successfully load from properties file.    private Map<String, String> name;    @Bean(value = "serviceName")    public Map<String, String> getName() {        return name;    }    public void setName(Map<String, String> name) {        this.name = name;    }} 它的用法;@Autowired@Qualifier("serviceName")Map<String, String> serviceNameMap;
查看完整描述

1 回答

?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

您可以將配置類替換為這樣(更簡單);


@Configuration

public class Config {


? ? @Bean

? ? @ConfigurationProperties(prefix = "amazon.service")

? ? public Map<String, String> serviceName() {

? ? ? ? return new HashMap<>();

? ? }

}

對于@ConfigurationProperties注入,您需要提供一個空的 bean 對象實例。


或者另一種方法,您可以使用 pojo 類來處理配置。例如;


你有這樣的屬性;


amazon:

? service:

? ? valueA: 1

? ? valueB: 2

? ? details:

? ? ? valueC: 3

? ? ? valueD: 10

您可以使用如下的 pojo;


class Pojo {


? ? private Integer valueA;

? ? private Integer valueB;

? ? private Pojo2 details;


? ? // getter,setters


? ? public static class Pojo2 {


? ? ? ? private Integer valueC;

? ? ? ? private Integer valueD;


? ? ? ? // getter,setters

? ? }

}

并在配置類中使用它;


@Configuration

public class Config {


? ? @Bean

? ? @ConfigurationProperties(prefix = "amazon.service")

? ? public Pojo serviceName() {

? ? ? ? return new Pojo();

? ? }

}


查看完整回答
反對 回復 2023-04-26
  • 1 回答
  • 0 關注
  • 253 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號