Spring not loading properties from external config file properly

Viewed 2252

I have an internal application.yml file located in the classpath resources with the following fields:

redis:
  hostname: localhost
  port: 6379
  database: 0
  password:

There is an external config file: config.properties. It defines some fields to be overridden in my server context. File config.properties:

redis.hostname = db.example.com
redis.password = my_password

The application fails to start because it is not able to read the redis.port property in the config file. My doubt is that spring is not retaining fields of a property source(redis) completely if it has already found some fields defined in the external file(hostname, password in this case).

I am running the application using the following command:

java -jar -Dspring.config.location=file:///home/username/config.properties application.jar

How do I make spring properly override the internal configuration file so that it only overrides the extra properties(redis.hostname, redis.password) but still retain the other fields defined in the internal file(like redis.port, redis.database) but not defined in the external file?

P.S: I know this is what is happening because when I add the redis.port=6379 property in the external config file, the applications works properly.

2 Answers

Step 1: Read the Spring Boot documentation:

Config locations are searched in reverse order. By default, the configured locations are classpath:/,classpath:/config/,file:./,file:./config/. The resulting search order is the following:

file:./config/
file:./
classpath:/config/
classpath:/

When custom config locations are configured by using spring.config.location, they replace the default locations. For example, if spring.config.location is configured with the value classpath:/custom-config/,file:./custom-config/, the search order becomes the following:

file:./custom-config/
classpath:custom-config/

Step 2: Specify the correct value:

-Dspring.config.location=classpath:/,file:///home/username/config.properties
file:

and

classpath:

need to be specified when you are binding the configuration in your code. When you are specifying the -D parameter, you could pass address of the property file relative to the jar file location.

Related