OOP With Java Unit 5 Final (1)
OOP With Java Unit 5 Final (1)
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.
• 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
this.name=name }
public void setState(String state)
}
{
} }}
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
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");
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">
</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;
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
• 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 :
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
-
</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 :
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;
</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;
Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}
Output :
Bean is going through init.
Hello : Amit Kumar
Bean will destroy now.
Spring - Autowiring
1. No
• This mode tells the framework that autowiring is not supposed to be done. It is the default mode
used by Spring.
Example :
Example :
<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.
• 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.
• 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.
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 −
• 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<>();
• 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<>();
• 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<>();