Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

specify files in resources folder in spring application.properties file

Tags:

spring-boot

I have a Spring Boot application, the code need to access a file under resources folder. here is my application.properties file:

cert.file=classpath:/resources/cert.p12

however it always complained:

java.io.FileNotFoundException: classpath:/resources/cert.p12 (No such file or directory)

I double checked folder my_project/target/classes to make sure the file cert.p12 exits there.

and in the code I tried to access the file:

@Value("${cert.file}")
private String certFile;
....
@Bean
public Sender sender() {
    return new Sender(certFile);
}

what exactly is the this classpath? and why it cannot find the file? Thanks!

like image 595
user468587 Avatar asked Aug 28 '15 19:08

user468587


People also ask

How do you load properties file from resources folder in Java?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().

Where do I put application properties file?

You will need to add the application. properties file in your classpath. If you are using Maven or Gradle, you can just put the file under src/main/resources . If you are not using Maven or any other build tools, put that under your src folder and you should be fine.


2 Answers

Classpath includes what you have inside you resources dir.

Try:

cert.file=classpath:cert.p12

I'm assuming that you have standard maven catalog structure.

like image 108
raduy Avatar answered Sep 23 '22 17:09

raduy


This syntax doesn't work with a normal FileInputStream. Use the Spring Resourceloader instead.

@Autowired
private ResourceLoader resourceLoader;

@Value("${property.name}")
private String property;

File getPropertyFile(){
    return resourceLoader.getResource(property).getFile();
}

application.properties

property.name=classpath:filename.txt
like image 42
Domo Avatar answered Sep 24 '22 17:09

Domo