Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring - How to Load Literal Values From Properties File
Next article icon

Spring - How to Load Literal Values From Properties File

Last Updated : 07 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Literals in Java are a synthetic representation of boolean, numeric, character, or string data. It is a medium of expressing particular values in the program, such as an integer variable named ‘’/count is assigned an integer value in the following statement.

int x = 100;   // Here 100 is a constant/literal.

Illustration: String literal.

String s = "Hello";

Properties File

The properties file is used to write the application-related property into that file. This file contains the different configuration which is required to run the application in a different environment, and each environment will have a different property defined by it. Inside the application properties file, we define every type of property like changing the port, database connectivity, connection to the eureka server, and many more. Now let’s see How to Load Literal Values from Properties File in a Spring Application. 

Prerequisite: Spring – Injecting Literal Values By Setter Injection

Implementation: Project

First, let's create a simple Spring Application and inject the literal values by setter injection. So, create a simple class Student having three attributes rollNo, name, and age. Create setter methods for these two attributes and a simple method to print the details of the student.

Example:

Java
// Java Program to Illustrate Student Class  // Class public class Student {      // Class data members     private int rollNo;     private String name;     private int age;      // Getters and setters      public void setRollNo(int rollNo)     {         this.rollNo = rollNo;     }      public void setName(String name)     {          // This keyword refers to current instance itself         this.name = name;     }      public void setAge(int age) { this.age = age; }      // Method     public void display()     {         System.out.println("Roll No: " + rollNo);         System.out.println("Name: " + name);         System.out.println("Age: " + age);     } } 

Now let’s create a Student Bean in the beans.xml file and inside the bean, you have to add your property’s name and its corresponding values inside the <property> tag. For example, for this project, we can write something like this

<bean id="student" class="Student">     <property name="rollNo" value="101"/>     <property name="name" value="Sagar"/>     <property name="age" value="20"/>  </bean>

Example: beans.xml file

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     https://www.springframework.org/schema/beans/spring-beans.xsd">      <bean id="student" class="Student">         <property name="rollNo" value="101"/>         <property name="name" value="Sagar"/>         <property name="age" value="20"/>     </bean>  </beans> 

So now our bean is ready. Now let’s create a class and define the main() method inside that class. Suppose we have created a class named Main and we have defined the main() method inside this class. Below is the code for the Main.java class. Comments are added inside the code for better understanding.

Example

Java
// Java Program to Illustrate Application File  // Importing required classes import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;  // Application class public class Main {      // Main driver method     public static void main(String[] args)     {         // Implementing Spring IoC         // using ApplicationContext         ApplicationContext context             = new ClassPathXmlApplicationContext(                 "beans.xml");          // Getting the bean student         Student student             = context.getBean("student", Student.class);          // Calling the methods         // inside main() method         student.display();     } } 

Now run your main() method and the output will be like this.

Output:

Roll No: 101  Name: Sagar  Age: 20

So we have seen this example before also. It's a simple example of setter-based dependency injection. But now, here is the interesting thing. Here is the concept that we are going to discuss and it's pretty useful. So let's come to the beans.xml file again

<bean id="student" class="Student">     <property name="rollNo" value="101"/>     <property name="name" value="Sagar"/>     <property name="age" value="20"/>  </bean>

The values declared inside the property file are static values (101, Sagar, 20). Now we want to load these particular values from a properties file. So now let's create a properties file in your classpath and name the file as student-info.properties (for this example we name it like this, you can name it according to your need). And in this file, we are going to write something like this

student.rollNo = 101  student.name = Sagar  student.age = 20

Now our properties file is ready and we have to load these values from the properties file to the beans.xml file. How to do it? So we can write something like this 

<context:property-placeholder location="classpath:student-info.properties"/>    <bean id="student" class="Student">     <property name="rollNo" value="${student.rollNo}"/>     <property name="name" value="${student.name}"/>     <property name="age" value="${student.age}"/>  </bean>

Note:

  • To load the dynamic values, the standard syntax is: "${ }"
  • Why this line "<context:property-placeholder location="classpath:student-info.properties"/>"?. This line is used to tell the Spring that we want to load the properties value from the student-info.properties file.

Example: File: beans.xml 

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"        xmlns:context="http://www.springframework.org/schema/context"        xsi:schemaLocation="http://www.springframework.org/schema/beans         https://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/context         https://www.springframework.org/schema/context/spring-context.xsd">      <context:property-placeholder location="classpath:student-info.properties"/>          <bean id="student" class="Student">         <property name="rollNo" value="${student.rollNo}"/>         <property name="name" value="${student.name}"/>         <property name="age" value="${student.age}"/>     </bean>  </beans> 

Again run your main() method and the output will be like this.

Output:

Roll No: 101  Name: Sagar  Age: 20

So we have seen that our application is working fine. And this is how one can Load Literal Values from Properties File. 


Next Article
Spring - How to Load Literal Values From Properties File

A

AmiyaRanjanRout
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Java-Spring
Practice Tags :
  • Java

Similar Reads

    Spring MVC Tutorial
    In this tutorial, we'll cover the fundamentals of Spring MVC, including setting up your development environment, understanding the MVC architecture, handling requests and responses, managing forms, and integrating with databases. You'll learn how to create dynamic web pages, handle user input, and i
    7 min read
    Spring - MVC Framework
    The Spring MVC Framework follows the Model-View-Controller architectural design pattern, which works around the Front Controller, i.e., the Dispatcher Servlet. The Dispatcher Servlet handles and dispatches all incoming HTTP requests to the appropriate controller. It uses @Controller and @RequestMapp
    4 min read
    Spring MVC using Java Based Configuration
    Spring MVC framework enables the separation of modules, namely Model, View, and Controller, and seamlessly handles application integration. This enables the developer to create complex applications using plain Java classes. The model object can be passed between the view and the controller using map
    3 min read
    ViewResolver in Spring MVC
    Spring MVC is a powerful Web MVC Framework for building web applications. It provides a structured way to develop web applications by separating concerns into Model, View, and Controller. One of the key features of Spring MVC is the ViewResolver, which enables you to render models in the browser wit
    7 min read
    How to Create Your First Model in Spring MVC?
    Spring MVC is a powerful Web MVC framework for building web applications. It is designed around the Model-View-Controller (MVC) pattern, which separates the application into three main components:Model: Represents the data of the application. It can be a single object or a collection of objects.View
    6 min read
    How to Create Your First View in Spring MVC?
    Spring MVC is a powerful Web MVC Framework for building web applications. It is designed around the Model-View-Controller (MVC) pattern, which separates the application into three main components:Model: Represents the data of the application. It can be a single object or a collection of objects.View
    5 min read
    Spring MVC CRUD with Example
    In this article, we will explore how to build a Spring MVC CRUD application from scratch. CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the four basic operations to create any type of project. Spring MVC is a popular framework for building web applications. Spring MVC follows
    7 min read
    Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite
    Spring MVC framework enables the separation of modules, namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain Java classes. The model object can be passed between the view and the controller
    5 min read
    What is Dispatcher Servlet in Spring?
    Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made
    6 min read
    Spring - Shortcut to Create Dispatcher Servlet in Eclipse/Spring Tool Suite
    Eclipse is an Integrated Development Environment (IDE) used in computer programming. It includes a base workspace and an extensible plug-in system for customizing the environment. It is the second-most-popular IDE for Java development. Eclipse is written mostly in Java and its primary use is for dev
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences