HowToDoInJava

Spring @GetMapping and @PostMapping

Lokesh Gupta

April 10, 2024

Learn to create Spring WebMVC REST controllers with @Controller annotation and map HTTP requests with annotations like @RequestMapping , @GetMapping and @PostMapping in a Spring or Spring Boot application.

1. Request Mapping Annotations

Before Spring 4.3 , Spring had only @RequestMapping annotation for mapping all the incoming HTTP request URLs to the corresponding controller methods.

Spring 4.3 introduced 5 new and more specific annotations for each HTTP request type .

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

For example, the following code demonstrates the usage of @GetMapping and @PostMapping .

To make it easy to relate the changes, in the given below code, @RequestMapping annotation has been used to map the same HTTP requests. Notice that we have specified the HTTP request type (GET, POST) as the annotation attribute method .

2. Spring @GetMapping Example

  • The @GetMapping annotation is a composed version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET) .
  • The @GetMapping annotated methods handle the HTTP GET requests matched with the given URI expression.

Let us understand how to write controller methods mapped with @GetMapping annotations. In the following example, we are mapping two GET requests:

  • HTTP GET /users – returns all the users in the system.
  • HTTP GET /users/{id} – returns a user by specified id.

3. Spring @PostMapping Example

  • The @PostMapping is a specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST) .
  • The @PostMapping annotated methods handle the HTTP POST requests matched with the given URI expression.
  • As a best practice, always specify the media types (XML, JSON etc.) using the ‘consumes’ and ‘produces’ attributes.

Let us understand how to write controller methods mapped with @PostMapping annotations. In the following example, we are mapping a POST request:

  • HTTP POST /users – creates a new user in the system.

4. Annotation Attributes

All request mapping annotations support the following attributes, but they should be used when appropriate for the request type:

  • path or value : specifies the mapping URI. A handler method that is not mapped to any path explicitly is effectively mapped to an empty path.
  • consumes : consists of one or more media types, one of which must match the request  Content-Type  header.
  • produces : consists of one or more media types one of which must be chosen via content negotiation against the “acceptable” media types, generally extracted from the  "Accept"  header but may be derived from query parameters.
  • headers : specifies the headers of the mapped request, narrowing the primary mapping, with a request only mapped if each such header is found to have the given value.
  • name : Assign a name to the mapping.
  • params : specifies the parameters of the mapped request, narrowing the primary mapping, with a request only mapped if each such parameter is found to have the given value.

5. Class-level Shared Attributes

The mapping annotations such as @RequestMapping, @GetMapping and @PostMapping , inherit the annotation attribute values from the @RequestMapping annotation applied at the @RestController class.

In HomeController , the @RequestMapping annotation at the top specifies the produces attribute to MediaType.APPLICATION_JSON_VALUE , so all the handler methods in this class, by default, will return the JSON response.

Note that the method-level mapping annotation may override the attribute values by providing its own values. In the following example, the /members API overrides the produces attribute so it will return the XML response to the clients.

6. Difference between @PostMapping and @RequestMapping

As noted above @PostMapping annotation is one specialized version of @RequestMapping annotation that handles only the HTTP POST requests .

@PostMapping = @RequestMapping(method = { RequestMethod.POST })

Let’s see the difference between @PostMapping and @RequestMapping annotations with a very simple example. Both versions in the given example will work exactly the same. They just have a slightly different syntax.

In other words, @PostMapping acts as a shortcut for @RequestMapping(method = RequestMethod.POST) . We can see the source code of the @PostMapping annotation which internally uses the @RequestMapping annotation.

Spring MVC has made writing request handlers / REST controller classes and methods very easy. Just add a few annotations like @GetMapping and @PostMapping and put the class where component scanning can find them and configure them in the web application context.

It is also very easy to create attributes at the class level so that all handler methods inherit them by default and can override them when needed.

Same way, you can use other request mapping annotations e.g. @PutMapping , @DeleteMapping and @PatchMapping .

Happy Learning !!

Source Code on Github

Further reading:

  • Spring Boot and Angular Application Example
  • Building HATEOAS Links with RESTEasy and JAX-RS
  • Spring Security Interview Questions
  • Spring Boot Interview Questions for Experienced Developers
  • Adding Role Based Security with Spring Boot REST APIs
  • Spring WebFlux Tutorial with CRUD Example

