我導入了一個具有某些@Value字段服務的依賴項。在我的 spring boot 應用程序中,我不使用這些服務,但我仍然使用此依賴項中的其他一些類,現在如果我運行我的應用程序,它將失敗,因為它無法解析占位符,例如引起:java.lang.IllegalArgumentException:無法解析值“${apn.authentication.token.teamId}”中的占位符“apn.authentication.token.teamId”所以為了解決這個問題,我必須在我的屬性中定義值。我搜索了一個設置,讓我的應用程序不會因未知值而失敗,但我找不到辦法做到這一點。即使缺少值,有沒有辦法讓我的 Spring Boot 應用程序啟動?或者我應該排除我不使用的類(如果這是唯一的選擇怎么辦)?
2 回答

慕田峪4524236
TA貢獻1875條經驗 獲得超5個贊
您可以設置一些默認值,以便如果該值不存在,則采用默認值
@Value("${apn.authentication.token.teamId:-99}") private int teamId;
或將值設置為空
@Value("${apn.authentication.token.teamId:#{null}}") private Integer teamId;

梵蒂岡之花
TA貢獻1900條經驗 獲得超5個贊
您可以將您的配置配置PropertySourcesPlaceholderConfigurer為不會在未知占位符上失?。?/p>
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertySourcesPlaceholderConfigurer;
}
它不會失敗,也不會費心去解決它。通常,在未知屬性(它們是屬性,因為您的應用程序需要它們運行)或添加它們的默認值時失敗是一種很好的做法。如果您的配置對您的應用程序運行不重要,您可以創建一個額外的配置文件并在運行時讀取它。