无法使用 Spring Boot 从 YAML 文件加载属性。

huangapple go评论73阅读模式
英文:

Unable to load properties from yaml file using spring boot

问题

以下是我的(policies.yml)yaml文件,我想通过Spring将其解析/映射到类:

urls:
  - url: url1
    actions:
      - action: acton1
        domains:
          - domain: domain1
      - action: action2
        domains:
          - domain: domain1
      
  - url: url2
    actions:
      - action: acton1
        domains:
          - domain: domain1
      - action: action2
        domains:
          - domain: domain1

这是我的配置类,用于加载yaml文件:

@Component
@EnableConfigurationProperties
@PropertySource(value = "classpath:policies.yml")
@ConfigurationProperties("urls")
public class SecurityURLConfigs {    
    private List<Url> urls = null;    
}

public class Url {
    private String url;
    private List<Action> actions = null;
}

public class Action {
    private String action;
    private List<Domain> domains = new ArrayList<Domain>();
}

public class Domain {
    private String domain;
}

但是这个配置没有从yaml文件中加载属性。有谁能指导一下这段代码有什么问题。

英文:

Below is my (policies.yml) yaml file in which I want to parse/map to classes through spring.

urls:
  - url: url1
    actions:
      - action: acton1
        domains:
          - domain: domain1
      - action: action2
        domains:
          - domain: domain1
  
  - url: url2
    actions:
      - action: acton1
        domains:
          - domain: domain1
      - action: action2
        domains:
          - domain: domain1

this is my configuration class to load yaml file.

@Component
@EnableConfigurationProperties
@PropertySource(value = &quot;classpath:policies.yml&quot;)
@ConfigurationProperties(&quot;urls&quot;)
public class SecurityURLConfigs {	
    private List&lt;Url&gt; urls = null;	
}

public class Url{
   private String url;
   private List&lt;Action&gt; actions = null;
}

public class Action {
    private String action;	
 	private List&lt;Domain&gt; domains = new ArrayList&lt;Domain&gt;();	
}

public class Domain {
    private String domain;
}

but this configuration isn't loading properties from yaml file. Can anybody guide whats wrong in this code.

答案1

得分: 1

你写道你的配置文件名为 policies.yml,但在代码中尝试加载的是 framepolicies.yml

另外,你将 urls 属性设置为根级别,但在类内部尝试获取它。我认为你应该尝试设置 @ConfigurationProperties(""),或者将 urls 块移动到另一个内部,并设置 @ConfigurationProperties("另一个")

英文:

You wrote your config file is named policies.yml, but in the code you try to load framepolicies.yml.

Also you set urls property as root, but try to get it inside class. I think you should either try to set @ConfigurationProperties(&quot;&quot;) or move the urls block inside another and set @ConfigurationProperties(&quot;another&quot;).

huangapple
  • 本文由 发表于 2020年10月2日 00:21:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64159453.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定