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

Spring Framework Unit 5

unit 5 notes java aktu

Uploaded by

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

Spring Framework Unit 5

unit 5 notes java aktu

Uploaded by

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

Unit 5

Spring Framework
Spring is a lightweight and popular open-source Java-based framework developed by
Rod Johnson in 2003. It is used to develop enterprise-level applications.. Its core
features can be used by any Java application, but there are extensions for building
web applications on top of the Java EE (Enterprise Edition) platform. Spring is known
for its modularity, which means you can use only the parts you need without the
overhead of the entire framework.
Advantages of Spring Framework
1. Modular and Lightweight: Spring follows a modular architecture, allowing
developers to use only the components they need, making application more
lightweight and easier to maintain. This modularity also promotes better code
organization.
2. Flexible Configuration: Spring supports multiple configuration options,
including XML , java-based configuration and annotation based configuration
this flexibility allow developers to choose the most suitable code approach for
their projects.
3. Dependency Injection (DI): Spring supports Dependency Injection which
simplifies the management of component dependencies, making code more
testable and adaptable to changes.
4. Aspect oriented programming (AOP): Spring provides AOP Support allowing,
developers to separate cross-cutting concern like logging, security and
transaction from the core application logic. This improves code modularity and
maintainability.
5. Simplified Database Access: Spring JDBC and Object Relation Mapping (ORM)
support (e.g. Hibernate, JPA) simplifies database access, reduce boilerplate
code and improves data access efficiency.
6. Testing support: Spring architecture encourages writing unit tests and it
provide support for integration testing.
7. Security: Spring security provides a robust framework for implementing
authentication and authorization, making it easier to secure web application
and services.
8. Integration Capabilities: Spring provides Integration with various technologies
and framework, such as angular, react, messaging systems (JMS), web services
(SOAP and REST), and other third-party libraries and APIs.
9. Scalability: Spring applications can be designed for scalability and can easily
integrate with cloud-native technologies and microservices architecture.
10. Open Source: Spring is open-source, which means it’s free to use and can be
customized to meet specific project requirements.
Spring container
The Spring container is at the core of the Spring Framework. The container will create
the objects, wire them together, configure them, and manage their complete life
cycle from creation till destruction. It utilizes dependency injection (DI) to provide
loose coupling between objects and to promote easier testing and maintenance. The
Spring Container, also known as the Inversion of Control (IoC) container, is what
makes the Spring Framework so powerful and flexible.
The container gets its instructions on what objects to instantiate, configure, and
assemble by reading the configuration metadata provided. The configuration
metadata can be represented either by XML, Java annotations, or Java code. The
following diagram represents a high-level view of how Spring works. The Spring IoC
container makes use of Java POJO classes and configuration metadata to produce a
fully configured and executable system or application.
There are 2 types of IoC containers:
1. BeanFactory: BeanFactory holds bean definitions and instantiates them
whenever asked for by the client application
2. ApplicationContext: This the most powerful Container, compare to Bean-
factory
configurableApplicationContext: It is use in spring boot. One of the implementation
of the ApplicationContext container. This container is used for Event Handling
propose
That means if you want to use an IoC container in spring whether we need to use a
BeanFactory or ApplicationContext or configurableApplicationContext. The
BeanFactory is the most basic version of IoC containers, and the ApplicationContext
extends the features of BeanFactory.
Example:
Step 1: Create a POJO (Student.java)
package Bean;
public class Student {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void display() {
System.out.println("Name: "+name);
System.out.println("Id: "+id);
}}
Step 2: Create a Spring Configuration File (applicationContext.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean definitions here -->
<bean class="Bean.Student" id="stdId">
<property name="id" value="101"></property>
<property name="name" value="priya"></property> </bean>
<bean class="Bean.Student" id="stdId1">
<property name="id" value="102"></property>
<property name="name" value="Pinki"></property> </bean> </beans>
Step 3: Write the Main Application to Connect Everything (TestMain.java)
//spring-beans .jar
//spring-core .jar
//spring-context .jar
//commons-logging .jar
//spring-expression .jar
Download above mentioned jar file
package main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import Bean.Student;
public class TestMain {
public static void main(String[] args) {
String config_loc= "/spResources/applicationContext.xml";
ApplicationContext context = new
ClassPathXmlApplicationContext(config_loc);
Student s = (Student)context.getBean("stdId");
s.display();
Student s1 = (Student)context.getBean("stdId1");
s1.display(); }}
Output:
Name: priya
Id: 101
Name: Pinki
Id: 102
Using java Based Configuration
Step 1. create POJO class (Student.java)
Step2. create SpringConfigFile (Springconfig.java)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import Beans.Student;
@Configuration
public class SpringConfig {
@Bean("stdId1")
public Student createStudentObj(){
Student std = new Student();
std.setId(101);
std.setName("priya");
return std; }}
Step 3: Write the Main Application to Connect Everything (TestMain.java)
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.
AnnotationConfigApplicationContext;
import Beans.Student;
import Resourcess.SpringConfig;
public class TestMain {
public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext(SpringConfig.class);
Student std = (Student)context.getBean("stdId1");
std.display(); }}
Using Annotation Based Configuration
Step 1 create POJO class(Employee.java)
package Beans;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Employee {
@Value("101")
int empId;
@Value("poojaa")
String empName;
public int getEmpId() {
return empId; }
public void setEmpId(int empId) {
this.empId = empId; }
public String getEmpName() {
return empName; }
public void setEmpName(String empName) {
this.empName = empName; }
public void display() {
System.out.println("Name: "+empName);
System.out.println("Id: "+empId); }}
Step2. Create xml config file (applicationContext.xml)
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- bean definitions here -->
<context:component-scan base-package="Beans" /> </beans>
Step 3: Write the Main Application to Connect Everything (EmpMain.java)
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import Beans.Employee;
public class EmpMain {
public static void main(String[] args) {
String srcFile = "/Resourcess/applicationContext.xml";
ApplicationContext context = new
ClassPathXmlApplicationContext(srcFile);
Employee e = (Employee) context.getBean("employee");
e.display();
}}
Aspect-Oriented Programming (AOP)
Aspect-Oriented Programming (AOP) is a programming paradigm that aims to
increase modularity by allowing the separation of cross-cutting concerns. These
concerns are aspects of a program that affect other parts of the program and
often include functionalities like logging, security, and transaction management,
which cut across multiple modules of an application.
Examples of AOP Use:
Logging: Automatically logging method calls and their parameters without
modifyinSg the method's code.
Security: Implementing access control checks across various modules.
Transaction Management: Managing transactions declaratively without hard-
coding transactional code into business logic.
Key Concepts of AOP:
Aspect: An aspect is a modularization of a concern that cuts across multiple classes.
Advice: Represent an action taken by an aspect at particular join point.
Join Point: Join Point is any point in your program such as method execution,
exception handling, field access etc. Spring supports only method execution join
point.
Pointcut: It is an expression of AOP that matches join point.
//AspectJ Runtime , AspectJ Weaver Jar file Required
Example
public interface Payment {
public void makePayment(); }
public class PaymentImpl implements Payment{
public void makePayment() {
System.out.println("Amount Debited.......");
System.out.println("Amount credited......."); }}
Configuration 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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- bean definitions here -->
<aop:aspectj-autoproxy />
<context:component-scan base-package="Beans" />
<bean name="pmnt" class="main.PaymentImpl" />
<bean name="myAspect" class="main.MyPaymentAspect" />
</beans>
MyPaymentAspect.java (Class)
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class MyPaymentAspect {
@Before("execution(* main.PaymentImpl.makePayment())")
public void printBefore() {
System.out.println("Payment Started----");
}}
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.
AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestPayment {
public static void main(String[] args) {
String srcFile = "/Resourcess/applicationContext.xml";
ApplicationContext context = new
ClassPathXmlApplicationContext(srcFile);
Payment p = context.getBean("pmnt" , Payment.class);
p.makePayment(); }}
Bean Scopes
Bean scopes define the lifecycle and visibility of the beans within the container. The
scope of a bean determines how and when the bean is instantiated and how long it
lives within the application. The primary bean scopes in Spring include singleton,
prototype, request, session.
Singleton Scope: This is the default scope in Spring. A single instance of the bean is
created per Spring IoC container.
• Only one instance is shared across the application.
• The bean is instantiated during the container startup by default.
• Suitable for stateless, shared resources such as services or DAOs.
Prototype Scope: A new instance of the bean is created every time it is requested
from the Spring container.
• Multiple instances are created.
• Suitable for stateful beans or those that maintain internal state.
Eg: @Scope("prototype")
Request Scope: A new bean instance is created for each HTTP request. This scope is
only valid in the context of a web-aware Spring Application Context.
• The bean is alive during the duration of an HTTP request.
• Useful for request-scoped data in web applications.
@Scope("request")
Session Scope: A single bean instance is created for the lifecycle of an HTTP session.
This scope is valid in a web application context.
• The bean lives as long as the HTTP session.
• Suitable for storing user session data across multiple requests.
@Scope("session")
Application Scope: in the Spring Framework is a context scope that is primarily used
in web applications. It ensures that a bean is scoped to the lifecycle of the
ServletContext, which means that a single instance of the bean will be created and
shared across the entire application.
• A single instance of the bean is created for the entire web application.
• The bean is shared among all users and all HTTP requests throughout the
application's lifetime.
• The bean's lifecycle is tied to the ServletContext.
• It gets instantiated when the web application starts and is destroyed when the
web application is shut down.
@Scope("application")
WebSocket scope: WebSocket scope in Spring is a specialized scope that manages
the lifecycle of a bean to match the lifecycle of a WebSocket session. This scope is
particularly useful in applications that use WebSocket for real-time communication
between clients and servers, such as chat applications, live updates, or interactive
games.

