[英]Spring Boot - Cannot read application.yml values from instantiated object
我正在嘗試使用 @ConfigurationProperties 注釋從 application.yml 讀取一些設置值。
TestClass
類的實例化對象使用了屬性類,所以我添加了@Configurable
注解,但properties
始終為null
,導致 NullpointerException。
屬性類:
@ConfigurationProperties
@Getter
@Setter
public class Properties {
private String setting;
}
以及使用屬性的對象:
@Configurable
public class TestClass{
@Autowired
private Properties properties;
void print(){
System.out.println(properties.getSetting());
}
}
如果我調用 print 方法,會發生NullPointerException
:
TestClass testClass = new TestClass();
testClass.print();
我錯過了什么嗎?
簡短的回答:
找到使用@SpringBootApplication
注釋的類,並在其中添加注釋@EnableConfigurationProperties(Properties.class)
@SpringBootApplication
@EnableConfigurationProperties(Properties.class)
public class ServiceLauncher {
解釋:
@ConfigurationProperties
不會將帶此注解的類注冊為 spring bean。 它僅用於 Spring 可以讀取帶有一些元配置信息的屬性(例如prefix = "some.prop.prefix"
)。
如果您希望將此類用作 spring bean(例如通過@Autowired
),您需要將上述注釋與@EnableConfigurationProperties
結合起來,然后告訴 spring 這個類必須成為一個 spring bean。
另一種解決方法:
您也可以只在 Properties 類上使用@Component
,這樣就足夠了,不需要@EnableConfigurationProperties
但后者是更好的做法。
@Component
@ConfigurationProperties
@Getter
@Setter
public class Properties {
編輯:在評論中澄清后,此代碼中還有另一個錯誤。 您應該將@Configurable
替換為@Configuration
。 第一個不在放置的類上創建spring bean!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.