Spring boot

How to read external properties file in spring boot

PropertySourcesPlaceholderConfigurer Spring boot

Spring boot allows application.properties to be loaded from an external location or from system path using PropertySourcesPlaceholderConfigurer

Specialization of PlaceholderConfigurerSupport that resolves ${…} placeholders within bean definition property values and @Value annotations against the current Spring Environment and its set of PropertySources.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.candidjava.spring.boot</groupId>
	<artifactId>ExternalizedConfiguration</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>ExternalizedConfiguration</name>
	<description>Externalized Configuration</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Launch as Spring boot application

package com.candidjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;

@SpringBootApplication
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }
 @Bean
 public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
  PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
  properties.setLocation(new FileSystemResource("/classpath:/application.properties"));
  properties.setIgnoreResourceNotFound(false);
  return properties;
 }
}

Sample controller UserController.java

package com.candidjava.spring.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.service.UserService;

@RestController
@RequestMapping(value = {
 "/user"
})
public class UserController {

 @Autowired
 UserService userService;


 @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
 public ResponseEntity<User> getUserById(@PathVariable("id") int id) {
  System.out.println("Fetching User with id " + id);
  User user = userService.findById(id);
  if (user == null) {
   return new ResponseEntity<User> (HttpStatus.NOT_FOUND);
  }
  return new ResponseEntity<User> (user, HttpStatus.OK);
 }

 @PostMapping(value = "/create", headers = "Accept=application/json")
 public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
  System.out.println("Creating User " + user.getName());
  userService.createUser(user);
  HttpHeaders headers = new HttpHeaders();
  headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
  return new ResponseEntity<Void> (headers, HttpStatus.CREATED);
 }

 @GetMapping(value = "/get", headers = "Accept=application/json")
 public List<User> getAllUser() {
  List<User> tasks = userService.getUser();
  return tasks;

 }

 @PutMapping(value = "/update", headers = "Accept=application/json")
 public ResponseEntity<String> updateUser(@RequestBody User currentUser) {
  User user = userService.findById(currentUser.getId());
  if (user == null) {
   return new ResponseEntity<String> (HttpStatus.NOT_FOUND);
  }
  user.setId(currentUser.getId());
  user.setName(currentUser.getName());
  user.setCountry(currentUser.getCountry());
  userService.update(user);
  return new ResponseEntity<String> (HttpStatus.OK);
 }

 @DeleteMapping(value = "/{id}", headers = "Accept=application/json")
 public ResponseEntity<User> deleteUser(@PathVariable("id") int id) {
  User user = userService.findById(id);
  if (user == null) {
   return new ResponseEntity<User> (HttpStatus.NOT_FOUND);
  }
  userService.deleteUserById(id);
  return new ResponseEntity<User> (HttpStatus.NO_CONTENT);
 }

 @PatchMapping(value = "/{id}", headers = "Accept=application/json")
 public ResponseEntity<User> updateUserPartial(@PathVariable("id") int id, @RequestBody User currentUser) {
  User user = userService.findById(id);
  if (user == null) {
   return new ResponseEntity<User> (HttpStatus.NOT_FOUND);
  }

  userService.updatePartially(currentUser, id);
  return new ResponseEntity<User> (user, HttpStatus.OK);
 }
}

UserService.java

package com.candidjava.spring.service;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserService {
 public void createUser(User user);
 public List<User> getUser();
 public User findById(int id);
 public void update(User user);
 public void deleteUserById(int id);
 public void updatePartially(User user, int id);
}

UserServiceImp.java

package com.candidjava.spring.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Service;

import com.candidjava.spring.bean.User;

@Service
public class UserServiceImp implements UserService {

 private static List<User> users;

 static {
  users = dummyUsers();
 }

 public List<User> getUser() {
  // TODO Auto-generated method stub
  return users;
 }

 public User findById(int id) {
  // TODO Auto-generated method stub
  for (User user: users) {
   if (user.getId() == id) {
    return user;
   }
  }
  return null;
 }

 public void createUser(User user) {
  // TODO Auto-generated method stub
  users.add(user);
 }

 public void deleteUserById(int id) {
  // TODO Auto-generated method stub
  Iterator<User> it = users.iterator();
  while (it.hasNext()) {
   User user = (User) it.next();
   if (user.getId() == id) {
    it.remove();
   }
  }
 }

 public void updatePartially(User currentUser, int id) {
  for (User user: users) {
   if (user.getId() == id) {
    if (currentUser.getCountry() != null) {
     user.setId(id);
     user.setCountry(currentUser.getCountry());
    }
    user.setName(user.getName());
    update(user);
   }
  }

 }

 public void update(User user) {
  // TODO Auto-generated method stub
  int index = users.indexOf(user);
  users.set(index, user);
 }

 private static List<User> dummyUsers() {
  // TODO Auto-generated method stub
  List<User> users = new ArrayList<User>();
  users.add(new User(14221, "John", "INDIA"));
  users.add(new User(14222, "Ben", "UK"));
  users.add(new User(14223, "Andrew", "INDIA"));
  users.add(new User(14224, "Samuael", "USA"));
  return users;
 }

}

User.java

package com.candidjava.spring.bean;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties({
 "hibernateLazyInitializer",
 "handler"
})
public class User {

 private int id;
 private String country;
 private String name;
 public User() {
  id = 0;
 }
 public User(int id, String name, String country) {
  this.id = id;
  this.name = name;
  this.country = country;
 }
 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 public String toString() {
  return "name:" + name;
 }

}

Download Source Code

You can download source code from my github account (click here)