• Single Instance per WebSocket Session: A new bean instance is created for
each WebSocket session.
• Lifecycle: The bean is created when a WebSocket session is established and
destroyed when the session ends.
• State Management: Suitable for managing state and data specific to a
particular WebSocket session.
Dependency Injection (DI)
Dependency Injection is a design pattern used to implement Inversion of Control
(IoC), allowing the creation of dependent objects outside of a class and providing
those objects to a class in various ways. It helps in creating loosely coupled code,
improving code maintainability and testability.
Types of Spring Dependency Injection:
Setter Dependency Injection (SDI): This is the simpler of the two DI methods. In this,
the DI will be injected with the help of setter and/or getter methods. Now to set the
DI as SDI in the bean, it is done through the bean-configuration file For this, the
property to be set with the SDI is declared under the <property> tag in the bean-
config file.
1. Create the Address Class
public class Address {
private String street;
private String city;
private String zipCode;
// Getters and Setters
public String getStreet() {
return street }
public void setStreet(String street) {
this.street = street; }
public String getCity() {
return city; }
public void setCity(String city) {
this.city = city; }
public String getZipCode() {
return zipCode; }
public void setZipCode(String zipCode) {
this.zipCode = zipCode; }
public String toString() {
return street + ", " + city + ", " + zipCode;
}}
2. Create the Student Class
public class Student {
private int id;
private String name;
private Address address;
// Getters and Setters
public int getId() {
return id;
public void setId(int id) {
this.id = id;}
public String getName() {
return name; }
public void setName(String name) {
this.name = name; }
public Address getAddress() {
return address; }
public void setAddress(Address address) {
this.address = address; }
public String toString() {
return "Student [id=" + id + ", name=" + name + ", address=" + address + "]";}}
3. Create the XML Configuration 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Definition for Address bean -->
<bean id="addressBean" class="com.example.Address">
<property name="street" value="123 Main St"/>
<property name="city" value="Springfield"/>
<property name="zipCode" value="12345"/>
</bean>
<!-- Definition for Student bean -->
<bean id="studentBean" class="com.example.Student">
<property name="id" value="1"/>
<property name="name" value="John Doe"/>
<property name="address" ref="addressBean"/>
</bean>
</beans>
4. Create the Main Class to Load the ApplicationContext
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) context.getBean("studentBean");
System.out.println(student);
}}
Constructor Dependency Injection involves providing the required dependencies
to a class through its constructor. When an instance of the class is created, all
dependencies are injected via the constructor. This approach ensures that the
dependencies are available immediately upon object creation, promoting
immutability.
To use Constructor Dependency Injection (DI) instead of Setter DI, you need to
modify the Student and Address classes to include constructors that take the
required dependencies as parameters. You also need to update the XML
configuration file to use the constructor-arg elements for DI.
Example:
1. Create Parameterized Constructors in both class Student and Address (above
example )
2. Update 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- Definition for Address bean -->


