Main Tutorials

How to load custom properties files in Spring Boot

load custom properties files

This article shows how to use @PropertySource annotation to load custom properties files in Spring Boot.

Table of contents:

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

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments