Spring Boot : Using PropertySource annotation to read custom .properties file

Vivek Singh
1 min readAug 11, 2021

--

For Git code check this - Git Link

As we know, we can use Value annotation to read application.properties file.

application.properties -

name = John
title = Mayer
server.port = 8080

TestController.java -

package com.example.customconfiguration.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/root")
public class TestController {
@Value("${name}")
String name;

@Value("${title}")
String title;

@GetMapping("/controller")
public String controllerTest() {
return "Hello " + name + title;
}
}

Similarly we can create a custom properties file and read the values in the file using PropertySource Annotation.

custom.properties -

customName = Japanese
customTitle = Mornings

CustomController.java -

package com.example.customconfiguration.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/custom")
@PropertySource("classpath:custom.properties")
public class CustomController {

@Value("${customName}")
String name;

@Value("${customTitle}")
String title;


@GetMapping("/controller")
public String controllerTest() {
return "Hello " + name + title;
}
}

In the above code, we are using a PropertySource annotation and passing the filename to be read. If there are multiple files to be read, we can use multiple PropertySource annotaiton or we can use PropertySources :

@PropertySources({     
@PropertySource("classpath:test1.properties"),
@PropertySource("classpath:test2.properties")
})
public class Properties{
//code
}

Conclusion :

This article explained how to read a custom properties file using PropertySource.

--

--

Vivek Singh
Vivek Singh

Written by Vivek Singh

Software Developer. I write about Full Stack, NLP and Blockchain. Buy me a coffee - buymeacoffee.com/viveksinless

No responses yet