<bean id="addressBean" class="com.example.Address">
<constructor-arg value="123 Main St"/>
<constructor-arg value="Springfield"/>
<constructor-arg value="12345"/>
</bean>

<!-- Definition for Student bean -->


<bean id="studentBean" class="com.example.Student">
<constructor-arg value="1"/>
<constructor-arg value="John Doe"/>
<constructor-arg ref="addressBean"/>
</bean>
</beans>
3. Main Class to Load the ApplicationContext
Autowiring
Autowiring feature of spring framework enables you to inject the object dependency
implicitly. It internally uses setter or constructor injection.
Autowiring can't be used to inject primitive and string values. It works with reference
only.
It requires the less code because we don't need to write the code to inject the
dependency explicitly.
No control of programmer.
Autowiring Modes
1. No: It is the default autowiring mode. It means no autowiring bydefault.
2. byName: The byName mode injects the object dependency according to name
of the bean. In such case, property name and bean name must be same. It
internally calls setter method.
3. byType: The byType mode injects the object dependency according to type. So
property name and bean name can be different. It internally calls setter
method.
4. Constructor: The constructor mode injects the dependency by calling the
constructor of the class. It calls the constructor having large number of
parameters.
5. Autodetect: It is deprecated since Spring 3.
Autowiring using XML byName | byType | constructor
byName Example
public class B {
B(){ System.out.println("b is created"); }
void print(){System.out.println("hello b");} }
public class A {
B b;
A(){ System.out.println("a is created"); }
public B getB() { return b; }
public void setB(B b) { this.b = b; }
void print(){ System.out.println("hello a"); }
void display(){ print(); b.print(); } }
applicationContext.XML
<?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="b" class=" packagNAMEe.B "></bean>
<bean id="a" class="packagNAMEe.A " autowire="byName"></bean> </beans>
Main class
public class Test {
public static void main(String[] args) {
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
A a=context.getBean("a",A.class);
a.display(); } }
byType Example
<bean id="b" class=" packagNAMEe.B "></bean>
<bean id="a" class="packagNAMEe.A " autowire="byType"></bean> </beans>
Constructor autowiring mode
<bean id="b" class=" packagNAMEe.A "></bean>
<bean id="a" class=" packagNAMEe.A " autowire="constructor" ></bean>
@Autowired annotation
The @Autowired annotation in Spring Framework is used for automatic dependency
injection. This means Spring will automatically inject the appropriate beans (objects)
into the fields, constructors, or setter methods annotated with @Autowired,
eliminating the need for explicit bean wiring in the XML configuration file or Java-
based configuration class.
Field Injection
public class MyService
@Autowired
private MyRepository myRepository;
// other method }
Constructor Injection
public class MyService {
private final MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
} // other methods }
Setter Injection
public class MyService {
private MyRepository myRepository;
@Autowired
public void setMyRepository(MyRepository myRepository) {
this.myRepository = myRepository; } // other methods }
How Autowiring Works
By Type: Spring looks for a bean with a type matching the field or parameter.
By Name: If there are multiple candidates, Spring uses the name of the field or
parameter to resolve the conflict.
Qualifier: When there are multiple beans of the same type and the name doesn’t help,
you can use @Qualifier to specify which bean to inject.
public class MyService {
@Autowired
@Qualifier("specificRepository")
private MyRepository myRepository; // other methods }
Lifecycle of a Bean in Spring
The lifecycle of a bean in the Spring Framework refers to the series of steps and
methods that a bean goes through from its instantiation to its eventual destruction.
The lifecycle of a bean is managed by the Spring container which is responsible for
creating, configuring, and destroying beans according to the defined bean scope
(singleton, prototype, etc.)
Spring framework provides the following ways for controlling the lifecycle events of a
bean. These are broadly categorized into three categories:
Interface-based Lifecycle can be achieved by implementing InitializingBean and
DisposableBean interfaces.
InitializingBean: Defines initialization logic in the afterPropertiesSet() method,
executed after the bean's properties are set.
DisposableBean: Defines cleanup logic in the destroy() method, executed before the
bean is destroyed.
Example:
1. Create classs
public class MyBean implements InitializingBean , DisposableBean{
String name;
//setter getter
public void afterPropertiesSet() { // Custom initialization logic }
public void destroy() { // Custom destruction logic }
}
2. Create the XML Configuration File
3. Create the Main Class to Load the ApplicationContext
Method-based Lifecycle is achieved by adding custom init() and destroy() methods in
the bean class and declaring them in the bean configuration file.
Example:
1. Create class
package Beans;
public class Student {
private int id;
private String name;
//setter getter
public void display() {
System.out.println("Name: "+name);
System.out.println("Id: "+id); }
public void initt() {
System.out.println("initialization"); }
public void destroyy() {
System.out.println("destroy"); } }
2. update the XML Configuration File
<bean class="Beans.Student" id="stdId11" init-method="initt" destroy-
method="destroyy">
<property name="id" value="102"></property>
<property name="name" value="Pinki"></property> </bean>
3. Create the Main Class to Load the ApplicationContext
AbstractApplicationContext context = new
ClassPathXmlApplicationContext("/Resourcess/applicationContext.xml");
Student std = (Student)context.getBean("stdId11");
std.display();
context.registerShutdownHook();
Annotation-based Lifecycle is achieved by adding @PostConstruct and @PreDestroy
annotated methods in the bean class.
From Spring 2.5 onwards, we can use the @PostConstruct and @PreDestroy
annotations for specifying the bean life cycle methods.
@PostConstruct annotated method will be invoked after the bean has been
constructed using the default constructor and just before its instance is returned to
the requesting object.
@PreDestroy annotated method is invoked just before the bean is about to be
destroyed inside the bean container.
This annotation is part of Common Annotations API and it’s part of JDK module
javax.annotation-api. So if you are using this annotation in Java 9 or above, you will
have to explicitly add this jar to your project. If you are using maven, then below
dependency should be added to it.
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
If you are on Java 8 or lower version, then you won’t have to add above dependency
public class MyBean {
@PostConstruct
public void init() { System.out.println("Verifying Resources"); }
@PreDestroy
public void shutdown() { System.out.println("Shutdown All Resources"); }}
Annotations
annotations are a powerful and concise way to configure your application. They
provide metadata about the code, which can be used by the framework to perform
certain operations or behaviors.
Core Spring Framework Annotations
@Required: It applies to the bean setter method. It indicates that the annotated
bean must be populated at configuration time with the required property, else it
throws an exception BeanInitilizationException.
@Autowired: Spring provides annotation-based auto-wiring by providing
@Autowired annotation. It is used to autowire spring bean on setter methods,
instance variable, and constructor. When we use @Autowired annotation, the spring
container auto-wires the bean by matching data-type.
@Configuration: It is a class-level annotation. The class annotated with
@Configuration used by Spring Containers as a source of bean definitions.
@ComponentScan: It is used when we want to scan a package for beans. It is used
with the annotation @Configuration. We can also specify the base packages to scan
for Spring Components.
@Bean: It is a method-level annotation. It is an alternative of XML <bean> tag. It tells
the method to produce a bean to be managed by Spring Container.
Spring Framework Stereotype Annotations
@Component: It is a class-level annotation. It is used to mark a Java class as a bean.
A Java class annotated with @Component is found during the classpath. The Spring
Framework pick it up and configure it in the application context as a Spring Bean.
@Controller: The @Controller is a class-level annotation. It is a specialization of
@Component. It marks a class as a web request handler. It is often used to serve web
pages. By default, it returns a string that indicates which route to redirect. It is mostly
used with @RequestMapping annotation.
@Service: It is also used at class level. It tells the Spring that class contains the
business logic.
@Repository: It is a class-level annotation. The repository is a DAOs (Data Access
Object) that access the database directly. The repository does all the operations
related to the database.
Spring Boot Annotations
@EnableAutoConfiguration: It auto-configures the bean that is present in the
classpath and configures it to run the methods. The use of this annotation is reduced
in Spring Boot 1.2.0 release because developers provided an alternative of the
annotation, i.e. @SpringBootApplication.
@SpringBootApplication: It is a combination of three annotations
@EnableAutoConfiguration, @ComponentScan, and @Configuration.
@RequestMapping is a central part of Spring's web application framework. It is used
to map web requests to specific handler functions in controllers. This annotation can
be applied at both the class and method level in a Spring controller.
1. Class-Level @RequestMapping: When @RequestMapping is applied at the class
level, it defines a common path for all handler methods in that controller.
2. Method-Level @RequestMapping: When @RequestMapping is applied at the
method level, it defines the specific paths and HTTP methods for the handler
methods.
@RequestMapping can specify the HTTP method, there are more specific
annotations for common HTTP methods that make the code more readable

• @GetMapping: It maps the HTTP GET requests on the specific handler


method. It is used to create a web service endpoint that fetches It is used
instead of using: @RequestMapping(method = RequestMethod.GET)
• @PostMapping: It maps the HTTP POST requests on the specific handler
method. It is used to create a web service endpoint that creates It is used
instead of using: @RequestMapping(method = RequestMethod.POST)
• @PutMapping: It maps the HTTP PUT requests on the specific handler
method. It is used to create a web service endpoint that creates or updates It
is used instead of using: @RequestMapping(method = RequestMethod.PUT)
• @DeleteMapping: It maps the HTTP DELETE requests on the specific handler
method. It is used to create a web service endpoint that deletes a resource. It
is used instead of using: @RequestMapping(method =
RequestMethod.DELETE)
• @PatchMapping: It maps the HTTP PATCH requests on the specific handler
method.PATCH method is typically used for partial updates to a resource. It is
used instead of using @RequestMapping(method = RequestMethod.PATCH)
@RequestBody: It is used to bind HTTP request with an object in a method
parameter. Internally it uses HTTP MessageConverters to convert the body of the
request. When we annotate a method parameter with @RequestBody, the Spring
framework binds the incoming HTTP request body to that parameter.
@ResponseBody: It binds the method return value to the response body. It tells the
Spring Boot Framework to serialize a return an object into JSON and XML format.
@PathVariable: It is used to extract the values from the URI. It is most suitable for
the RESTful web service, where the URL contains a path variable. We can define
multiple @PathVariable in a method.
@RequestParam: It is used to extract the query parameters form the URL. It is also
known as a query parameter. It is most suitable for web applications. It can specify
default values if the query parameter is not present in the URL.
@RequestHeader: It is used to get the details about the HTTP request headers. We
use this annotation as a method parameter. The optional elements of the annotation
are name, required, value, defaultValue. For each detail in the header, we should
specify separate annotations. We can use it multiple time in a method
@RestController: It can be considered as a combination of @Controller and
@ResponseBody annotations. The @RestController annotation is itself annotated
with the @ResponseBody annotation. It eliminates the need for annotating each
method with @ResponseBody.
@RequestAttribute: It binds a method parameter to request attribute. It provides
convenient access to the request attributes from a controller method. With the help
of @RequestAttribute annotation, we can access objects that are populated on the
server-side.
Spring Boot Runners
Spring Boot runners are special beans that are executed when the Spring application
context is fully initialized. There are two main types of runners in Spring Boot:
1. CommandLineRunner: This is a functional interface with a single method
run(String... args). It is used to execute code after the Spring Boot application
has started. To use it, you need to implement this interface and override the
run method.
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Application started with ApplicationRunner");
}}
2. ApplicationRunner: Similar to CommandLineRunner, but it provides more
options for parsing the command-line arguments. The run method in
ApplicationRunner receives an ApplicationArguments object.
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Application started with ApplicationRunner");
}}
Logger in Spring Boot
Logging in Spring Boot is typically done using the SLF4J (Simple Logging Facade
for Java) API along with a logging backend like Logback, Log4j2, or Java Util
Logging. Spring Boot provides built-in support for logging, and you can use the
Logger interface to log messages at different levels (INFO, DEBUG, ERROR,
etc.).
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(MyClass.class);
public void myMethod() {
logger.info("This is an info message");
logger.debug("This is a debug message");
logger.error("This is an error message");
}
# application.properties (Configure this in application.properties file)
logging.level.org.springframework=INFO
logging.level.com.example=DEBUG
logging.file.name=logs/myapp.log

