2017-09-05 36 views
2

是否有可能從application.yaml獲取自己的對象並將其與@Value綁定到我的組件?是否可以從彈簧應用程序屬性獲取自定義對象?

型號:

@Data 
public class CurrencyPlan { 
    private String id; 
    private String basePrice; 
    private String merchantId; 
} 

application.yml:

plans: 
    eur: 
    id: id 
    basePrice: 5 
    merchantId: someid 

我想要做的事:

@Value("${plans.eur}") CurrencyPlan eurPlan 

我能得到什麼:

java.lang.IllegalArgumentException: Could not resolve placeholder 'plans.eur' in value "${plans.eur}" 

這甚至有可能嗎?如果是這樣,怎麼做?我敢出出主意:(提前

感謝;)

+1

如果您將'application.yaml'重命名爲'application.yml',該怎麼辦?只是猜測,因爲[doc](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html)提到'.yml'擴展名。 – juzraai

+0

對不起,它是application.yml,我在創建問題時做了一個錯字 –

回答

4

如果你正在尋找你的屬性綁定到你可以使用@ConfigurationProperties類。

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties

@ConfigurationProperties(prefix="plans.eur")@Component將被放置在CurrencyPlan@EnableConfigurationProperties最好放在@Configuration類別上。

在您可以將CurrencyPlan類自動裝入依賴類後。

+0

但是有沒有一種注入方式就像普通對象而不是組件?看起來很奇怪我有這樣的類作爲組件 –

+0

你的意思是不是由春天管理?不可以。如果您在開始討論'@ EnableConfigurationProperties'註釋時閱讀文檔中的部分,則可以刪除組件方面,但它始終是一個彈簧管理bean來執行此操作。 –

+1

好吧,我給了它更多的想法,這個解決方案是我一直在尋找的,謝謝:) –

相關問題