首页 > 解决方案 > 如何在 Spring Boot MVC 中加载文件?

问题描述

我发现的所有示例都使用 XML 配置文件。我尝试了以下方法:

    IdSClientConfigurationImpl config = new IdSClientConfigurationImpl("idsclient.properties");
    config.load();

它给了一个例外

java.io.FileNotFoundException: idsclient.properties (The system cannot find the file specified)
        at java.io.FileInputStream.open0(Native Method) ~[na:1.8.0_152]
        at java.io.FileInputStream.open(FileInputStream.java:195) ~[na:1.8.0_152]
        at java.io.FileInputStream.<init>(FileInputStream.java:138) ~[na:1.8.0_152]
        at com.cisco.ccbu.common.ids.client.impl.IdSClientConfigurationImpl.load(IdSClientConfigurationImpl.java:82) ~[idsclientlib-11.6.1.jar:na]

我将文件放在与application.properties.

$ find src -name idsclient\*
src/main/resources/idsclient.properties

它被复制到类文件夹期间mvn spring-boot:run

$ find target -name idsclient\*
target/classes/idsclient.properties

那么在 Spring Boot 应用程序的上下文中文件的真实路径是什么?

我也试过

IdSClientConfigurationImpl config = new IdSClientConfigurationImpl("classpath:/idsclient.properties");

但它给了

java.io.FileNotFoundException: classpath:\idsclient.properties(文件名、目录名或卷标语法不正确)

标签: javaspringspring-mvcspring-boot

解决方案


您可以使用Spring 资源ClassPathResource

   //either autowire
   @Value("classpath:idsclient.properties")
   private Resource idsclientResource; 


   //or construct manually
   ClassPathResource idsclientResource = new ClassPathResource("idsclient.properties");

   ...

   IdSClientConfigurationImpl config = new IdSClientConfigurationImpl(idsclientResource.getFile().getPath()); 

推荐阅读