0% found this document useful (0 votes)
43 views68 pages

Unit-5 - Updated. Uhv Baa Hs

The document provides an overview of the Spring Framework and Spring Boot, detailing core concepts such as Dependency Injection, Inversion of Control, and various modules within the Spring ecosystem. It highlights the advantages of using Spring, including simplified development, modularity, and high integration capabilities. Additionally, it outlines how to create and manage beans in Spring through different configuration methods, along with a step-by-step example of building a Spring application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views68 pages

Unit-5 - Updated. Uhv Baa Hs

The document provides an overview of the Spring Framework and Spring Boot, detailing core concepts such as Dependency Injection, Inversion of Control, and various modules within the Spring ecosystem. It highlights the advantages of using Spring, including simplified development, modularity, and high integration capabilities. Additionally, it outlines how to create and manage beans in Spring through different configuration methods, along with a step-by-step example of building a Spring application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Unit-5

Spring Framework: Spring Core Basics-Spring Dependency Injection concepts, Spring Inversion of
Control, AOP, Bean Scopes- Singleton, Prototype, Request, Session, Application, Web Socket, Auto
wiring, Annotations, Life Cycle Call backs, Bean Configuration styles

Spring Boot: Spring Boot Build Systems, Spring Boot Code Structure, Spring Boot Runners, Logger,
BUILDING RESTFUL WEB SERVICES, Rest Controller, Request Mapping, Request Body, Path
Variable, Request Parameter, GET, POST, PUT, DELETE APIs, Build Web Applications
Spring Framework (Open-Source Framework)
Spring is a Java-based framework used to build Standalone and enterprise-level
applications, web apps, REST APIs, and microservices.
• Released in 2003(initial), 2004(production) developed by Rod Johnson
It helps developers write clean, loosely coupled, testable, and maintainable code using:
• Inversion of Control (IoC)
• Dependency Injection (DI)
• Aspect-Oriented Programming (AOP)
Why Do We Need Spring Framework?
Problems Before Spring:
Java EE (Java 2 Enterprise Edition) apps used EJBs, which were:
• Complex to configure
• Hard to test
• Heavy and slow
• Required lots of boilerplate code
How Spring Solves These:
• Simplifies development with auto-wiring and annotations
• Removes boilerplate code
• Supports loose coupling using DI
• Improves testability (easy unit testing)
• Modular – use only what you need
• Integrates easily with Hibernate, JDBC, and more
➢ Spring is a powerful Java framework that simplifies enterprise software development. With support
for dependency injection, aspect-oriented programming, and a wide range of tools, Spring is the
backbone of modern Java development.
Spring Ecosystem (Major Modules)
1. Spring Core 5. Spring Boot
• Provides IoC and DI • Provides ready-to-use, production-grade
• Foundation of the framework Spring applications
2. Spring AOP • No XML configuration required
• Used for cross-cutting concerns like logging, • Auto-configures most settings
security, etc. 6. Spring Security
3. Spring JDBC / Spring ORM • Handles authentication and authorization
• Simplifies database access 7. Spring Cloud
• Integrates with JDBC, Hibernate, JPA, etc. • For microservices, service discovery, config
4. Spring Web / Spring MVC servers, etc.
• For building web applications and RESTful 8. Spring Batch
APIs • For large-scale batch processing
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.
1. Core Container This is the foundation of the Spring Framework and is responsible for dependency
injection (DI) and bean life cycle management. Beans: Manages bean configuration and instantiation.
Core: Provides the core functionalities like the IoC (Inversion of Control) container. Context: A
configuration interface that accesses objects in a framework-style manner. Expression Language
(SpEL): A powerful expression language for querying and manipulating an object graph at runtime.
2. Data Access / Integration These modules simplify working with databases and messaging
systems': Simplifies database access by handling resource management and error handling. ORM
(Object-Relational Mapping): Supports integration with ORM frameworks like Hibernate, JPA, etc.
OXM (Object XML Mapping): Helps in converting Java objects to XML and vice versa. MS (Java
Messaging Service): Simplifies message sending and receiving. Transactions: Supports
programmatic and declarative transaction management for classes.
3. Web (MVC / Remoting)These modules are used for developing web applications. Web: Provides
basic web-oriented integration features. Servlet: Works with Java Servlet API. Portlet: Helps in
developing JSR-168 portlet applications. Struts: Provides support for integrating with Apache Struts.
4. AOP (Aspect-Oriented Programming)Used to separate cross-cutting concerns (like logging,
security, etc.) from business logic: Provides support for aspect-oriented programming. Aspects:
Offers integration with AspectJ (a popular AOP framework).
5. Instrumentation Supports class instrumentation and class loader implementations, useful in
application servers or development tools.
6. TestSupports testing of Spring components using JUnit or TestNG.
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