guest

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Tutorial Series

Privacy Policy

REST API Tutorial

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

Spring @GetMapping

last modified October 18, 2023

In this article we show how to use @GetMapping annotation to map HTTP GET requests onto specific handler methods.

Spring is a popular Java application framework for creating enterprise applications.

@GetMapping

@GetMapping annotation maps HTTP GET requests onto specific handler methods. It is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET) .

Spring @GetMapping example

The following application uses @GetMapping to map two request paths onto handler methods. In this example, we use annotations to set up a Spring web application.

This is the project structure.

In the pom.xml file we have the following dependencies: logback-classic , javax.servlet-api , junit , spring-webmvc , and spring-test .

The logback.xml is a configuration file for the Logback logging library.

MyWebInitializer registers the Spring DispatcherServlet , which is a front controller for a Spring web application.

The getServletConfigClasses returns a web configuration class.

The WebConfig enables Spring MVC annotations with @EnableWebMvc and configures component scanning for the com.zetcode package.

MyController provides mappings between request paths and handler methods.

@RestController is used for creating restful controllers, which do not use a view technology. The methods typically return XML, JSON, or plain text.

The @GetMapping maps a / root path from a GET request to the index method. It returns a plain text.

MyControllerTest tests the two pages.

We run the application and create two GET requests with curl tool.

In this article we have presented the @GetMapping annotation.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Spring tutorials .

what is @getmapping annotation in spring boot

Java Guides

Java Guides

Search this blog, spring @getmapping, @postmapping, @putmapping, @deletemapping and @patchmapping.

Check out my 10+ top Udemy courses and discount coupons: My Udemy Courses - Ramesh Fadatare

YouTube Video - 25+ Spring and Spring Boot Annotations

New Spring MVC Request Annotations

  • @GetMapping - shortcut for @RequestMapping(method = RequestMethod.GET)
  • @PostMapping - shortcut for @RequestMapping(method = RequestMethod.POST)
  • @PutMapping - shortcut for @RequestMapping(method = RequestMethod.PUT)
  • @DeleteMapping - shortcut for @RequestMapping(method =RequestMethod.DELETE)
  • @PatchMapping - shortcut for @RequestMapping(method = RequestMethod.PATCH)

How It Works

Add maven dependency, @getmapping, @postmapping, @putmapping, @deletemapping, @patchmapping, complete example - employeecontroller.java.

Refer this article for complete CRUD example at https://www.javaguides.net/2018/09/spring-boot-2-jpa-mysql-crud-example.html

Related Spring and Spring Boot Annotations

Spring boot @bean annotation example spring @qualifier annotation example spring @autowired annotation with example spring @bean annotation with example spring @configuration annotation with example spring @propertysource annotation with example spring @import annotation with example spring @importresource annotation example spring - @lazy annotation example spring - @primary annotation example spring @postconstruct and @predestroy example spring @repository annotation spring @service annotation   the spring @controller and @restcontroller annotations spring boot @component, @controller, @repository and @service spring @scope annotation with prototype scope example spring @scope annotation with singleton scope example spring boot @pathvariable spring boot @responsebody spring @requestbody - binding method parameters to request body spring boot @responsestatus annotation spring boot - creating asynchronous methods using @async annotation @springboottest spring boot example @springboottest vs @webmvctest @datajpatest spring boot example spring @postconstruct and @predestroy example spring @getmapping, @postmapping, @putmapping, @deletemapping and @patchmapping spring boot @enableautoconfiguration annotation with example spring boot @springbootapplication annotation with example, check out my bestseller udemcy courses:.

Check out my 10+ top Udemy courses and discount coupons:  My Udemy Courses - Ramesh Fadatare

what is @getmapping annotation in spring boot

You not include the PatchMapping in the Complete example, sad

what is @getmapping annotation in spring boot

Added PatchMapping in the complete example.

Post a Comment

Leave Comment

My Top and Bestseller Udemy Courses

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out all my Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

what is @getmapping annotation in spring boot

@GetMapping

Learn how to create a GET mapping in the REST service that returns a list of POJOs as JSON.

  • 1. Defining the PlayerService class
  • 2. Defining the getAllPlayers() method

