0% found this document useful (0 votes)
12 views

OOP With Java Unit 5 Final (1)

Uploaded by

therohitpatwa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

OOP With Java Unit 5 Final (1)

Uploaded by

therohitpatwa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

All Spring Framework

Spring Boot
Unit-5
Java Spring Framework
• Spring is a lightweight framework.
• It can be thought of as a framework of frameworks because it provides
support to various frameworks such as Struts, Hibernate, Tapestry,
EJB, JSF, etc.
• It was developed by Rod Johnson in 2003.
• Spring is a Dependency Injection Framework to make java application loosely
coupled.
• Spring framework makes the easy development of
JavaEE applications.
• The Spring framework comprises of several modules such as Core, Beans, IOC,
AOP, DAO, Context, ORM, WEB MVC etc.
Advantages of Spring Framework
1. Predefined Templates
• Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no need to write too much code. It hides the basic
steps of these technologies.

2. Loose Coupling
• The Spring applications are loosely coupled because of dependency injection.

3. Easy to test
• The Dependency Injection makes easier to test the application. The EJB or Struts application require server to run the application but Spring
framework doesn't require server.

4. Lightweight
• Spring framework is lightweight because of its POJO(Plain Old Java Object) implementation. The Spring Framework doesn't force the
programmer to inherit any class or implement any interface. That is why it is said non-invasive.

5. Fast Development
• The Dependency Injection feature of Spring Framework and it support to various
frameworks makes the easy development of JavaEE application.
6. Powerful abstraction
• It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.

7. Declarative support
• It provides declarative support for caching, validation, transactions and formatting.
Dependency Injection
It is a design pattern.
Inversion Of Control (IOC) and Dependency Injection
These are the design patterns that are used to remove dependency from the programming code. They
make the code easier to test and maintain.
Let's understand this with the following code:
class Employee{ Address address; Employee(){
address=new Address();
}
}
In such case, there is dependency between the Employee and Address (tight coupling).
IOC makes the code loosely coupled. In such case, there is no need to modify the code if our logic is
moved to new environment.
In Spring framework, IOC container is responsible to inject the dependency. We provide metadata to the
IOC container either by XML file or annotation.
Spring Modules
• The Spring framework comprises of many modules such as core, beans, context,
expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS, Transaction, Web, Servlet, Struts etc. These modules
are grouped into Test, Core Container, AOP, Aspects, Instrumentation, Data Access / Integration, Web (MVC / Remoting) as
displayed in the following diagram.
• Spring Core Container
• The Spring Core container contains core, beans, context and expression language
(EL) modules.
1. Core and Beans
• These modules provide IOC and Dependency Injection features.
2. Context
• This module supports internationalization (I18N), EJB, JMS, Basic Remoting.
3. Expression Language
• It is an extension to the EL defined in JSP. It provides support to setting and
getting property values, method invocation, accessing collections and indexers,
named variables, logical and arithmetic operators, retrieval of objects by name
etc.
• AOP, Aspects and Instrumentation
• These modules support aspect oriented programming implementation where
you can use Advices, Pointcuts etc. to decouple the code.

• The aspects module provides support to integration with AspectJ.

• The instrumentation module provides support to class instrumentation and


classloader implementations.
Data Access / Integration
• This group comprises of JDBC, ORM, OXM, JMS and Transaction modules.
These modules basically provide support to interact with the database.

• Web
• This group comprises of Web, Web-Servlet, Web-Struts and Web-Portlet. These
modules provide support to create web application.

• Test
• This layer provides support of testing with JUnit and TestNG.
Dependency Injection
• Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it
can be easy to manage and test the application.
• Dependency Injection makes our programming code loosely coupled and easier for testing.
• In such case we provide the information from the external source such as XML file.
Let‘s understand dependency injection with the following code:

class Employee{
Address address;
Employee(){
address=new
Address();
}
}
In such case, there is dependency between the Employee and Address (tight coupling)
In the Inversion of Control scenario(Dependency Injection), we do this something like
this:

class Employee{
Address
address;
Employee(Address address){
this.address=address;
}
public void setAddress(Address address){
this.address=address;
}
}
In such case, instance of Address class is provided by external souce such as XML file
either by constructor or setter method.
Two ways to perform Dependency Injection in Spring framework

• Spring framework provides two ways to inject dependency


• By Setter method
• By Constructor
1. Dependency Injection using Setter Method
class Student class Address
{ {

int id; String street;


String city; String
String name;
state; String
Address address;
country;
public void setStreet(String street)
public void setId(int id)
{
{
this.street=street;
this.id=id
}
} public void setCity(String city)
public void setName(String name) {
{ this.city=city;

this.name=name }
public void setState(String state)
}
{

public void setAddress(Address address) this.state=state;


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

} }}
2. Dependency Injection using Constructor Method
class Student
{
int id;
String name;
Address address;
public Student(int id, String name, Address address)
{
this.id=id;
this.name=name;
this.address=address;
}
}

class Address
{
String street;
String city;
String state;
String country;
public Address(String street, String city, String State, String country)
{
this.street=street;
this.city=city;
this.state=state;
this.country=country;
}
}
IoC Container
• The IoC container is responsible to instantiate, configure and assemble the
objects. The IoC container gets information from the XML file and works
accordingly. The main tasks performed by IoC container are:
• to instantiate the application class
• to configure the object
• to assemble the dependencies between the objects

• There are two types of IoC containers. They are:


• BeanFactory
• ApplicationContext
Difference between BeanFactory and the ApplicationContext

• The org.springframework.beans.factory.BeanFactory and the


org.springframework.context.ApplicationContext interfaces acts as the IoC container. The
ApplicationContext interface is built on top of the BeanFactory interface. It adds some
extra functionality than BeanFactory such as simple integration with Spring's AOP,
message resource handling (for I18N), event propagation, application layer specific
context (e.g. WebApplicationContext) for web application. So it is better to use
ApplicationContext than BeanFactory.
Using BeanFactory
• The XmlBeanFactory is the implementation class for the BeanFactory interface. To use
the BeanFactory, we need to create the instance of XmlBeanFactory class as given
below:
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);

The constructor of XmlBeanFactory class receives the Resource object so we need to pass
the resource object to create the object of BeanFactory.
Using ApplicationContext
• The ClassPathXmlApplicationContext class is the implementation class of
ApplicationContext interface. We need to instantiate the
ClassPathXmlApplicationContext class to use the ApplicationContext as given below:

ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");

The constructor of ClassPathXmlApplicationContext class receives string, so we can pass


the name of the xml file to create the instance of ApplicationContext.
Developing Spring Application

• To create Spring application, we are required to perform following steps :


1. create the class
2. create the xml file to provide the values
3. create the test class
4. Load the spring jar files
5. Run the test class
1. Creating Java Class
public class Student {
private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public void displayInfo(){


System.out.println("Hello: "+name);
}
}

This is simple bean class, containing only one property name with its getters and setters method. This
class contains one extra method named displayInfo() that prints the student name by the hello message.
2. Creating xml file
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="studentbean" class="Student">


<property name="name" value=“Amit Kumar"></property>
</bean>

</beans>

The bean element is used to define the bean for the given class. The property subelement of bean
specifies the property of the Student class named name. The value specified in the property element will
be set in the Student class object by the IOC container.
3. Creating Test Class
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class Test {


public static void main(String[] args) {
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);

Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}

The Resource object represents the information of applicationContext.xml file. The Resource is the interface and the
ClassPathResource is the implementation class of the Reource interface. The BeanFactory is responsible to return the
bean. The XmlBeanFactory is the implementation class of the BeanFactory. There are many methods in the BeanFactory
interface. One method is getBean(), which returns the object of the associated class.
4. Load the jar files required for spring framework

