0

Simple Spring boot program to load application.properties from src/main/resource directory:

@SpringBootApplication
public class PathLearningApplication {

    public static void main(String[] args) throws IOException {
        // 1.
        InputStream inputStream = new ClassPathResource("classpath:application.properties").getInputStream(); 

        // 2.
        InputStream inputStream2 = new ClassPathResource("application.properties").getInputStream();

        // 3.
        ResourceLoader resourceLoader = new DefaultResourceLoader();

        Resource resource = resourceLoader.getResource("classpath:application.properties");
        resource.getInputStream();

        SpringApplication.run(PathLearningApplication.class, args);
    }

}

When I tried to run this program locally using Intellij, line number 1. gave me the error:

Error:

Exception in thread "main" java.io.FileNotFoundException: class path resource [classpath:application.properties] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:199)
    at com.example.PathLearning.PathLearningApplication.main(PathLearningApplication.java:19)

While line number 2. (InputStream2) and line number 3. (ResourceLoader works fine).

Here is the classPath set in intellij using stackoverflow

How to add directory to classpath in an application run profile in IntelliJ IDEA?

Classpath set in intellij

So now my questions related to this post are:

  1. What is the difference between classpath: prefix and without classpath: prefix in path
  2. why line 1 (ClassPathResource) didn't work while line 3 (ResourceLoader) worked in which I have also used classpath prefix.
  3. What is the best way of loading the file? Using the classpath prefix or without it, and what is its purpose?
Vini
  • 8,299
  • 11
  • 37
  • 49
  • Spring resource handling - https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/resources.html (Sections 6.3 and 6.4 explain Resources and ResourceLoader) – Vini Dec 09 '22 at 20:06
  • Can you please tell me why Line 1? ClassPathResource with the "classpath:" prefix is not working. – ZoroSenpai Dec 10 '22 at 07:18

0 Answers0