Starting from this lesson, we will build a REST service that provides basic CRUD functionality. The client sends an HTTP request to the REST service. The dispatcher servlet handles the request and if the request has JSON data, the HttpMessageConverter converts it to Java objects. The request is mapped to a controller which calls service layer methods. The service layer delegates the call to repository and returns the data as POJO. The MessageConverter converts the data to JSON and it is sent back to the client. The flow of request is shown below:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.

Apps Developer Blog

Tutorials for Software Developers

Spring Annotations @PostMapping, @GetMapping, @PutMapping and @DeleteMapping

In this blog post, I will share the Spring annotations used to map HTTP requests to specific handler methods. These annotations include @PostMapping , @GetMapping, @PutMapping , and @DeleteMapping.

While most Spring Boot applications use the @RequestMapping annotation, which I will also cover in this post, I’ll begin with the newer shortcut annotations that have been available since Spring 4.3.

New Spring Boot REST Request Annotations

Spring Boot provides a set of new REST request annotations that simplify the process of building RESTful web services. These annotations are designed to be more specific and descriptive than the classic @RequestMapping annotation.

One key difference between the new annotations and the classic @RequestMapping annotation is that the new annotations are more concise and easier to read. They also provide more specific functionality and help to reduce the amount of boilerplate code required to build a RESTful web service.

Here are some of the new Spring Boot REST request annotations and the parameters that each of them can accept:

The @GetMapping Annotation

This annotation is used to handle HTTP GET requests. It can be translated to @RequestMapping(method = RequestMethod.GET) . And it accepts the following parameters:

  • value : A string that specifies the URL path that this method should handle.
  • produces : A string or an array of strings that specifies the media type(s) of the response that this method produces.
  • params : An array of strings that specifies the request parameters that must be present for this method to be invoked.
  • headers : An array of strings that specifies the headers that must be present for this method to be invoked.

This example shows how to use @GetMapping to handle an HTTP GET request for retrieving a user by ID. The value parameter specifies the URL path, and the @PathVariable annotation is used to extract the user ID from the URL path.

The @PostMapping Annotation

This annotation is used to handle HTTP POST requests. It can be translated to @RequestMapping(method = RequestMethod.POST) . And it accepts the following parameters:

  • consumes : A string or an array of strings that specifies the media type(s) of the request body that this method consumes.

Consider the following example where I show you how to use @PostMapping to handle an HTTP POST request for creating a new user. The value parameter specifies the URL path, and the @RequestBody annotation is used to extract the user object from the request body. The ResponseEntity is used to return a 201 Created status code and the location of the newly created user in the response header.

The @PutMapping Annotation

This annotation is used to handle HTTP PUT requests. It can be translated to @RequestMapping(method = RequestMethod.PUT) . And it accepts the same parameters as @PostMapping .

This example shows how to use @PutMapping to handle an HTTP PUT request for updating a user. The value parameter specifies the URL path, and the @PathVariable annotation is used to extract the user ID from the URL path. The @RequestBody annotation is used to extract the updated user object from the request body.

The @DeleteMapping Annotation

This annotation is used to handle HTTP DELETE requests. It can be translated to @RequestMapping(method = RequestMethod.DELETE) . And it accepts the same parameters as @GetMapping .

The example below shows how to use @DeleteMapping to handle an HTTP DELETE request for deleting a user. The value parameter specifies the URL path, and the @PathVariable annotation is used to extract the user ID from the URL path.

By using these new REST request annotations, you can build RESTful web services in Spring Boot more easily and with less code. They provide a more concise and descriptive way of defining the URLs and parameters for each RESTful operation, which can make your code more readable and easier to maintain.

Returning JSON or XML in Spring Boot using ‘produces’ and ‘consumes’ parameters

In Spring Boot, you can use the produces and consumes parameters in the request mapping annotations to specify the format of the request and response body. This is useful if you want to return data in JSON or XML format, depending on the content type of the request.

The produces parameter specifies the media type that the method can produce, i.e., the format of the response body. The consumes parameter specifies the media type that the method can consume, i.e., the format of the request body. By default, Spring Boot supports several media types, such as JSON ( application/json ) and XML ( application/xml ).

Here is an example of using produces and consumes parameters in a request mapping annotation:

In this example, the @PostMapping annotation specifies that the method should handle HTTP POST requests to the /users endpoint. The consumes parameter specifies that the method can only consume requests in JSON format, and the produces parameter specifies that the response should also be in JSON format.

You can also specify multiple media types by using an array of strings, like this:

