有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring引导访问静态资源缺少scr/main/resources

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

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

我的第一个想法是把它放在src/main/resources中,但是当我尝试创建文件(countries.xml)时,我得到了一个NPE,stacktrace显示我的文件在ProjectDirectory中查找(所以src/main/resources/没有添加)。我试图创建文件(resources/countries.xml),路径看起来像ProjectDirectory/resources/countries。xml(所以同样没有添加src/main)

我试着添加这个,但没有结果

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

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

有人能告诉我问题出在哪里吗

更新: 仅供将来参考——在构建项目后,我遇到了访问文件的问题,所以我将文件更改为InputStream

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

共 (4) 个答案

  1. # 1 楼答案

    只需使用弹簧类型ClassPathResource

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

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

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

    InputStream is = new ClassPathResource("countries.xml").getInputStream();
    
  2. # 2 楼答案

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

    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();
    }
    
  3. # 3 楼答案

    要获取类路径中的文件:

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

    要在启动时读取文件,请使用@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.
        }
    }
    

    下面是一个Small example用于在Spring Boot应用程序启动时读取XML文件

  4. # 4 楼答案

    在使用Spring Boot应用程序时,当它被部署为JAR时,使用resource.getFile()很难获得类路径资源,因为我遇到了同样的问题。 这个扫描可以通过使用Stream来解决,Stream会找出类路径中任何位置的所有资源

    下面是同样的代码片段-

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