Reputation: 711
I've created a configuration class that will store configuration values. These configuration values should be read in from a configuration file "config.properties
". Below is the config class:
@Configuration
@ComponentScan(basePackages = {"com.boot.Training.*"})
@PropertySource("file:/src/main/java/config.properties")
public class AppConfig {
@Value("${myFirstName}")
private static String myFirstName;
@Value("${myLastName}")
private static String myLastName;
public static void showVariables() {
System.out.println("firstName: " + myFirstName);
System.out.println("lastName: " + myLastName);
}
}
And below are the contents of the config.properties
file:
myFirstName=John
myLastName=Doe
Running my program should simply print the values of these variables. But instead, Eclipse tells me it cannot find the config.properties
file, even though I specified that it is located in /src/main/java/config.properties
.
I'm likely specifying the file location without taking something else into account. What am I missing here?
Upvotes: 4
Views: 20714
Reputation: 2230
The basic way to specify a file:
location to appoint a properties file that is located elsewhere on your host environment is:
@PropertySource("file:/path/to/application.properties")
/path/to/application.properties
should be absolute path pointing to your .properties
file (in your example you are mixing file:
usage and relative path which is not correct )it is also possible to specify a system property or an environment variable that will be resolved to its actual value when your application starts. For example, ${CONF_DIR} below will be replaced with its associated value when the Spring application starts:
Open /etc/environment in any text editor like nano or gedit and add the following line:
CONF_DIR=/path/to/directory/with/app/config/files
Check it system variable has been set:
echo $CONF_DIR
/path/to/directory/with/app/config/files
use PropertySource like:
@PropertySource("file:${CONF_DIR}/application.properties")
Upvotes: 1
Reputation: 31720
The location you are using (file:/src/main/java/config.properties
) refers to an absolute path rather than one relative to your project home.
A more common way to do this is to ship config.properties
as part of your project in a resources directory, and refer to it via the classpath. If you move it to /src/main/resources/config.properties
, you can load it this way:
@PropertySource("classpath:config.properties")
I believe in theory you could just leave it in /src/main/java
and change your @PropertySource
location to what I have above, but moving it to /resources
is the more idiomatic way of doing this.
Upvotes: 3