Spring Boot Architecture


Spring Boot is a module of the Spring Framework. It is used to create stand-alone,
production-grade Spring Based Applications with minimum efforts. It is developed on
top of the core Spring Framework. Spring Boot follows a layered architecture in which
each layer communicates with the layer directly below or above (hierarchical
structure) it.
Presentation Layer: The presentation layer handles the HTTP requests, translates the
JSON parameter to object, and authenticates the request and transfer it to the
business layer. In short, it consists of views i.e., frontend part.
Business Layer: The business layer handles all the business logic. It consists of service
classes and uses services provided by data access layers. It also performs
authorization and validation.
Database Layer: In the database layer, CRUD (create, retrieve, update, delete)
operations are performed.

Request comes from client to controller.


Controller forwards request to service class.
Service class performs appropriate operations with data, and if there are any
database operations required, then service layer calls respective DAO class methods.
DAO class makes use of DTO object, to store data while performing database
operations.
DTO and Model are mapped with each other with the help of ModelMapper in
service class.
DTO object is returned back to controller by service class.
Controller returns DTO object to the client as a response.
1. Project Setup
• Create project boilerplate and add dependencies from spring initializr
• Select Maven project and Java language
• Give a name to your project
• Add dependencies for SpringWeb, MySql Driver and Spring Data JPA
• Click on Generate.
• The project zip file will get downloaded, now unzip your folder.
2. Create the PostgreSQL database
3. Configuring the database into your project
server.port=1030
spring.datasource.url=jdbc:postgresql://localhost:5432/DB
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialec
t
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
4. Create the Entity
import org.springframework.stereotype.Component;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Component
@Entity
@Table
public class Employee{
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private int id;
private String name;
//setter getter
// to String}
5. Create the Repository
import com.example.demo.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee,
Integer> {
}
6. Create the Service

import com.example.demo.entity.Employee;
import com.example.demo.exception.ResourceNotFoundException;
import com.example.demo.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;

public List<Employee> getAllEmployees() {


return employeeRepository.findAll();
}

public Employee getEmployeeById(int id) {


return employeeRepository.findById(id);
}

public Employee saveEmployee(Employee employee) {


return employeeRepository.save(employee); }
public void deleteEmployee(int id) {
employeeRepository.deleteById(id); }}
7. Create the Controller
import com.example.demo.entity.Employee;
import com.example.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
@GetMapping("/{id}")
public Employee getEmployeeById(@PathVariable int id) {
Employee employee = employeeService.getEmployeeById(id);
return employee;
}
@PostMapping
public Employee createEmployee(@RequestBody Employee employee) {
return employeeService.saveEmployee(employee);
}