Spring Framework helps reduce this kind of coupling using Dependency Injection (DI).
//Contact.java //Address.java
public class Contact { public class Address {
private double mob; private int streetNo;
private String email; private String city;
public Contact(double mob, String email) { private String state;
this.mob = mob; private Contact contact;
this.email = email; public Address(int streetNo, String city, String state,
} Contact contact) {
this.streetNo = streetNo;
public void display() {
System.out.println("Mobile: " + mob + ", Email: this.city = city;
" + email); this.state = state;
} this.contact = contact;
} }
public void display() {
System.out.println("Street No: " + streetNo + ",
City: " + city + ", State: " + state);
contact.display();
}
}
//Person.java Main.java
public class Person { public class Main {
private int adhaar; public static void main(String[] args) {
private String name; Contact contact = new Contact(9876543210L,
"[email protected]");
private Address address; Address address = new Address(12, "Kanpur",
public Person(int adhaar, String name, Address "UP", contact);
address) { Person person = new Person(123456789,
this.adhaar = adhaar; "Anuj", address);
this.name = name;
this.address = address; person.display();
}
}
}
public void display() {
System.out.println("Adhaar: " + adhaar + ",
Name: " + name);
address.display();
}
}
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. Meaning that the framework controls
the program flow rather than the developer.
• 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. Beanfactory (old Method)
2. ApplicationContext (new Method)
Bean in Spring?
A Bean is just a Java object that is managed by the Spring Framework. It is
automatically injected where needed. It makes your code clean, reusable, and testable.
Example
public class Student {
private String name;
// constructor, getters, setters
}
This is just a normal Java class. But if you want Spring to create and manage it (like
calling the constructor, setting values, managing lifecycle), you need to register it as a
Bean. Once it's a Bean, Spring will take care of creating it and giving it wherever
needed.
How to Make a Bean?
There are three ways:
1. XML Configuration (Old style)
<bean id="student" class="com.example.Student"/>

2. Annotation-based
@Component
public class Student { }

3. Java-based Configuration
@Configuration
public class AppConfig {
@Bean
public Student student() {
return new Student();
}
}
Step-by-Step Spring Core Example:
Create a Spring application where:
1. A Student object is created and configured by Spring.
2.We fetch and display student details from the Spring Container.
Step 1: Project Structure
spring-student-app/
├── src/
│ ├── com/example/model/Student.java
│ ├── com/example/config/AppConfig.java
│ └── MainApp.java
├── pom.xml (if using Maven)
Add Spring Core Dependency
If you're using Maven, use this pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0"
<project> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<modelVersion>4.0.0</modelVersion> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
<groupId>com.example</groupId> http://maven.apache.org/xsd/maven-4.0.0.xsd">
<artifactId>spring-student-app</artifactId> <!-- Project Details -->
<version>1.0</version> <modelVersion>4.0.0</modelVersion>
<dependencies> <groupId>com.example</groupId>
<!-- Spring Core --> <artifactId>spring-student-app</artifactId>
<dependency> <version>1.0</version>
<groupId>org.springframework</groupId> <dependencies>
<artifactId>spring-context</artifactId> <!-- Spring Core and Context Dependency (We need this to use
<version>5.3.32</version> @Configuration, @Bean, ApplicationContext) -->

</dependency> <dependency>

</dependencies> <groupId>org.springframework</groupId>
</project> <artifactId>spring-context</artifactId>
<version>5.3.32</version> <!-- Use latest stable version -->
Note: get the latest version from </dependency>
https://mvnrepository.com by searching spring-context </dependencies>
</project>
Step 3: Create the Student Class public String getName() {
//com/example/model/Student.java return name;
package com.example.model; }
public class Student { public int getAge() {
private String name; return age;
private int age; }
public Student() { public void displayInfo() {
System.out.println("Student object System.out.println("Student Name: " +
created"); name);
} System.out.println("Student Age: " + age);
// Setters and Getters }
public void setName(String name) { }
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
Step 4: Create Java-based Configuration
//com/example/config/AppConfig.java student.setAge(21);
package com.example.config; return student;
import com.example.model.Student; }
import org.springframework.context.annotation.Bean; }
import org.springframework.context.annotation.Configuration;
// Tells Spring that this class contains bean definitions Note:

@Configuration Spring looks for classes annotated with


@Configuration and uses them to configure
public class AppConfig { beans.
// This method tells Spring to create and manage a 'student' bean AppConfig.java is where you define how your
@Bean application’s beans (objects) are created,
configured, and managed by Spring using Java
public Student student() { code
Student student = new Student();
student.setName("Rahul");
Step 4: Main Application
//MainApp.java public class MainApp {
import com.example.model.Student; public static void main(String[] args) {
import com.example.config.AppConfig; // Create Spring container using Java-based config class
import ApplicationContext context = new
org.springframework.context.ApplicationContext; AnnotationConfigApplicationContext(AppConfig.class);
import // Ask Spring to give the 'student' bean
org.springframework.context.annotation.AnnotationC
Student student = context.getBean(Student.class);
onfigApplicationContext;
// Use the student object
student.displayInfo();
}
}
Example: Step-by-Step Procedure to Create Maven Spring Project in Eclipse using
Constructor Injection
Step 1: Create a Maven Project Step 2: Project Structure
Eclipse creates the following folder structure:
1. Open Eclipse
SpringXMLConstructorDemo/
2. Go to File → New → Other… └── src/
3. Select Maven Project → Next ├── main/
│ ├── java/
4. Check Create a simple project (skip archetype
│ │ └── com/example/Address.java
selection) → Next
│ │ └── com/example/Person.java
5. Enter: │ │ └── com/example/MainApp.java
o Group Id: com.example │ └── resources/
o Artifact Id: SpringXMLConstructorDemo │ └── beans.xml

o Click Finish
Step 3: Add Spring Dependencies in pom.xml <dependencies>
Open pom.xml and replace it with: <!-- Spring Core -->
<project xmlns="http://maven.apache.org/POM/4.0.0" <dependency>
xmlns:xsi="http://www.w3.org/2001/XMLSchema- <groupId>org.springframework</groupId>
instance"
<artifactId>spring-context</artifactId>
xsi:schemaLocation="http://maven.apache.org/POM/4.0. <version>5.3.36</version>
0
</dependency>
http://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <!-- Commons Logging (used internally by
<groupId>com.example</groupId> Spring) -->
<artifactId>SpringXMLConstructorDemo</artifactId> <dependency>
<version>1.0-SNAPSHOT</version> <groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>
Step 4: Create Java Classes //Person.java
//Under src/main/java/com/example/, package com.example;
create:Address.java
public class Person {
package com.example; private Address address;
public class Address { private String name;
private String city;
public Person(Address address, String name) {
public Address(String city) { this.address = address;
this.city = city; this.name = name;
}
}
public void display() { public void show() {
System.out.println("City: " + city); System.out.println("Person details: " + name);
}
address.display();
} }
}
//MainApp.java
package com.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Person person = (Person) context.getBean("personBean");
person.show();
}
}
Step 5: Create XML Configuration
Under src/main/resources/, create a file beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-
beans.xsd">
<!-- Address Bean -->
<bean id="addressBean" class="com.example.Address">
<constructor-arg value="Kanpur"/>
</bean> Step 6: Run the Application
<!-- Person Bean -->
•Right-click on MainApp.java →
<bean id="personBean" class="com.example.Person">
<constructor-arg ref="addressBean"/> Run As → Java Application
<constructor-arg value="Anuj Kumar"/>
</bean>

</beans>
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 and
life cycle. 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.

Dependency Injection is the method of providing the


Spring IoC is achieved through Dependency
dependencies and Inversion of Control is the end
Injection.
result of Dependency 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.

Aspect-Oriented Programming, Dependency look up In case of any changes in business requirements, no


are other ways to implement Inversion of Control. code change is required.
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 OOPs 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.
Key Concepts in AOP
• Aspect: A module that encapsulates a cross-cutting concern
(e.g., logging aspect).
• Join Point: A specific point in the program flow (e.g., method call,
exception thrown).
• Advice: Code that is executed at a join point (e.g., before, after, or
around).
• Pointcut: A predicate that matches join points (e.g., "all methods
in package X").
• Weaving: The process of linking aspects with other application
types or objects.
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

<bean class="com.test.DIDemo.Employee" name="stud1"


scope="request">
<property…
</bean>
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.
• 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.
public class Car {
@Autowired
private Engine engine; // Injected automatically
}
Modes Description
This mode tells the framework that autowiring is not supposed to be done. It is the
No
default mode used by Spring.

byName It uses the name of the bean for injecting dependencies.

byType It injects the dependency according to the type of bean.

Constructor It injects the required dependencies by invoking the constructor.

Autodetect(depre
The autodetect mode uses two other modes for autowiring – constructor and byType.
cated in Spring 3)

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.

<bean id="state" class=“pack.State">


<property name="name" value="UP" />
</bean>
<bean id="city" class=“pack.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.
<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.

<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.

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


<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="autodetect"></bean>
class City { package com.test.DemoProject;
private int id; Auto wiring example import org.springframework.beans.factory.annotation.Autowired;
private String name; public class State {
private State s; dependency private String name;
public City() {
public String getName() { return name; }
}
public void setName(String s) { this.name = s; }
public int getID() { return id; }
public void setId(int eid) { this.id = eid; } @Override
public String getName() { return name; } public String toString() {
public void setName(String st) { this.name = st; } return "State [name=" + name + "]";
public State getS() { }
return s; public State(String name) {
} super();
public void setS(State s) { this.name = name;
this.s = s; }
} public State() {
public int getId() {
super();}
return id;
}
}
public City(State s) {
super(); package com.test.DemoProject; //main
this.s = s; import org.springframework.context.ApplicationContext;
} import
public City(int id, String name, State s) {
org.springframework.context.support.ClassPathXmlApplicationContext;
super();
this.id = id;
public class Test {
this.name = name; public static void main(String[] args) {
this.s = s; ApplicationContext context = new
} ClassPathXmlApplicationContext("/com/test/DemoProject/config1.xml");
@Override City city=context.getBean("city", City.class);
public String toString() { System.out.println(city);
return "City [id=" + id + ", name=" + name + ", s=" + s + "]"; }
} }
}
@autowired
There are three ways to apply the @Autowired annotation:
NOTE: PUT FOLLOWING LINE IN CONFIG.XML FILE
<context:annotation-config/>
1. On a field: This is the most common way to use the @Autowired annotation. Simply annotate the field with
@Autowired and Spring will inject an instance of the dependency into the field when the bean is created.

public class MyBean {


@Autowired
private MyDependency dependency;
}

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.

public class MyBean {


private MyDependency dependency;
@Autowired
public void setDependency(MyDependency dependency) {
this.dependency = dependency;
}
}

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.
Bean 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.
• Note: We can choose a custom method name instead of init() and
destroy(). Here, we will use init() method to execute all its code as the
spring container starts up and the bean is instantiated, and destroy()
method to execute all its code on closing the container.

1. Spring bean life cycle involves initialization and destruction callbacks


and Spring bean aware classes.
2. Initialization callback methods execute after dependency injection is
completed. Their purposes are to check the values that have been set in
bean properties, perform any custom initialization or provide a wrapper on
original bean etc. Once the initialization callbacks are completed, bean is
ready to be used.
3. When IoC container is about to remove bean, destruction callback
methods execute. Their purposes are to release the resources held by
bean or to perform any other finalization tasks.
4. When more than one initialization and destructions callback methods
have been implemented by bean, then those methods execute in certain
order.
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).

<bean name="address1" class="com.kiet.TEST.Address">


<property name="city" value="Ghaziabad"/>
<property name="state" value="UP"/>
</bean>

2. Annotation-based configuration:Uses annotations like @Component,


@Service, @Repository, and @Autowired for dependency injection and bean
declaration.

Add following tag to config file.


<context:annotation-config/>
<context:component-scan base-package="com.kiet.TEST"/>
3. Java-based Configuration (JavaConfig):Configuration is done using Java classes annotated
with @Configuration.Beans are defined using @Bean annotations within these configuration
classes.
@Component
public class Employee {//Employee.java
void doSomething()
{
System.out.println("employee object created");
}
}
//APP JAVA
ApplicationContext context=new AnnotationConfigApplicationContext(EmpConfig.class);
Employee emp=context.getBean("employee", Employee.class);
emp.doSomething();
@Configuration // EmpConfig.java
@ComponentScan(basePackages = "com.kiet.TESTa")
public class EmpConfig {
@Bean
public Employee getEmployee() {
return new Employee();
}
}
WebSocket API
Spring Framework provides a WebSocket API that adapts to various WebSocket
engines, including Tomcat, Jetty, GlassFish, WebLogic, and Undertow. This API allows
developers to easily implement WebSocket-based applications. The Spring Framework
also provides a number of features that make it easy to develop WebSocket-based
applications, including:
• A messaging framework that supports STOMP, a text-oriented messaging protocol
that can be used over any reliable 2-way streaming network protocol such as TCP and
WebSocket.
• A JavaScript client library that makes it easy to develop WebSocket-based web
applications.
• A number of pre-built WebSocket-based applications, such as a chat application and a
stock ticker.
SPRING BOOT
• Spring Boot is most commonly used and contains all Spring
Framework features. Nowadays Spring Boot is becoming the best
choice for Java developers to build rapid Spring applications.
When Java Developers use Spring Boot for developing
applications then they will focus on the logic instead of struggling
with the configuration setup environment of the application.
SPRING BOOT
Spring Boot is an open-source Java framework that makes it easy to create Spring-based
applications. It provides a number of features that make development faster and easier, including:
Auto-configuration:
• Spring Boot can automatically configure many of the beans that you need for your application,
based on the dependencies that you have included. This means that you don't have to spend time
writing a lot of XML configuration files.
Embedded servers:
• Spring Boot can embed a number of different web servers, such as Tomcat and Jetty. This means
that you don't have to deploy your application to a separate server.
Starter projects:
• Spring Boot provides a number of starter projects that you can use to get started quickly with
different types of applications, such as web applications, RESTful web services, and batch
applications.
Microservices:
• Spring Boot is a popular choice for developing microservices, which are small, independent
services that can be combined to create a larger application. Spring Boot makes it easy to develop
and deploy microservices, and it provides a number of features that are useful for microservices,
such as embedded servers and service discovery.
Springboot Key Features
• Built on top of Spring Framework
• Simplifies development and deployment of Spring applications
• Auto-configuration
• Starter dependencies
• Opinionated defaults
• Embedded servers (Tomcat, Jetty, etc.)
• Production-ready features (metrics, health checks, etc.)
SPRING BOOT
Benefits of Spring Boot
• Faster development time
• Reduced boilerplate code
• Integrated development environment
• Easy deployment (self-contained JARs)
• Microservices architecture support
SPRING BOOT BUILD SYSTEMS
Spring Boot supports several build systems, but it primarily
recommends two: Maven and Gradle
These build systems are recommended because they offer
excellent support for dependency management.
• Maven: Maven uses an XML file (pom.xml) for its configuration. It
provides a uniform build system and a quality project information.
Spring Boot’s spring-boot-starter-parent project can be used as a
parent project in Maven to provide sensible defaults.
• Gradle: Gradle uses Groovy-based DSL (Domain Specific
Language) for its configuration. It’s known for its performance and
flexibility.
Maven Gradle
Based On Maven is based on developing pure Java Gradle, on the other hand, is based on
language-based software developing domain-specific language projects
Configuration Maven uses an XML file for its configuration and Gradle uses a Groovy-based Domain-Specific
follows strict conventions. This makes it easy for Language (DSL) for its configuration, providing
developers to understand the layout of a project, more flexibility in the build process
but also limits customization options
Performance Maven, in terms of execution of projects, is quite Gradle is known for its performance and is
slow generally faster than Maven2. It uses
mechanisms like incrementality, build cache,
and the Gradle Daemon for work avoidance
and faster builds
Flexibility Maven provides a very rigid model that makes Gradle is highly customizable and can be
customization tedious and sometimes modified under various technologies for
impossible. diverse projects
User Maven’s longer tenure means that its support Gradle’s IDE support continues to improve
Experience through IDEs is better for many users quickly
Dependency Both Gradle and Maven offer excellent support for dependency management. However, Gradle’s
Management mechanisms for work avoidance and incrementality make it much faster than Maven
Structuring Spring Boot Code
Spring Boot does not require any specific code layout to work.
However, there are some best practices that help.
According to Spring boot documentation:
Place your main application class in a root package above other
classes. The @EnableAutoConfiguration annotation is often placed on
your main class, and it implicitly defines a base “search package” for
certain items. For example, if you are writing a JPA application, the
package of the @EnableAutoConfiguration annotated class is used to
search for @Entity items.
Using a root package also lets the @ComponentScan annotation be
used without needing to specify a basePackage attribute. You can also
use the @SpringBootApplication annotation if your main class is in the
root package.
Main class
package com.example.myapplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@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>

Method can be get, post, put, delete, options etc


GET, POST, PUT, and DELETE are HTTP methods that define how clients and servers communicate over the World
Wide Web. HTTP methods enable API clients to perform CRUD (Create, Read, Update, and Delete) actions on an
API’s resources in a standardized and predictable way. The most commonly used HTTP methods are:
GET
The GET method is used to retrieve data on a server. Clients can use the GET method to access all of the
resources of a given type, or they can use it to access a specific resource. For instance, a GET request to the
/products endpoint of an e-commerce API would return all of the products in the database, while a GET request
to the /products/123 endpoint would return the specific product with an ID of 123. GET requests typically do not
include a request body, as the client is not attempting to create or update data.
POST
The POST method is used to create new resources. For instance, if the manager of an e-commerce store wanted
to add a new product to the database, they would send a POST request to the /products endpoint. Unlike GET
requests, POST requests typically include a request body, which is where the client specifies the attributes of
the resource to be created. For example, a POST request to the /products endpoint might have a request body
that looks like this:
{
"name": "Sneakers",
"color": "blue",
"price": 59.95,
"currency": "USD"
}
PUT
The PUT method is used to replace an existing resource with an updated version. This method works by
replacing the entire resource (i.e., the specific product located at the /products/123 endpoint) with the data
that is included in the request’s body. This means that any fields or properties not included in the request body
are deleted, and any new fields or properties are added.

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.
Spring Boot Starters
Spring Boot Starters are a set of convenient dependency
descriptors that you can include in your application. They help you
get a project up and running quickly by providing a collection of
curated dependencies that are commonly used together.

Commonly Used Starters


spring-boot-starter-web
•Purpose: For building web applications using Spring MVC.
•Includes: Spring MVC, embedded Tomcat/Jetty/Undertow server, and
necessary dependencies for web development.
spring-boot-starter-data-jpa

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

Purpose: For adding security to Spring Boot applications.


Includes: Spring Security, OAuth, and other security-related dependencies.
RESTFUL WEB SERVICES
RESTful web services are a type of web service that uses the HTTP protocol to
communicate with clients. They are based on the Representational State Transfer
(REST) architectural style, which defines a set of constraints that make web services
more interoperable and scalable.
REST Controller
• A REST controller is a type of controller that is used to create RESTful web
services. REST stands for REpresentational State Transfer, and it is an architectural
style for designing web services.
• REST controllers are typically annotated with the @RestController annotation. This
annotation tells Spring that the controller is a REST controller, and it enables a
number of features that are useful for developing RESTful web services, such as
automatic serialization of responses to JSON or XML.
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
}
Request Mapping: @RestController
•Request Mapping is an annotation that is used to map @RequestMapping("/student")
public class StudentController {
web requests to specific handler classes and/or handler
StudentService studentService;
methods. public StudentController(StudentService
•The annotation is used at the class level to express studentService) {
shared mappings or at the method level to narrow down super();
to a specific endpoint mapping. this.studentService = studentService;
•The annotation has various attributes to match by URL, }
HTTP method, request parameters, headers, and media @PostMapping
types. Student addStudent(@RequestBody Student
student)
{
Request Body: return
•A request body is data sent by the client to your API. this.studentService.addStudent(student);
•It is typically used when we expect the client to send }
data in the request body when submitting a form or }
sending JSON data.
•You can use the @RequestBody annotation in Spring
Boot to bind the HTTP request body to a parameter in a
controller method.
Path Variable:
@GetMapping("/{id}")
•Path variables are used to extract values from the URI Student getStudent(@PathVariable int id)
and use them as method parameters. {
•You can use the @PathVariable annotation in Spring return this.studentService.getStudent(id);
Boot to extract values from the URI path. }
•Path variables are typically used to handle dynamic URIs
where one or more of the URI value works as a
parameter.

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 Spring "name", defaultValue = "World") String name) {
Boot to extract input data passed through an HTTP URL return String.format("Hello %s!", name);
}
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.

You might also like