In this example, the @GetMapping annotation specifies that the method should handle HTTP GET requests to the /users/{id} endpoint. The produces parameter specifies that the method can produce responses in both JSON and XML formats, and Spring Boot will automatically choose the appropriate format based on the content type of the request.

In conclusion, using produces and consumes parameters in Spring Boot request mapping annotations is a powerful feature that allows you to easily return data in the format that the client expects, whether it’s JSON, XML, or another format.

Read Request Body with the @RequestBody annotation

Spring Boot provides the @RequestBody annotation to bind the request body of a HTTP POST, PUT or PATCH request to a method parameter in your controller. This annotation is useful when you need to extract data from the request body, for example when creating or updating a resource.

Here’s an example of how to use the @RequestBody annotation in your controller method:

In the above example, the createUser method accepts a User object in the request body and returns a ResponseEntity with the saved user object.

By default, Spring Boot uses Jackson to deserialize the request body into a Java object. You can customize the deserialization process using Jackson annotations such as @JsonFormat and @JsonProperty .

If the request body is invalid or not present, Spring Boot returns a 400 Bad Request response by default. You can customize the response using exception handling.

In addition to JSON, Spring Boot also supports other media types such as XML and form data. You can specify the media type using the consumes attribute of the request mapping annotation, for example:

In the above example, the createUser method accepts form data in the request body and returns a ResponseEntity with the saved user object.

Overall, the @RequestBody annotation is a powerful tool for handling HTTP request bodies in your Spring Boot REST endpoints.

Extract values from the request URI with the @PathVariable annotation

In Spring Boot REST APIs, it’s often required to extract values from the request URI to pass as parameters to the REST API methods. The @PathVariable annotation in Spring Boot provides a way to do that. The @PathVariable annotation is used to bind a method parameter to a URI template variable.

To use @PathVariable annotation, simply add it before the parameter in the method definition. The parameter name should match the URI template variable name. Here’s an example:

In the example above, the @PathVariable Long id binds the id parameter to the id variable in the URI template /users/{id} . So if a GET request is sent to /users/1 , the value 1 will be extracted and passed to the getUserById() method.

It’s also possible to specify the URI template variable name in the @PathVariable annotation, in case it doesn’t match the parameter name. Here’s an example:

In the example above, the @PathVariable("userId") Long userId binds the userId parameter to the userId variable in the URI template /users/{userId}/posts/{postId} , and the @PathVariable("postId") Long postId binds the postId parameter to the postId variable in the same URI template.

Class-level Shared Annotations

In addition to the annotations we’ve discussed so far, Spring Boot also provides the ability to define class-level shared annotations that apply to all the methods in the class. This can be useful if you have a set of endpoints that all require the same configuration.

To define class-level shared annotations, simply add the desired annotations to the class declaration. Here’s an example that demonstrates the use of both class-level shared annotations and method-level annotations within a Spring Boot REST controller:

In this example, the @RestController annotation is used to mark the class as a REST controller. The @RequestMapping annotation is used at the class level to define the base URL path for all of the controller’s methods. In this case, all of the methods in the UserController class are mapped to URLs that begin with “/users”.

The @Autowired annotation is used to inject an instance of the UserService class into the UserController .

The @GetMapping annotation is used on the getUserById method to specify that it should handle HTTP GET requests to the URL “/users/{userId}”. The @PathVariable annotation is used to indicate that the userId parameter should be populated with the value from the URL path.

The @PostMapping annotation is used on the createUser method to specify that it should handle HTTP POST requests to the URL “/users”. The @RequestBody annotation is used to indicate that the method should deserialize the request body into a User object. The method returns a ResponseEntity with a status of 201 Created and a Location header that points to the newly created user’s URL.

Complete Example

Creating the project.

To apply the concepts you have learned, let’s work on an example project. First, create a Spring Boot project and then define a User class in the project. The User class can be structured as follows:

Create a UserRepository interface to manage user data. The UserRepository interface will be used to interact with the database and perform CRUD operations on user data.

Finally, you need to create a REST controller class where you can define the endpoints of your application. This class will be responsible for handling incoming requests from the client and sending back responses.

And this is what the default main class of your Spring Boot project looks like:

You can find my application.properties file below for reference:

Testing the project using Postman

After running your Spring Boot application, you can test your API endpoints using a tool like Postman . Here are the steps to follow:

  • Open Postman and create a new request.
  • Set the request method to POST .
  • Set the request URL to http://localhost:8080/users .
  • Select the Body tab.
  • Select the raw option and set the type to JSON .
  • In the request body, enter the following JSON object: { "name": "John Doe", "email": " [email protected] " }
  • Click the Send button to submit the request.

Testing a @PostMapping method

  • To retrieve all users, set the request method to GET .

Testing a @GetMapping method

You can use similar steps to test other endpoints that you have defined in your controller class.

This tutorial covered the basics of using the new Spring Boot REST request annotations: @PostMapping, @GetMapping, @PutMapping, and @DeleteMapping. We also discussed how to return JSON or XML using the ‘produces’ and ‘consumes’ parameters, how to read the request body with @RequestBody, and how to extract values from the request URI with @PathVariable.

Finally, we learned about class-level shared annotations. With these tools, you can easily create powerful and flexible RESTful web services in Spring Boot. Make sure to explore more Spring Boot REST tutorials and examples to enhance your knowledge and skills in building RESTful web services with Spring Boot.

Video tutorials

Related Posts:

  • @PutMapping in Spring Boot REST
  • Spring Boot Stereotype Annotations
  • Spring Core Annotations with Examples
  • Add H2 Database to Spring Boot with Spring Security: A Guide
  • Create Spring Boot Project with Spring Initializr
  • Spring Boot Actuator vs Spring Boot Starter Actuator
  • How to Use @Value Annotation in Spring
  • Spring RestTemplate Tutorial
  • Spring MVC Internationalization Tutorial
  • Spring Web MVC - Configure JSP Support

Powered by Contextual Related Posts

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

@GetMapping annotation in spring

@getmapping spring boot.

This article will cover @GetMapping annotation in spring boot with example.

Prior to 4.3, @RequestMapping along with method attribute as RequestMethod.GET was used to configure GET request handler method as shown below

With @GetMapping , above method can be replaced as

@GetMapping is followed by the string which signifies the URL for which this method will be exposed. So, @GetMapping is a shorthand annotation for @RequestMapping .

Spring docs state,

@GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET) .

Enabling @GetMapping @GetMapping is added in spring 4.3. So, in order to use it you need to have below dependency as per the build tool

or if you are using Spring boot, then add below dependency

@GetMapping annotation example Suppose you have a web application that accepts HTTP requests. You want to expose a URL that returns a list of all users. Since the method returns something, it will be an HTTP GET request handler method. It will be declared as

Now, suppose there is another method that returns details of a user based on an id and this id is received from the URL. Request handler method will be annotated with @GetMapping as shown below

Source Code Examples

Source Code Examples

Search this blog, @getmapping spring boot example, what is @getmapping.

@GetMapping  - shortcut for @RequestMapping(method = RequestMethod.GET)

Why Use @GetMapping?

@getmapping example, setting up the project , the model , the controller .

  • @GetMapping without any value returns a list of all books. 
  • @GetMapping("/{id}") returns a book with a specific ID.

Running the Application 

Conclusion , related java source code examples:, related spring boot source code examples, spring core annotations with examples, post a comment, our bestseller udemy courses.

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot + Apache Kafka - The Quickstart Practical Guide
  • Spring Boot + RabbitMQ (Includes Event-Driven Microservices)
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out discount coupons: Udemy Courses - Ramesh Fadatare

Spring @RestController, @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping Annotation Example

By Atul Rai | Last Updated: February 5, 2019 Previous       Next

This page will walk through Spring @RestController, @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping Annotation Example.  To handle the HTTP request in the application Spring Framework provides these annotations, some of annotated at the class level and some of at method level.

Related Post:   Spring MVC @Controller, @RequestMapping, @RequestParam, and @PathVariable Annotation Example

1. @RestController Annotation

@Restontroller annotation was introduced in Spring version 4. It is a convenience annotation that is itself annotated with @Controller and @ResponseBody .

A class annotated with @RestController annotation.

A class without using @RestController annotation.

Both above classes return the “Welcome to Websparrow” as output and if you do not add @ResponseBody annotation in ControllerDemo class, it will throw the exception.

@RestController = @Controller + @ResponseBody

2. @GetMapping Annotation

@GetMapping annotation is handled HTTP GET request and it is used at method level only. It was introduced in 4.3 version.

