![](/img/trans.png)
[英]Spring Boot injecting Map values from .properties and .yaml using ConfigurationProperties
[英]Spring Boot: read list from yaml using @Value or @ConfigurationProperties
我想從 yaml 文件 (application.yml) 中讀取主機列表,文件如下所示:
cors:
hosts:
allow:
- http://foo1/
- http://foo2/
- http://foo3/
(示例 1)
我使用的類定義了這樣的值:
@Value("${cors.hosts.allow}")
List<String> allowedHosts;
但是閱讀失敗,因為 Spring 抱怨這個:
java.lang.IllegalArgumentException:無法解析字符串值“${cors.hosts.allow}”中的占位符“cors.hosts.allow”
當我像這樣更改文件時,可以讀取該屬性,但自然它不包含列表,而只包含一個條目:
cors:
hosts:
allow: http://foo1, http://foo2, http://foo3
(我知道我可以將這些值作為一行讀取並用","
將它們分開","
但我還不想尋求解決方法)
這也不起作用(盡管我認為根據snakeyamls docs這應該是有效的):
cors:
hosts:
allow: !!seq [ "http://foo1", "http://foo2" ]
(跳過!!seq
並僅使用[
/ ]
也是失敗的)
我在這里閱讀了涉及使用@ConfigurationProperties
的建議,並將示例轉移到 Java 並將其與您在 Example1 中看到的 yaml 文件一起使用:
@Configuration
@EnableWebMvc
@ConfigurationProperties(prefix = "cors.hosts")
public class CorsConfiguration extends WebMvcConfigurerAdapter {
@NotNull
public List<String> allow;
...
當我運行這個時,我收到了這個投訴:
org.springframework.validation.BindException: org.springframework.boot.bind.RelaxedDataBinder$RelaxedBeanPropertyBindingResult: 1 個錯誤字段“允許”對象“cors.hosts”中的字段錯誤:拒絕值[null]; 代碼 [NotNull.cors.hosts.allow,NotNull.allow,NotNull]; 參數 [org.springframework.context.support.DefaultMessageSourceResolvable: 代碼 [cors.hosts.allow,allow]; 參數 ts []; 默認消息 [允許]];
我搜索了其他方法來配置我的 CORS 主機並發現了這個Spring Boot 問題,但由於尚未完成,我無法將其用作解決方案。 所有這些都是通過 Spring Boot 1.3 RC1 完成的
所以,你有這樣一個yaml:
cors:
hosts:
allow:
- http://foo1/
- http://foo2/
- http://foo3/
然后首先綁定數據
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix="cors.hosts")
public class AllowedHosts {
private List<String> HostNames; //You can also bind more type-safe objects
}
然后在另一個組件中你做
@Autowired
private AllowedHosts allowedHosts;
你完成了!
在application.yml中使用逗號分隔值
corsHostsAllow: http://foo1/, http://foo2/, http://foo3/
用於訪問的java代碼
@Value("${corsHostsAllow}")
String[] corsHostsAllow
我嘗試過並且成功了;)
我已經能夠從以下屬性中讀取列表 -
屬性 -
cors.hosts.allow[0]=host-0
cors.hosts.allow[1]=host-1
閱讀財產 -
@ConfigurationProperties("cors.hosts")
public class ReadProperties {
private List<String> allow;
public List<String> getAllow() {
return allow;
}
public void setAllow(List<String> allow) {
this.allow = allow;
}
}
我遇到了同樣的問題,但解決了,給你我的解決方案
exclude-url: >
/management/logout,
/management/user/login,
/partner/logout,
/partner/user/login
Spring boot 2.1.6.RELEASE版本成功
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.