Reputation: 51
I have created a properties file and trying to access this in my spring DAO class file, but am getting "java.io.FileNotFoundException: config.properties (The system cannot find the file specified)". I have tried different scenarios to put the file in different folder/locations but getting same issue. Can anybody please help me on this. Below is the code and structure details,
In DAO class,
FileReader reader = new FileReader("config.properties");
Properties properties = new Properties();
properties.load(reader);
I tried to put the "config.properties" file under src/main/resources and also under WEB-INF/
. My DAO class is in src/main/java/com/test/dao
Thanks in Advance.
Upvotes: 1
Views: 2495
Reputation: 6206
If you are trying to read from a property file, the best practice would be to keep it in the src/main/resources folder , which is the default location for property files as per spring . The you can either use annotations to read the values in the property file, which spring will automatically read and inject.
By using @value annotation:
@Value( "${jdbc.url:aDefaultUrl}" )
private String jdbcUrl;
Note: Here you can also specify the default value.
By using xml configuration:
<bean id="dataSource">
<property name="url" value="${jdbc.url}" />
<bean>
By using the @PropertySource annotation :
@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {
//...
}
Here you can provide the keys to be mapped in the class and it will get mapped automatically to the fields.
you can also specify multiple property files like :
@PropertySources({
@PropertySource("classpath:foo.properties"),
@PropertySource("classpath:bar.properties")
})
Note : Keep in mind for this to work the property file should have an extension like .properties and values in property file should follow the property file convention.
Upvotes: 1
Reputation: 26492
You can keep the file in src/main/resources where its most appropriate and change the way you retrieve it into:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("config.properties").getFile());
FileReader reader = new FileReader(file);
Upvotes: 1