@GetMapping = @RequestMapping(value=”/home”, method = RequestMethod.GET)

3. @PostMapping Annotation

@PostMapping annotation is handled HTTP POST  request.  @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping( method = RequestMethod.POST) . It was also introduced in Spring 4.3 version.

@PostMapping = @RequestMapping(value=”/save”, method = RequestMethod.POST)

4. @PutMapping Annotation

@PutMapping annotation is used for mapping HTTP PUT requests onto specific handler methods. If you want to update existing data use @PutMapping annotation.

@PutMapping = @RequestMapping(value=”/update/{id}”, method = RequestMethod.PUT)

5. @DeleteMapping Annotation

@DeleteMapping annotation is handled HTTP DELETE  request.

@DeleteMapping = @RequestMapping(value=”/delete/{id}”, method = RequestMethod.DELETE)
  • Spring MVC @Controller, @RequestMapping, @RequestParam, and @PathVariable Annotation Example
  • @RestController
  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping

      Next

Similar Posts

  • Spring Boot- The Tomcat connector configured to listen on port 8080 failed to start
  • Spring Boot RESTful Web Service Example
  • Spring 5 method replacement example
  • Spring Boot – Handling Errors in WebClient
  • Display all beans name loaded by Spring Boot
  • Spring depends on attribute example
  • Spring Boot– Consuming a REST Services with WebClient
  • Spring Boot + RabbitMQ Example
  • Spring Boot- How to change default context path

About the Author

' src=

  • Java Tutorial
  • Java Spring
  • Spring Interview Questions
  • Java SpringBoot
  • Spring Boot Interview Questions
  • Spring MVC Interview Questions
  • Java Hibernate
  • Hibernate Interview Questions
  • Advance Java Projects
  • Java Interview Questions
  • Spring Boot - Application Properties
  • How to Set Context Path in Spring Boot Application?
  • Configuring Store Procedure in Spring Boot Application
  • How to Run Your First Spring Boot Application in Spring Tool Suite?
  • How to Run Spring Boot Application?
  • How Spring Boot Application Works Internally?
  • How to Run Your First Spring Boot Application in Eclipse IDE?
  • How to Create a Simple Spring Application?
  • How to Enable HTTPs in Spring Boot Application?
  • Deployment of Spring MVC Application on a Local Tomcat Server
  • How to Implement Simple Authentication in Spring Boot?
  • Spring Boot - application.yml/application.yaml File
  • Configure Multiple Datasource in Spring Boot Application
  • Spring - How to Load Literal Values From Properties File
  • How to create a basic application in Java Spring Boot
  • How To Dockerize A Spring Boot Application With Maven ?
  • Best Practices For Structuring Spring Boot Application
  • Containerizing Spring Boot Application
  • Spring Application Without Any .xml Configuration

How to Access Values From application.properties in Spring Boot?

In a Spring Boot application, application.properties is the central repository for defining configuration properties. These properties are accessible across the application to customize behavior. Accessing values from application.properties is a common requirement in Spring Boot projects.

Spring Boot automatically loads properties from application.properties files in the classpath. To access these properties in Spring components, we use annotations like @Value or the Environment object provided by Spring.

Key Terminologies:

  • application.properties : This is the file where Spring Boot application configuration properties are defined, usually located in the src/main/resources directory by default.
  • Properties : These key-value pairs are used for configuration in Spring Boot and are typically defined in the application.properties file.
  • @Value : This annotation in Spring is used to inject values ​​into Spring beans from properties files, environment variables, or system properties.
  • Placeholders : For Spring Boot, placeholders are expressions used in resolving property values ​​at runtime, usually specified with ${…} syntax.
  • Classpath: This is the location in the Java Virtual Machine where classes are stored. the application.properties file in the classpath is automatically loaded by Spring Boot.
  • Configuration Properties Binding : This provides a way to bind properties defined in application.properties to Java objects, simplifying the configuration and use of properties

Implementation to access values from application.properties in Spring Boot application

Below is the implementation steps to access values from application.properties in Spring Boot.

Create a new Spring Boot project using Spring Initializr and include the following dependencies:

  • Spring Devtools

Once the project is created, the file structure resembles the image below.

Folder Structure

Open the application.properties file and add the following properties:

Step 3: Create the Controller class

We will create the controller class to access values from the application.properties file.

