【问题标题】:Resource injection in Spring Boot not working with gradleSpring Boot中的资源注入不适用于gradle
【发布时间】:2023-04-05 19:57:02
【问题描述】:

我有一个配置 bean。

@Component
public class Config {

   @Value("classpath:${app.file.name.srgbicc}")
   public Resource icc;

   @PostConstruct
   void init(){
      try {
         tempdir = Files.createTempDir();
         newIcc = copyIccFileToTemp();           
      }catch (IOException e){
        throw new RuntimeException(e);
      }
  }

  private File copyIccFileToTemp() throws IOException {
      File tempIcc = new File(tempdir, icc.getFilename());
      FileUtils.copyFile(icc.getFile(),tempIcc);
      return tempIcc;
  }    

}

icc.getFile() 上有一个 FileNotFoundException

application.properties

app.file.name.srgbicc = sRGB.icc

我查看了我的类路径,发现如下情况:

build/classes/main (no icc file)
build/resources/main (icc file, application.properties)

在应用程序启动期间打印出我的类路径时,我只找到了...myApp/build/classes/main。 那里没有 ../build/resources/main../src/main/resources 条目。

所以我想知道为什么资源不在类路径上? 根据http://docs.spring.io/spring-boot/docs/1.1.5.RELEASE/reference/htmlsingle/#build-tool-plugins-gradle-running-applications 这应该是。

当然,如果我将 icc 文件放在 build/classes/main 中,它会按预期工作,但它不应该在那里。对吧?

我尝试在 intellij 中使用gradle rungradle bootRun 运行应用程序,我使用static main。好消息是应用程序始终失败,与我如何启动它无关。

我的项目布局

myApp
     src
        main
           java
               pkg
                  Config.java
           resources
               sRGB.icc
               application.properties

供参考: 智能 13 弹簧启动 1.1.5 Fgradle 2.0

更新 这是我的代码的精简示例 https://gist.github.com/Vad1mo/bb5d23ca251341236fbd

我在 config.init 中删除了 @PostConstruct 并使用 gradle build 运行应用程序,当我从 intellij 运行测试失败时,所有测试都成功。这很奇怪,我知道有不同的行为

【问题讨论】:

  • 您究竟是如何运行应用程序(Gradle 或 IntelliJ)的,您将资源文件具体放在哪里?看起来有些东西配置错误,因为处理后的资源文件应该进入build/resources/main,而不是build/classes/resources/main
  • @PeterNiederwieser 创建问题时出现复制和粘贴错误。我的路径是build/resources/main
  • 您究竟是如何运行应用程序(Gradle 或 IntelliJ)的,您将资源文件具体放在哪里?
  • @Peter 我更新了我的问题。我只是运行 gradle run 或 gradle bootRun 没有参数。设置是简单的香草弹簧启动教程。将尝试设置一个示例项目。
  • 您的项目布局有src/resources,但必须是src/main/resources

标签: spring gradle spring-boot intellij-13


【解决方案1】:

我现在解决了这个问题。

帮助我的只是做一个简单的clean build 并在 intellij 中重建项目。我使用了很多 eclipse 和 maven,所以我希望它会自动发生。

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 2020-05-25
    • 2018-08-25
    • 2015-06-28
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    相关资源
    最近更新 更多