Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Spring - Properties


Say, we are using an application where we are saving data to the database. In such cases it is a good practice to keep the database credentials like username, connection url in an external file or a properties file.


Spring gives us the flexibility to fetch the contents from the properties file. Let us understand with the below example where we are going to get the value of the 'brand' property of 'Car' class from a properties file :


application.properties

brandProp=Honda

So, in the above case we have defined a properties file named 'application.properties' and set the value of 'brandProp' to 'Honda'.



Car Class

class Car {

 String brand;

 -- Getters and Setters --

}


How would Spring come to know about the application.properties file?

Now, in the application-context.xml we are going to inform Spring about the application.properties file.


application-context.xml

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation = "http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <context:property-placeholder location="application.properties">

  <bean name = "car" class = "Car">
   <property name = "brand" value="${brandProp}"/>
  </bean>

</beans>

The below line from application-context.xml tells Spring that the name of the properties file is 'application.properties' and it needs to be included in the application.


<context:property-placeholder location="application.properties">

Then comes the main part where we are trying to fetch value from 'application.properties' and assign it to the 'brand' property of the 'Car' class.


<bean name = "car" class = "Car">
   <property name = "brand" value="${brandProp}"/>
</bean>

Note that value="${brandProp} gets the value from 'application.properties'


brandProp=Honda

And assigns it to the 'brand' property of'Car' class.