簡體   English   中英

在 spring boot @Configuration/@ConfigurationProperties 中使用不同的前綴

[英]Use different prefixes in spring boot @Configuration/@ConfigurationProperties

我有 spring boot 應用程序和具有此類配置的.yaml文件:

storage:
  path: C:\\path\\example
cache:
  durtion: 60

我需要一個包含緩存和存儲的類。 我認為 @ConfigurationProperties 會幫助我,但我唯一能用這個注釋做的就是創建兩個不同的類:

@Component
@ConfigurationProperties(prefix = "storage")
public class ConfigA(){
     @Getter
     @Setter
     private String path;
}
...

@Component
@ConfigurationProperties(prefix = "cache")
public class ConfigB(){
     @Getter
     @Setter
     private int duration;
}

如何將ConfigAConfigB組合在一個類中? 不使用@Value嗎? 更新:我已經設法做這樣的事情,但我不確定這是最好的方法:

@Configuration
public class ValuesConfig {

    @Bean
    @ConfigurationProperties(prefix = "cache")
    public Cache cache(){
        return new Cache();
    }

    @Component
    public static class Cache{
        @Getter
        @Setter
        private int duration;
    }

}

您可以有一個不帶前綴的“全局”配置,SpringBoot 將嘗試從所有屬性的“根”中實現它


public class StorageConfig(){
     @Getter
     @Setter
     private String path;
}

public class CacheConfig(){
     @Getter
     @Setter
     private int duration;
}

@Component
@ConfigurationProperties
public class GlobalConfig(){
     @Getter
     @Setter
     private StorageConfig storage;
     @Getter
     @Setter
     private CacheConfig cache;
}

當您使用@Component注釋您的配置時,它們可以像任何其他組件一樣注入,因此您只需注入即可訪問它們所擁有的屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM