【问题标题】:Unable to load external properties in Spring Boot无法在 Spring Boot 中加载外部属性
【发布时间】:2016-01-05 13:43:54
【问题描述】:

我有一个非常基本的 spring boot 命令行应用程序,我试图从我的项目中存在的 application.yml 文件加载属性。该项目是使用 gradle 构建的,我使用 groovy 作为语言。

现在无论我将 application.yml 文件放在哪里,我似乎都无法将其值分配给配置属性 bean。文件如下

application.yml

my:
  name: "some name"
  servers:
    - dev.bar.com
    - foo.bar.com

Config.groovy

import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Configuration

@Configuration
@ConfigurationProperties(prefix = "my")
public class Config {

    private List<String> servers = new ArrayList<String>();
    private String name

    public List<String> getServers() {
        return this.servers;
    }

    public String getName() {
        return this.name
    }
}

Worker.groovy 命令行运行器

@Component
class Worker implements CommandLineRunner {

    @Autowired
    Config config

    @Override
    public void run(String... args) throws Exception {
        println "Running a test app"
        println config.name
        println config.getServers()
    }
}

目录结构

app-name
  -build.gradle
  -src
    -main
      -groovy
        -config
          -application.yml
        -com
          -company
            -app
              Worker.groovy
              Config.groovy
              Application.groovy

我还尝试将 application.yml 重命名为 application.properties 并将其添加到 com.company.app 项目下,但工作类的 run 方法始终将属性打印为 null。我相信我可能错过了一些非常基本的东西,但似乎找不到它有什么。

如果我需要提供任何其他详细信息,请告诉我。

【问题讨论】:

  • 成功了!我希望文档对此更清楚。您为什么不将此作为答案而不是评论发布,我会接受它作为有效答案?谢谢!!

标签: spring groovy gradle spring-boot


【解决方案1】:

application.yml 应该在src/main/resources/config 之下。

src/main/resources 目录处理(复制)资源。

默认情况下,groovy 插件会忽略 src/main/groovy 中除 groovy 类之外的其他类。

【讨论】:

    猜你喜欢
    • 2018-06-25
    • 2015-01-23
    • 2018-02-25
    • 2014-12-21
    • 2015-05-14
    • 2015-09-29
    • 2017-01-16
    • 1970-01-01
    相关资源
    最近更新 更多