@PutMapping("/{id}")
public Employee updateEmployee(@PathVariable int id, @RequestBody
Employee employeeDetails) {
Employee employee = employeeService.getEmployeeById(id);
employee.setName(employeeDetails.getName());

Employee updatedEmployee = employeeService.saveEmployee(employee);


return updatedEmployee;
}
@DeleteMapping("/{id}")
public void deleteEmployee(@PathVariable int id) {
employeeService.deleteEmployee(id);
}}
8. Run Your Application

Java Stream API


The Stream API in Java, introduced in Java 8, provides a powerful way to process
sequences of elements. It allows for functional-style operations on collections of
objects, making it easier to write concise and readable code for tasks like filtering,
mapping, and reducing data.
A sequence of elements supporting sequential and parallel aggregate operations.
Does not store data; instead, it operates on a data source such as collections, arrays,
or I/O channels.
Can be created from a collection using the stream().
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List<String> list = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");
// Using Stream API to filter and transform the list
List<String> result = list.stream()
.filter(s -> s.length() > 5)
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
// Output: [BANANA, CHERRY, ELDERBERRY]
System.out.println(result); }}
In this example, the stream() method creates a stream from the list, filter() selects
elements with more than 5 characters, map() transforms them to uppercase, sorted()
sorts them, and collect() gathers the result into a new list.
Type Annotations in Java
Type annotations in Java, introduced in Java 8, provide a way to annotate types in
various contexts. They enhance the capability of annotations to include places where
types are used, enabling better code analysis, error detection, and documentation.
Type annotations are annotations that can be applied to any use of a type.
They can be used in declarations, generic types, casts, implements clauses, throws
clauses, and more.
public class TypeAnnotationExample {
// Type annotation in variable declaration
private List<@NonNull String> list;
// Type annotation in method parameter
public void setList(List<@NonNull String> list) {
this.list = list; }
// Type annotation in constructor
public TypeAnnotationExample(List<@NonNull String> list) {
this.list = list;}
// Type annotation in method return type
public @NonNull String getFirstElement() {
return list.get(0); }}

You might also like