Go to src > org.example.springvaluedemo > ExampleController and put the below code.

Open the main class(no need to changes in main class).

Go to src > org.example.springvaluedemo > SpringValueDemoApplication and put the below code.

Step 5: Run the Application

Once we run the application, then the project will run at port 8080.

Application Runs

API Endpoint:

Output in Browser

This example demonstrates the how to the access values from the application.properties into the Spring Boot application.

Please Login to comment...

Similar reads.

  • Java-Spring-Boot
  • Advance Java

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Spring Boot-2 (@GetMapping annotation)

    what is @getmapping annotation in spring boot

  2. all the annotations used in spring boot

    what is @getmapping annotation in spring boot

  3. java

    what is @getmapping annotation in spring boot

  4. all the annotations used in spring boot

    what is @getmapping annotation in spring boot

  5. Spring @GetMapping and @PostMapping with Examples

    what is @getmapping annotation in spring boot

  6. Learn Spring Boot by Annotations

    what is @getmapping annotation in spring boot

VIDEO

  1. What is REST API in Spring boot?

  2. Spring Boot CRUD

  3. 7. How to create GET REQUEST Using SPRING BOOT !!

  4. How to make Spring Data JPA handle Auditing

  5. 03-3 Spring Boot Application Annotation

  6. 8. How to create DELETE REQUEST Using SPRING BOOT !!!

