unit - 05
unit - 05
Spring Framework
Spring Framework
• Open-Source Framework
• Standalone and Enterprise application can be developed
• Released in 2003(initial), 2004(production) developed by Rod
Johnson
Advantages
• Modular and lightweight(lightweight and easy to maintain
applications)
• Flexible configuration(supports Java-based, XML-based and
annotation-based configurations)
• Dependency Injection(dependency management)
• Aspect oriented programming(Allows developers to separate code
from the features like logging, transactions, security etc.)
• Easy database handling(reduce boilerplate code increase efficiency)
• Testing support
• Security(robust framework for implementing authentication,
authorization)
• High integration capabilities(with other frameworks and technologies
like angular, react, JMS, SOAP, REST)
• High Scalability
• Open-Source
Modules
The Spring
Framework consists
of features organized
into about 20
modules. These
modules are grouped
into Core Container,
Data
Access/Integration,
Web, AOP (Aspect
Oriented
Programming),
Instrumentation, and
Test, as shown in the
following diagram.
Dependency?
• Example of dependency
• Code has very high degree of coupling due to aggregation
• To create Object of class Person, we depend on Address
Object, and to create Address object, we need contact
Inversion of Control (IoC)
• Inversion of Control (IoC) is a design principle that emphasizes keeping
Java classes independent of each other.
• IoC is achieved through Dependency Injection (DI).
• IoC refers to transferring the control of objects and their dependencies
from the main program to a container or framework.
• The IoC container uses two primary mechanisms to work:
Bean instantiation:
• The IoC container is responsible for creating and configuring beans. This
can be done through XML configuration, Java annotations, or a
combination of both.
Dependency injection:
• The IoC container injects dependencies into beans. This means that the
IoC container is responsible for providing beans with the objects they need
to function.
Spring Dependency Injection
• Dependency Injection (DI) is a design pattern that allows you to
decouple your code by making it easier to create and manage
objects.
• In Spring, DI is implemented using the Inversion of Control (IoC)
container. The IoC container is responsible for creating and
managing objects, and it injects them into your code when
needed.
• Dependency Injection is a fundamental aspect of the Spring
framework, through which the Spring container “injects” objects
into other objects or “dependencies”.
There are two types of Spring Dependency Injection.
• Setter Dependency Injection (SDI)
• Constructor Dependency Injection (CDI)
Spring Container
• The Spring container is the core of the Spring Framework.
• Manages Bean Objects(create, initialize, destroy)[Life cycle of
bean]
• It is responsible for creating, configuring, and managing the
objects that make up your application.
• The container uses a technique called dependency injection to
manage the relationships between objects.
• Transaction Management
Spring container are of TWO TYPES
1. Bean factory(old Method)
2. ApplicationContext(new Method)
Spring IoC (Inversion of Control) Spring Dependency Injection
Spring IoC Container is the core of Spring Spring Dependency injection is a way to inject the
Framework. It creates the objects, configures and dependency of a framework component by the
assembles their dependencies, manages their entire following ways of spring: Constructor Injection
life cycle. and Setter Injection
Spring helps in creating objects, managing objects, Spring framework helps in the creation of loosely-
configurations, etc. because of IoC (Inversion of coupled applications because of Dependency
Control). Injection.
IoC is a design principle where the control flow of Dependency Injection is one of the subtypes of the
the program is inverted. IOC principle.
4. Press finish
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.8</version>
</dependency>
10.
execute App.java
Aspect-Oriented Programming (AOP)
• Aspect-Oriented Programming (AOP) is a programming technique that allows
developers to modularize cross-cutting concerns. Cross-cutting concerns are
tasks that affect multiple parts of a program, such as logging, security, and
transaction management.
• AOP allows developers to separate these concerns from the main program
logic. This makes the code more modular, reusable, and maintainable.
• Spring AOP is a popular implementation of AOP. It provides a simple and
powerful way to write custom aspects.
• Spring provides simple and powerful ways of writing custom aspects by using
either a schema-based approach or the @AspectJ annotation style. Both of these
styles offer fully typed advice and use of the AspectJ pointcut language while still
using Spring AOP for weaving.
• AOP is used in the Spring Framework to:
• Provide declarative enterprise services. The most important such service
is declarative transaction management.
• Let users implement custom aspects, complementing their use of OOP with AOP.
Benefits of using AOP
Modularity:
• AOP allows developers to separate cross-cutting concerns from
the main program logic. This makes the code more modular,
reusable, and maintainable.
Reusability:
• Aspects can be reused across multiple projects. This saves
time and effort, and it can help to improve the consistency of
code.
Maintainability:
• AOP makes it easier to maintain code. This is because cross-
cutting concerns are separated from the main program logic.
This makes it easier to understand and modify the code.
BEAN SCOPE
• In the Spring Framework, a bean's scope determines how long it lives and how
many instances of it are created.
• The default scope is singleton, which means that only one instance of the bean
is created and shared across the entire application context. Other scopes include
prototype, request, session, and global session.
• The prototype scope creates a new instance of the bean each time it is
requested. This is useful for beans that are not thread-safe or that need to be
customized for each request.
• The request scope creates a new instance of the bean for each HTTP
request. This is useful for beans that need to be associated with a specific
request, such as a database connection or a shopping cart.
• The session scope creates a new instance of the bean for each user
session. This is useful for beans that need to be associated with a specific user,
such as a user profile or a shopping cart.
• The global session scope creates a new instance of the bean for each user
session across all applications in the same cluster. This is useful for beans that
need to be shared across multiple applications, such as a user profile or a
shopping cart.
BEAN SCOPE
• You can specify the scope of a bean using the @Scope
annotation. For example, the following code creates a bean with
the prototype scope:
@Scope("prototype")
public class MyBean {
// ...
}
OR
Autodetect(depre The autodetect mode uses two other modes for autowiring – constructor and
cated in Spring 3) byType.
1. No
This mode tells the framework that autowiring is not supposed to be done. It is the default
mode used by Spring.
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.
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.
<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.
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.
2. On a constructor: You can also use the @Autowired annotation on a constructor. This will cause Spring to
inject an instance of the dependency into the constructor when the bean is created.
public class MyBean {
private MyDependency dependency;
@Autowired
public MyBean(MyDependency dependency) {
this.dependency = dependency;
}
}
3. On a setter method: You can also use the @Autowired annotation on a setter method. This will cause
Spring to inject an instance of the dependency into the setter method when the bean is created.
The @Autowired annotation can be used on any field, constructor, or setter method that is declared in a
Spring bean. The dependency that is injected must be a Spring bean itself.
Life Cycle Call backs
• 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 we want to execute some code on
the bean instantiation and just after closing the spring container, then we
can write that code inside the custom init() method and
the destroy() method.
package com.kiet.FirstProject;
public class Employee { <bean name="employee" class="com.kiet.FirstProject.Employee"
private int eid;
private String name;
init-method="init" destroy-method="destroy">
public Employee() { <property name="eid" value="21"/>
super();
}
<property name="name" value="Rohit Sharma"/>
public Employee(int eid, String name) { </bean>
super();
this.eid = eid;
this.name = name;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getName() {
AbstractApplicationContext context=new
return name; ClassPathXmlApplicationContext("/com/kiet/FirstProject/conf.xml");
} Employee emp=context.getBean("employee",Employee.class);
public void setName(String name) {
this.name = name;
context.registerShutdownHook();
} System.out.println(emp);
public void init()
{
System.out.println("initialized");
}
public void destroy()
{
System.out.println("destroyed");
}
@Override
public String toString() {
return "Employee [eid=" + eid + ", name=" + name + "]";
}}
Bean Configuration styles in spring
framework
1. XML-based configuration: Traditional approach where beans are defined in
XML configuration files (applicationContext.xml).
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Spring Boot Runners
Spring Boot Runners are interfaces that allow you to execute code
when a Spring Boot application starts. They are typically used to
perform some initialization or setup tasks before the application starts
processing requests.
There are two types of runners:
CommandLineRunner:
• This is the legacy runner that was introduced in Spring Boot 1.0. It
has one abstract method, run(String... args): void.
ApplicationRunner:
• This is a newer runner that was introduced in Spring Boot 1.3. It has
one abstract method, run(ApplicationArguments args) throws
Exception.
The main difference between the two runners is that the
ApplicationRunner gives you access to the application arguments,
while the CommandLineRunner does not.
Logger
A logger in Spring Boot is a tool that helps developers track and
monitor the events that happen in their application. It is a crucial
part of any application, as it can help identify and fix errors, as
well as track performance and usage.
Spring Boot comes with a built-in logger, which is based on the
popular Logback logging framework. This logger can be used to
log messages to the console, to a file, or to a remote server.
Benefits of using a logger in Spring Boot:
• Improved debugging
• Better performance monitoring
• Increased security
• Enhanced compliance
BASICS OF WEB APPLICATIONS
• Localhost: In a computer network, localhost refers to the
computer you are using to send a loopback request. This
request is data from your computer acting as a virtual server,
which is sent back to itself without ever passing through a
physical network.
• Server at localhost refers to your own machine is
hosting(server) at “localhost” or http://127.0.0.1
• Spring Boot has inbuilt “tomcat-apache” server.(no external
installation is required.
<!DOCTYPE html>
<html> result
<head>
<meta charset="ISO-8859-1">
<title>Index</title>
</head>
<body>
<form action="#app" method="get"><br>
<input type="text" placeholder="Name"/><br>
On pressing submit button
<input type="password" placeholder="Password">
<input type="submit" value="submit">
Url is appended with request
</form>
Parmeters(get method)
</body>
</html>
PATCH
The PATCH method is used to update an existing resource. It is similar to PUT, except that PATCH
enables clients to update specific properties on a resource—without overwriting the others. For instance, if
you have a product resource with fields for name, brand, and price, but you only want to update the price,
you could use the PATCH method to send a request that only includes the new value for the price field.
The rest of the resource would remain unchanged. This behavior makes the PATCH method more flexible
and efficient than PUT.
DELETE
The DELETE method is used to remove data from a database. When a client sends a DELETE request, it
is requesting that the resource at the specified URL be removed. For example, a DELETE request to the
/products/123 endpoint will permanently remove the product with an ID of 123 from the database. Some
APIs may leverage authorization mechanisms to ensure that only clients with the appropriate permissions
are able to delete resources.
Creating “hello world” application in Spring Boot
Step 1: https://start.spring.io/
Step 2:
Step 3:
Press Generate
Step 4:
package com.kiet.FirstSBProject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@GetMapping("/hello")//END POINT -1
@ResponseBody
public String hello(@RequestParam(value = "name",
defaultValue = "World") String name) {
Step 9: Add controller return String.format("Hello %s!", name);
}
@GetMapping("/hi")//END POINT -2
@ResponseBody
public String hello() {
return "hi";
}
}
Purpose: For using Spring Data JPA with Hibernate for data persistence.
Includes: Spring Data JPA, Hibernate, JDBC, and necessary dependencies for
database access and ORM.
spring-boot-starter-security
Request Parameter:
•Request parameters are used to extract input data @ResponseBody
passed through an HTTP URL or passed as a query. public String hello(@RequestParam(value =
•You can use the @RequestParam annotation in "name", defaultValue = "World") String name) {
Spring Boot to extract input data passed through an return String.format("Hello %s!", name);
}
HTTP URL or passed as a query.
•Request parameters are typically used to filter data
or to pass additional information to the controller
method.
GET, POST, PUT, and DELETE
GET, POST, PUT, and DELETE are the four most common HTTP
methods used in Spring Boot.
• GET: is used to retrieve data from a server.
• POST: is used to create new data on a server.
• PUT: is used to update existing data on a server.
• DELETE: is used to delete data from a server.
• In Spring Boot, these methods are mapped to controller
methods using the @GetMapping, @PostMapping,
@PutMapping, and @DeleteMapping annotations,
respectively.