How to load custom properties files in Spring Boot
This article shows how to use @PropertySource
annotation to load custom properties files in Spring Boot.
Table of contents:
- 1. Load default properties file
- 2. Load custom properties files
- 3. Load multiple custom properties files
- 4. Download Source Code
- 5. References
P.S. Tested with Spring Boot 3.1.2
1. Load default properties file
Spring default loads application.properties
into the application’s environment, and we can use @Value
to access the property values.
src/main/resources/application.properties
server.name=SpringAppCluster01
ServerProperties.java
package com.mkyong.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ServerProperties {
@Value("${server.name}")
private String name; // Value = 'SpringAppCluster01'
//...
}
2. Load custom properties files
We can use @PropertySource
to load a custom properties file.
src/main/resources/server.properties
server.name=SpringAppCluster01
ServerProperties.java
package com.mkyong.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:server.properties")
public class ServerProperties {
@Value("${server.name}")
private String name; // Value = 'SpringAppCluster01'
//...
}
3. Load multiple custom properties files
@PropertySource
example.
import org.springframework.context.annotation.PropertySource;
@PropertySource({
"classpath:/server/db.properties",
"classpath:/server/file.properties"
})
@PropertySources
example.
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.annotation.PropertySource;
@PropertySources({
@PropertySource("classpath:/server/db.properties"),
@PropertySource("classpath:/server/file.properties")
})
Note
Study more about Spring @PropertySource example.
4. Download Source Code
$ git clone https://github.com/mkyong/spring-boot.git
$ cd spring-boot-externalize-config-3
$ mvn test
$ mvn spring-boot:run
5. References
About Author
Comments
Subscribe
0 Comments