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?
So now my questions related to this post are:
- What is the difference between classpath: prefix and without classpath: prefix in path
- why line 1 (ClassPathResource) didn't work while line 3 (ResourceLoader) worked in which I have also used classpath prefix.
- What is the best way of loading the file? Using the classpath prefix or without it, and what is its purpose?