首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring引导-嵌套配置属性不被识别

Spring引导-嵌套配置属性不被识别
EN

Stack Overflow用户
提问于 2022-02-10 14:51:01
回答 1查看 1.1K关注 0票数 2

正如标题所述,我的自定义属性在应用程序启动时没有注册。你介意看一下吗?

我的custom.yml

代码语言:javascript
复制
bridge:
  url: xxx
  authentication:
    auth-url: xxx
    user: xxx

我的BridgeProperties.java

代码语言:javascript
复制
@Component
@PropertySource("classpath:custom.yml")
@ConfigurationProperties(
        prefix = "bridge"
)

public class BridgeProperties {
    @NestedConfigurationProperty
    protected ApiProperties apiProperties = new ApiProperties();
}

我的ApiProperties.java

代码语言:javascript
复制
  public class ApiProperties {
    protected String url;
    protected ApiProperties.Authentication authentication;
    // getter and setter

    public ApiProperties() {
    }

    public static class Authentication {
      protected String authUrl;
      protected String user;
      public Authentication() {}
      // getter and setter
    }

我的申请的入口点:

代码语言:javascript
复制
@SpringBootApplication
@PropertySources(value = {
        @PropertySource("classpath:application.yml"),
        @PropertySource("classpath:custom.yml")
})

public class IntegrationService {
    public static void main(String... args) {
        SpringApplication.run(IntegrationService.class, args);
    }
}

当打印到命令行时,我得到null,而不是分配给custom.yml中的url、auth-url和user的值。

EN

回答 1

Stack Overflow用户

发布于 2022-06-27 23:11:45

正如白龙遗址中提到的

还值得一提的是,YAML文件不支持@PropertySource注释,因此如果我们需要使用该注释,它将限制我们使用属性文件。

如果确实需要以yaml格式导入其他外部文件,则必须实现自己的PropertySourceFactory,就像在这篇文章中一样。

对我来说,我看不到不使用默认application.yml的好处,因为您可以定义由不同Properties类管理的多个节。

例如,如果您只是将属性放在application.yml中,并且使用最近的JDK (>=jdk 14)进行编译,甚至可以使用该记录以非常紧凑的方式管理您的属性:

您所要做的只是添加EnableConfigurationProperties注释:

代码语言:javascript
复制
@SpringBootApplication
@EnableConfigurationProperties(BridgeProperties.class)
public class IntegrationService {
    public static void main(String... args) {
        SpringApplication.run(IntegrationService.class, args);
    }
}

并定义用于映射yaml属性的记录:

代码语言:javascript
复制
@ConfigurationProperties(prefix = "bridge")
public final record BridgeProperties(String url, Authentication authentication) {
    public record Authentication(String authUrl, String user){
    }
}

记住,如果使用profile dev启动应用程序,也可以在配置文件(如application-dev.yml )中定义环境变量,例如,如果生产概要文件名为prd,则为生产application-prd.yml定义环境变量。您仍然可以将公共属性保留在application.yml中。

如果您真的想进入外部文件路径,我建议切换到.properties,因为@PropertySource本机支持它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71067273

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档