• There are mainly three jar files required to run this application.
• org.springframework.core-3.0.1.RELEASE-A
• com.springsource.org.apache.commons.logging-1.1.1
• org.springframework.beans-3.0.1.RELEASE-A

5. Run the test class

• Now run the Test class. You will get the output Hello: Amit Kumar
AOP (Aspect Oriented Programming)
• One of the key components of Spring Framework is the Aspect oriented programming (AOP) framework.
Aspect-Oriented Programming entails breaking down program logic into distinct parts called so-called
concerns. The functions that span multiple points of an application are called cross-cutting concerns and
these cross-cutting concerns are conceptually separate from the application's business logic. There are
various common good examples of aspects like logging, auditing, declarative transactions, security, caching,
etc.
• The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect.
Dependency Injection helps you decouple your application objects from each other and AOP helps you
decouple cross-cutting concerns from the objects that they affect. AOP is like triggers in programming
languages such as Perl, .NET, and others.
• Spring AOP module provides interceptors to intercept an application. For example, when a method is
executed, you can add extra functionality before or after the method execution.
Spring - Bean
• The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans.

• A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.

• These beans are created with the configuration metadata that you supply to the container. For example, in the form of XML <bean/> definitions
which we have already seen.

Example :

<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
-

<!-- A simple bean definition -->


<bean id="studentbean" class="Student">
<property name="name" value=“Amit Kumar"></property>
</bean>

</beans>
Bean Scopes

• When defining a <bean> we have the option of declaring a scope for that bean.
The Spring Framework supports the following five scopes :
1. singleton
2. prototype
3. request
4. session
5. global-session
1. Singleton Scope
• If a scope is set to singleton, the Spring IoC container creates exactly one
instance of the object defined by that bean definition. This single instance is
stored in a cache of such singleton beans, and all subsequent requests and
references for that named bean return the cached object.
• The default scope is always singleton.
• The scope property can be set to singleton in the bean configuration file, as follows :

<!-- A bean definition with singleton scope -->


<bean id = "..." class = "..." scope = "singleton">
<!-- collaborators and configuration for this bean go here -->
</bean>
2. Prototype Scope
• If the scope is set to prototype, the Spring IoC container creates a new bean instance
of the object every time a request for that specific bean is made.
• As a rule, use the prototype scope for all state-full beans and the singleton scope for
stateless beans.
• The scope property can be set to prototype in the bean configuration file, as follows :

<!-- A bean definition with singleton scope -->


<bean id = "..." class = "..." scope = “prototype">
<!-- collaborators and configuration for this bean go here -->
</bean>
3. Request Scope
• This creates a single bean instance per HTTP request.
• It is valid only in the context of a web application.

4. Session Scope
• This creates a single bean instance per HTTP session.
• It is valid only in the context of a web application.

