简体   繁体   English

如何告诉spring从外部文件夹加载资源?

[英]how to tell spring to load resources from external folder?

I'm trying to read a text file in config folder - MyProject/config in spring boot configuration class using MyConfig.class.getResourceAsStream(/config/test.txt). 我正在尝试使用MyConfig.class.getResourceAsStream(/config/test.txt)在spring文件夹配置类中读取config文件夹中的文本文件 - MyProject / config。

MyProject
  -config
    -test.txt
  -src
    -main
      -java
        -com
          -myproject
            -configurations
              -MyConfig

It always return null as the resource not found. 它始终返回null,因为找不到资源。 Whereas it can read the file if it is located under MyProject/src/main/resources folder. 而如果它位于MyProject / src / main / resources文件夹下,它可以读取该文件。

MyProject
  -src
    -main
      -resources
        -test.txt
      -java
        -com
          -myproject
            -configurations
                -MyConfig

Is there any specific configuration required to tell spring-boot to check the entire path of the project? 是否需要任何特定的配置来告诉spring-boot检查项目的整个路径?

@Configuration
@EnableAutoConfiguration
public class MyConfig {

  @Bean
  public Config config() { 
    return new Config(MyConfig.class.getResourceAsStream("/config/test.txt"); // This doesn't work. The same setup work if I have the file under resources folder.MyConfig.class.getResourceAsStream("/test.txt")
  }
  }

That method will load only from classpath/modulepath. 该方法仅从classpath / modulepath加载。 Check of the config folder is in the classpath. 检查config文件夹是否在类路径中。

假设您有一个典型的项目结构,请尝试将test.txt文件放在src / main / resources文件夹中,以便通过springboot上下文进行扫描。

例如<> E:\\ MyProject \\ config \\ test.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM