Java Spring Boot 访问静态资源缺少 scr/main/resources

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36371748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:47:22  来源:igfitidea点击:

Spring Boot access static resources missing scr/main/resources

javaspringspring-bootresourcesspring-properties

提问by lenach87

I am working on a Spring Boot application. I need to parse an XML file (countries.xml) on start. The problem is that I do not understand where to put it so that I could access it. My folders structure is

我正在开发一个 Spring Boot 应用程序。我需要在开始时解析一个 XML 文件 (countries.xml)。问题是我不知道把它放在哪里以便我可以访问它。我的文件夹结构是

ProjectDirectory/src/main/java
ProjectDirectory/src/main/resources/countries.xml

My first idea was to put it in src/main/resources, but when I try to create File (countries.xml) I get a NPE and the stacktrace shows that my file is looked in the ProjectDirectory (so src/main/resources/ is not added). I tried to create File (resources/countries.xml) and the path would look like ProjectDirectory/resources/countries.xml (so again src/main is not added).

我的第一个想法是将它放在 src/main/resources 中,但是当我尝试创建文件 (countries.xml) 时,我得到了一个 NPE 并且堆栈跟踪显示我的文件在 ProjectDirectory 中(因此 src/main/resources/没有添加)。我尝试创建文件 (resources/countries.xml) 并且路径看起来像 ProjectDirectory/resources/countries.xml(所以再次没有添加 src/main)。

I tried adding this with no result

我尝试添加这个但没有结果

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    super.addResourceHandlers(registry);
}

I know that I can add src/main/ manually, but I want to understand why is it not working as it has to. I also tried examples with ResourceLoader - with the same no result.

我知道我可以手动添加 src/main/,但我想了解为什么它不能正常工作。我还尝试了 ResourceLoader 的示例 - 没有结果。

Could anyone suggest what the problem is?

任何人都可以提出问题是什么?

UPDATE:Just for future references - after building the project, I encountered problem with accessing file, so I changed File to InputStream

更新:仅供将来参考 - 构建项目后,我遇到了访问文件的问题,因此我将 File 更改为 InputStream

InputStream is = new ClassPathResource("countries.xml").getInputStream();

采纳答案by luboskrnac

Just use Spring type ClassPathResource.

只需使用 Spring 类型ClassPathResource

File file = new ClassPathResource("countries.xml").getFile();

As long as this file is somewhere on classpath Spring will find it. This can be src/main/resourcesduring development and testing. In production, it can be current running directory.

只要这个文件在类路径上的某个地方,Spring 就会找到它。这可以src/main/resources在开发和测试期间进行。在生产中,它可以是当前运行目录。

EDIT:This approach doesn't work if file is in fat JAR. In such case you need to use:

编辑:如果文件在 fat JAR 中,则此方法不起作用。在这种情况下,您需要使用:

InputStream is = new ClassPathResource("countries.xml").getInputStream();

回答by Sanjay Rawat

To get the files in the classpath :

要获取类路径中的文件:

Resource resource = new ClassPathResource("countries.xml");
File file = resource.getFile();

To read the file onStartup use @PostConstruct:

要读取文件 onStartup 使用@PostConstruct

@Configuration
public class ReadFileOnStartUp {

    @PostConstruct
    public void afterPropertiesSet() throws Exception {

        //Gets the XML file under src/main/resources folder
        Resource resource = new ClassPathResource("countries.xml");
        File file = resource.getFile();
        //Logic to read File.
    }
}

Here is a Small examplefor reading an XML File on Spring Boot App startup.

这是一个在 Spring Boot App 启动时读取 XML 文件的小示例

回答by Sachchidanand Singh

While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile()when it is deployed as JAR as I faced the same issue. This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.

在使用 Spring Boot 应用程序时,resource.getFile()当它部署为 JAR 时,很难获取使用的类路径资源,因为我遇到了同样的问题。使用 Stream 解决此扫描,它将找出放置在类路径中任何位置的所有资源。

Below is the code snippet for the same -

以下是相同的代码片段 -

ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);

回答by Andrew Gans

You need to use following construction

您需要使用以下构造

InputStream in = getClass().getResourceAsStream("/yourFile");

Please note that you have to add this slash before your file name.

请注意,您必须在文件名之前添加此斜杠。

回答by Sanjay Sharma

You can use following code to read file in String from resource folder.

您可以使用以下代码从资源文件夹中读取字符串中的文件。

final Resource resource = new ClassPathResource("public.key");
String publicKey = null;
try {
     publicKey = new String(Files.readAllBytes(resource.getFile().toPath()), StandardCharsets.UTF_8);
} catch (IOException e) {
     e.printStackTrace();
}

回答by Galley

I use spring boot, so i can simple use:

我使用弹簧靴,所以我可以简单地使用:

File file = ResourceUtils.getFile("classpath:myfile.xml");

回答by Nemanja Rajkovic

I use Spring Boot, my solution to the problem was

我使用 Spring Boot,我对问题的解决方案是

"src/main/resources/myfile.extension"

Hope it helps someone.

希望它可以帮助某人。

回答by ramakotireddy nagireddy

Because java.net.URL is not adequate for handling all kinds of low level resources, Spring introduced org.springframework.core.io.Resource. To access resources, we can use @Value annotation or ResourceLoader class. @Autowired private ResourceLoader resourceLoader;

因为 java.net.URL 不足以处理各种底层资源,Spring 引入了 org.springframework.core.io.Resource。要访问资源,我们可以使用 @Value 注解或 ResourceLoader 类。@Autowired 私有 ResourceLoader 资源加载器;

@Override public void run(String... args) throws Exception {

@Override public void run(String... args) 抛出异常 {

    Resource res = resourceLoader.getResource("classpath:thermopylae.txt");

    Map<String, Integer> words =  countWords.getWordsCount(res);

    for (String key : words.keySet()) {

        System.out.println(key + ": " + words.get(key));
    }
}