5. GlobalSession Scope
• This creates a single bean instance per global HTTP session.
• It is valid only in the context of a web application.
Bean Life Cycle
• Bean life cycle is managed by the spring container.
• When we run the program then, first of all, the spring container gets started.
• After that, the container creates the instance of a bean as per the request, and then
dependencies are injected.
• And finally, the bean is destroyed when the spring container is closed.
• Therefore, if you want to execute some code on the bean instantiation and just after
closing the spring container, then you can write that code inside the custom init()
method and the destroy() method.
Note: We can choose a custom method name instead of init() and destroy()
The following figure shows the process flow of the bean life cycle :
Implementing Life Cycle of a Bean
• To implement life cycle of a bean , we are required to perform following steps :
1. Firstly, we need to create a bean and define the init() and destroy()
methods in the class.
2. Now, we need to configure the XML file and need to register the
init() and destroy() methods in it.
3. Finally, we need to create a test class to run this bean.
1. Creating a bean
public class Student {
private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public void displayInfo(){ System.out.println("Hello: "+name);


}
public void init(){
System.out.println("Bean is going through init.");
}
public void destroy() { System.out.println("Bean will destroy
now.");
}
}
2. Creating xml file
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="studentbean" class="Student“ init-method = "init"


destroy-method = "destroy">

<property name="name" value=“Amit Kumar"></property>


</bean>

</beans>
3. Creating Test Class
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class Test {


public static void main(String[] args) {
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);

Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}

Output :
Bean is going through init.
Hello : Amit Kumar
Bean will destroy now.
Spring - Autowiring

• Autowiring in the Spring framework can inject dependencies automatically.


• The Spring container detects those dependencies specified in the configuration file and
the relationship between the beans. This is referred to as Autowiring in Spring.
• To enable Autowiring in the Spring application we should use @Autowired annotation.
• Autowiring in Spring internally uses constructor injection.
• An autowired application requires fewer lines of code comparatively but at the same
time, it provides very little flexibility to the programmer.
Autowiring Modes

1. No
• This mode tells the framework that autowiring is not supposed to be done. It is the default mode
used by Spring.

Example :

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City"></bean>
2. byName
• It uses the name of the bean for injecting dependencies. However, it requires that the name of the
property and bean must be the same. It invokes the setter method internally for autowiring.

Example :

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byName"></bean>
3. byType
• It injects the dependency according to the type of the bean. It looks up in the configuration file for
the class type of the property. If it finds a bean that matches, it injects the property. If not, the
program throws an error. The names of the property and bean can be different in this case. It
invokes the setter method internally for autowiring.
• Example :

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byType"></bean>
4. constructor
• It injects the required dependencies by invoking the constructor. It works similar to the “byType”
mode but it looks for the class type of the constructor arguments. If none or more than one bean
are detected, then it throws an error, otherwise, it autowires the “byType” on all constructor
arguments.
• Example :

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="constructor"></bean>
5. autodetect
• The autodetect mode uses two other modes for autowiring – constructor and byType. It first tries to
autowire via the constructor mode and if it fails, it uses the byType mode for autowiring. It works in
Spring 2.0 and 2.5 but is deprecated from Spring 3.0 onwards.
• Example :

<bean id="state" class="sample.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire=“autodetect"></bean>
Spring Framework Annotations
• 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

Types of Spring Framework Annotations


Basically, there are 6 types of annotation available in the whole spring framework.
1. Spring Core Annotations
2. Spring Web Annotations
3. Spring Boot Annotations
4. Spring Scheduling Annotations
5. Spring Data Annotations
6. Spring Bean Annotations
What is Web Socket?
• A Web Socket is a continuous two-way communication channel between clients and servers. The client could be any
web browser, and the server could be any backend system. Using the HTTP request/response connections, the
WebSocket can transmit any number of protocols and can provide server-to- client information without polling. It
allows two-way data transfer in which we can simultaneously transfer data from client to server and vice versa.
• The advanced technology opens an interactive two-way communication between the client and server. By using the
WebSocket API, we can send information to the server and receive the runtime response without polling the server
for a response.
• The below image explains how WebSocket transfers the data:
What is Spring Boot?

• Spring Boot is an open-source Java framework used to create a Micro Service.


• Spring boot is developed by Pivotal Team, and it provides a faster way to set up
and an easier, configure, and run both simple and web-based applications.
• It is a combination of Spring Framework and Embedded Servers.
• The main goal of Spring Boot is to reduce development, unit test, and
integration test time and in Spring Boot, there is no requirement for XML
configuration.
Advantages
• Easy to understand and develop spring applications
• Increases productivity
• Reduces the development time
Goals
• To avoid complex XML configuration in Spring
• To develop a production ready Spring applications in an easier way
• To reduce the development time and run the application
independently
• Offer an easier way of getting started with the application
How does it work?
• Spring Boot automatically configures your application based on the dependencies
you have added to the project by
using @EnableAutoConfiguration annotation. For example, if MySQL database is
on your classpath, but you have not configured any database connection, then
Spring Boot auto-configures an in-memory database.
• The entry point of the spring boot application is the class contains
@SpringBootApplication annotation and the main method.
• Spring Boot automatically scans all the components included in the project by
using @ComponentScan annotation.
Spring Boot Starters
• Handling dependency management is a difficult task for big projects. Spring Boot resolves this
problem by providing a set of dependencies for developers convenience.
• For example, if you want to use Spring and JPA for database access, it is sufficient if you
include spring-boot-starter-data- jpa dependency in your project.
Examples :
following are Spring Boot starters explained below for a better understanding :
1. Spring Boot Starter Actuator dependency is used to monitor and manage your application.
Its code is shown below −

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2. Spring Boot Starter Security dependency is used for Spring Security. Its code is shown below −

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3. Spring Boot Starter Thyme Leaf dependency is used to create a web application. Its code is shown
below −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
4. Spring Boot Starter Test dependency is used for writing Test cases. Its code is shown below −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
Spring Boot - Build Systems
In Spring Boot, choosing a build system is an important task. Maven or Gradle is recommend as
they provide a good support for dependency management. Spring does not support well other build
systems.
• Dependency Management
Spring Boot team provides a list of dependencies to support the Spring Boot version for its every release. You do not need to
provide a version for dependencies in the build configuration file. Spring Boot automatically configures the dependencies
version based on the release. Remember that when you upgrade the Spring Boot version, dependencies also will upgrade
automatically.

Note − If you want to specify the version for dependency, you can specify it in your configuration file.
However, the Spring Boot team highly recommends that it is not needed to specify the version for
dependency.
Maven Dependency
For Maven configuration, we should inherit the Spring Boot Starter parent project
to manage the Spring Boot Starters dependencies. For this, simply we can inherit
the starter parent in our pom.xml file as shown below.

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
Gradle Dependency
We can import the Spring Boot Starters dependencies directly into build.gradle file.
We do not need Spring Boot start Parent dependency like Maven for Gradle.
Observe the code given below −

buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}") }
Spring Boot - Code Structure