COMMENTS

  1. Spring @GetMapping and @PostMapping with Examples

    Learn to create Spring WebMVC REST controllers with @Controller annotation and map HTTP requests with annotations like @RequestMapping, @GetMapping and @PostMapping in a Spring or Spring Boot application.. 1. Request Mapping Annotations. Before Spring 4.3, Spring had only @RequestMapping annotation for mapping all the incoming HTTP request URLs to the corresponding controller methods.

  2. Spring

    Spring - @PostMapping and @GetMapping Annotation. Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.

  3. @GetMapping Spring Boot Example

    In this tutorial, we will learn how to use @GetMapping annotation in a Spring Boot application to handle HTTP GET requests. @GETMapping Annotation Overview. The GET HTTP method is used to get a single resource or multiple resources and @GetMapping annotation for mapping HTTP GET requests onto specific handler methods. Specifically, @GetMapping is a composed annotation that acts as a shortcut ...

  4. GetMapping (Spring Framework 6.1.7 API)

    Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping (method = RequestMethod.GET) . NOTE: This annotation cannot be used in conjunction with other @RequestMapping annotations that are declared on the same method. If multiple @RequestMapping annotations are detected on the same method, a warning will be ...

  5. Spring @GetMapping

    Spring @GetMapping example. The following application uses @GetMapping to map two request paths onto handler methods. In this example, we use annotations to set up a Spring web application. pom.xml. src. ├───main. │ ├───java. │ │ └───com. │ │ └───zetcode.

  6. Spring @GetMapping, @PostMapping, @PutMapping, @DeleteMapping and

    The new approach makes it possible to shorten this simply to: Spring currently supports five types of inbuilt annotations for handling different types of incoming HTTP request methods which are GET, POST, PUT, DELETE, and PATCH. These annotations are: From the naming convention, we can see that each annotation is meant to handle the respective ...

  7. @GetMapping

    Learn how to create a GET mapping in the REST service that returns a list of POJOs as JSON. 1. Defining the PlayerService class. 2. Defining the getAllPlayers () method. Starting from this lesson, we will build a REST service that provides basic CRUD functionality. The client sends an HTTP request to the REST service.

  8. Spring Annotations @PostMapping, @GetMapping, @PutMapping and

    In this blog post, I will share the Spring annotations used to map HTTP requests to specific handler methods. These annotations include @PostMapping, @GetMapping, @PutMapping, and @DeleteMapping.. While most Spring Boot applications use the @RequestMapping annotation, which I will also cover in this post, I'll begin with the newer shortcut annotations that have been available since Spring 4.3.

  9. @GetMapping annotation in Spring boot with example

    This article will cover @GetMapping annotation in spring boot with example. @GetMapping annotation was introduced in Spring 4.3. It is applied over controller methods that handle HTTP GET requests. Prior to 4.3, @RequestMapping along with method attribute as RequestMethod.GET was used to configure GET request handler method as shown below.

  10. Spring & Spring Boot Annotations Series

    Hi, welcome to Spring & Spring Boot Annotations Series. In this video, we will learn how to use @GetMapping annotation in Spring boot applications.@GetMappin...

  11. Spring @RequestMapping

    Spring Framework 4.3 introduced a few new HTTP mapping annotations, all based on @RequestMapping: @GetMapping @PostMapping @PutMapping @DeleteMapping @PatchMapping; These new annotations can improve the readability and reduce the verbosity of the code. Let's look at these new annotations in action by creating a RESTful API that supports CRUD ...

  12. java

    With sprint Spring 4.3. and up things have changed. Now you can use @GetMapping on the method that will handle the http request. The class-level @RequestMapping specification is refined with the (method-level)@GetMapping annotation. Here is an example:

  13. Spring Boot controllers: @GetMapping and objects

    Aug 31, 2023. 1. If you have been working with Spring Boot long enough, writing a controller is something you can do in your sleep. Each night you dream about REST. You communicate with your wife ...

  14. Spring's RequestBody and ResponseBody Annotations

    2. @RequestBody. Simply put, the @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object. First, let's have a look at a Spring controller method: @RequestBody LoginForm loginForm) {. exampleService.fakeAuthenticate(loginForm);

  15. @GetMapping Spring Boot Example

    Spring @GetMapping example shows how to use @GetMapping annotation to map HTTP GET requests onto specific handler methods. What is @GetMapping? @GetMapping is a specialized version of the @RequestMapping annotation in Spring MVC. It is specifically tailored for HTTP GET requests. By using this annotation, you tell Spring that a particular method should respond to GET requests at a specified URL.

  16. Spring @PathVariable Annotation

    However, if the path variable name is different, we can specify it in the argument of the @PathVariable annotation: return "ID: " + employeeId; We can also define the path variable name as @PathVariable (value="id") instead of PathVariable ("id") for clarity. 4. Multiple Path Variables in a Single Request.

  17. Spring @RestController, @GetMapping, @PostMapping, @PutMapping, and

    This page will walk through Spring @RestController, @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping Annotation Example. To handle the HTTP request in the application Spring Framework provides these annotations, some of annotated at the class level and some of at method level.

  18. #8 Spring Boot Tutorial

    Spring Boot Tutorial - Hello everyone, In this video, you will learn how to use @GetMapping annotation in Spring Boot application.Spring Boot Tutorial for Be...

  19. Spring @RequestMapping New Shortcut Annotations

    All of the above annotations are already internally annotated with @RequestMapping and the respective value in the method element.. For example, if we'll look at the source code of @GetMapping annotation, we can see that it's already annotated with RequestMethod.GET in the following way: @Target({ java.lang.annotation.ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented ...

  20. How to Build Spring Boot Project in VSCode?

    Creating a Spring Boot project in Visual Studio Code (VS Code) streamlines the Java development experience. In this article, we'll explore the steps to set up and build a Spring Boot project in VS Code, ensuring a solid foundation to start developing robust applications. Step by Step process to the Build a Spring Boot Project in VS Code

  21. Spring Boot annotation @GetMapping can not be resolved to a type

    2. I tried creating a Spring Project from Spring Initializr for the first time in my local computer. But I am getting these errors @GetMapping cannot be resolved to a type. My pom.xml file-. <parent>. <groupId>org.springframework.boot</groupId>. <artifactId>spring-boot-starter-parent</artifactId>.

  22. Spring @RequestParam Annotation

    We can also do @RequestParam (value = "id") or just @RequestParam ("id"). 4. Optional Request Parameters. Method parameters annotated with @RequestParam are required by default. This means that if the parameter isn't present in the request, we'll get an error: GET /api/foos HTTP/1.1.

  23. How to Run a CommandLineRunner Bean Conditionally in Spring Boot

    In Spring Boot, CommandLineRunner is an interface used to execute code once the application startup is complete. ... Conditional execution in Spring Boot can be achieved using the @Conditional family of annotations provided by Spring. These annotations allow you to specify conditions under which the bean is included in the application context ...

  24. How to Access Values From application.properties in Spring Boot?

    Key Terminologies: application.properties: This is the file where Spring Boot application configuration properties are defined, usually located in the src/main/resources directory by default.; Properties: These key-value pairs are used for configuration in Spring Boot and are typically defined in the application.properties file. @Value: This annotation in Spring is used to inject values into ...