yozawiratama
yozawiratama

Reputation: 4318

Spring project how to set realtive and absolute path to get a properties file?

I got a source code from my team, and this is a spring framework project. but little different from before.

Okay I got a problem with get properties file from java code. this is my simple structure project :

root
 |- src
    |- log4j.properties
    |- persistent.properties
    |- id.com.my.api.elastic.utils
       |- StaticVariable.java

I need to load 2 properties file to StaticVariable.java properly

this is my code for now :

public static final String PROPERTIES_PATH = "/src/persistent.properties";
public static final String LOG4J_PATH = "/src/log4j.properties";

but when I run on tomcat server still not found this file, so I changed :

public static final String PROPERTIES_PATH = "..\\persistent.properties";
public static final String LOG4J_PATH = "..\\log4j.properties";

Also not found, how to solve this?

this is how the previous programmer use the code :

@Configuration
@ComponentScan(basePackages = "id.com.my.api.elastic")
@PropertySource("file:" + StaticVariable.PROPERTIES_PATH)
public class SpringJDBCConfiguration {
    Logger logger = LoggerFactory.getLogger(getClass());

Upvotes: 0

Views: 2686

Answers (1)

Antoniossss
Antoniossss

Reputation: 32517

public static final String PROPERTIES_PATH = "/persistent.properties";
public static final String LOG4J_PATH = "/log4j.properties";

those paths wil work with Class#getResource and Class#getResourceAsStream

As for your update:

You are requesting source to be a file - this wont work after packaging application - probably will work only in IDE. Insted of

@PropertySource("file:" + StaticVariable.PROPERTIES_PATH)

it should be

@PropertySource("classpath:/persistent.properties")

and

@PropertySource("classpath:/log4j.properties")

Read more here https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html

Upvotes: 1

Related Questions