Spring Boot does not have any code layout to work with. However, there are some best
practices as follows :
Default package
A class that does not have any package declaration is considered as a default package. Note
that generally a default package declaration is not recommended. Spring Boot will cause issues
such as malfunctioning of Auto Configuration or Component Scan, when you use default
package.

Note − Java's recommended naming convention for package declaration is reversed


domain name. For example − com.ee.myproject
Typical Layout
The typical layout of Spring Boot application will be as follows:
Spring Boot - Runners
Application Runner and Command Line Runner interfaces lets you to execute the
code after the Spring Boot application is started. You can use these interfaces to perform any actions immediately after the
application has started. This chapter talks about them in detail.

• Application Runner
Application Runner is an interface used to execute the code after the Spring Boot application started. The example given
below shows how to implement the Application Runner interface on the main class file.

package com.iimt.demo;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("Hello World from Application Runner");
}
}
Command Line Runner
• Command Line Runner is an interface. It is used to execute the code after the Spring Boot application
started. The example given below shows how to implement the Command Line Runner interface on the
main class file.

package com.iimt.demo;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... arg0) throws Exception {
System.out.println("Hello world from Command Line Runner");
}
}
Spring Boot - Logging
• Spring Boot uses Apache Commons logging for all internal logging. Spring Boot’s default configurations provides a support for the
use of Java Util Logging, Log4j2, and Logback. Using these, we can configure the console logging as well as file logging.

• If you are using Spring Boot Starters, Logback will provide a good support for logging. Besides, Logback also provides a use of good
support for Common Logging, Util Logging, Log4J, and SLF4J.

Log Format
• The default Spring Boot Log format is shown in the screenshot given below.

which gives you the following information −

• Date and Time that gives the date and time of the log
• Log level shows INFO, ERROR or WARN
• Process ID
• The --- which is a separator
• Thread name is enclosed within the square brackets []
• Logger Name that shows the Source class name
• The Log message
Building RESTful Web Services
• Spring Boot provides a very good support to build RESTful Web Services for enterprise
applications.
• For building a RESTful Web Services, we need to add the Spring Boot Starter Web dependency into the
build configuration file.
If you are a Maven user, use the following code to add the below dependency in your pom.xml file −

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

If you are a Gradle user, use the following code to add the below dependency in your build.gradle file

compile('org.springframework.boot:spring-boot-starter-web')
Rest Controller
• The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and
custom response. Its syntax is as follows −

@RestController
public class ProductServiceController {
}

Request Mapping
• The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We
can define Request method to consume and produce object. The default request method is GET.

@RequestMapping(value = "/products")
public ResponseEntity<Object> getProducts() { }
Request Body
• The @RequestBody annotation is used to define the request body content type.

public ResponseEntity<Object> createProduct(@RequestBody Product


product) {
}

Path Variable
• The @PathVariable annotation is used to define the custom or
dynamic request URI. The Path variable in request URI is defined as
curly braces {} as shown below −

public ResponseEntity<Object> updateProduct(@PathVariable("id")


String id) {
}
Request Parameter
• The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it is a
required parameter. We can also set default value for request parameters as shown here −

public ResponseEntity<Object> getProduct(


@RequestParam(value = "name", required = false, defaultValue =
"honey") String name) {
}
GET API
• The default HTTP request method is GET. This method does not require any Request Body. You can send request parameters and path variables to define the custom or dynamic URL.

• The sample code to define the HTTP GET request method is shown below. In this example, we used HashMap to store the Product. Note that we used a POJO class as the product to be stored.

• Here, the request URI is /products and it will return the list of products from HashMap repository. The controller class file is given below that contains GET method REST Endpoint.

package com.iimt.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.iimt.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
Product almond = new Product();
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}}
POST API
• The HTTP POST request is used to create a resource. This method contains the Request Body. We can send request parameters and path variables to define the custom or dynamic URL.

• The following example shows the sample code to define the HTTP POST request method. In this example, we used HashMap to store the Product, where the product is a POJO class.

• Here, the request URI is /products, and it will return the String after storing the product into HashMap repository.

package com.iimt.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.iimt.demo.model.Product;

@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();

@RequestMapping(value = "/products", method = RequestMethod.POST)


public ResponseEntity<Object> createProduct(@RequestBody Product product) {
productRepo.put(product.getId(), product);
return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
}
}

PUT API
The HTTP PUT request is used to update the existing resource. This method contains a Request Body. We can send request parameters and
path variables to define the custom or dynamic URL.

• The example given below shows how to define the HTTP PUT request method. In this example, we used HashMap to update the existing Product, where the product is a POJO class.

• Here the request URI is /products/{id} which will return the String after a the product into a HashMap repository. Note that we used the Path variable {id} which defines the products ID that needs to be
updated.

package com.iimt.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.iimt.demo.model.Product;

@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();

@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)


public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
}
}
DELETE API
• The HTTP Delete request is used to delete the existing resource. This method does not contain any Request Body. We can send request
parameters and path variables to define the custom or dynamic URL.

• The example given below shows how to define the HTTP DELETE request method. In this example, we used HashMap to remove the existing product, which is a POJO class.

• The request URI is /products/{id} and it will return the String after deleting the product from HashMap repository. We used the Path variable
{id} which defines the products ID that needs to be deleted.

package com.tutorialspoint.demo.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tutorialspoint.demo.model.Product;

@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();

@RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)


public ResponseEntity<Object> delete(@PathVariable("id") String id) {
productRepo.remove(id);
return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
}
}
Join us and subscribe our Chenal

You might also like