0% found this document useful (0 votes)
2 views22 pages

Understanding Spring Framework in Java

notes of java spring

Uploaded by

Deepak Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

Understanding Spring Framework in Java

notes of java spring

Uploaded by

Deepak Singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

OOPs with Java

Unit-V(Spring Framework)

Introduction:-Prior to the advent of Enterprise Java Beans (EJB), Java developers needed to
use JavaBeans to create Web applications. Although JavaBeans helped in the development of user
interface (UI) components, they were not able to provide services, such as transaction management
and security, which were required for developing robust and secure enterprise applications. The
advent of EJB was seen as a solution to this problem EJB extends the Java components, such as Web
and enterprise components, and provides services that help in enterprise application development.
However, developing an enterprise application with EJB was not easy, as the developer needed to
perform various tasks, such as creating Home and Remote interfaces and implementing lifecycle
callback methods which lead to the complexity of providing code for EJBs Due to this complication,
developers started looking for an easier way to develop enterprise applications.
The Spring framework(which is commonly known as Spring) has emerged as a solution to all these
complications This framework uses various new techniques such as Aspect-Oriented Programming
(AOP), Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications,
thereby removing the complexities involved while developing enterprise applications using EJB, Spring
is an open source lightweight framework that allows Java EE 7 developers to build simple, reliable,
and scalable enterprise applications. This framework mainly focuses on providing various ways to help
you manage your business objects. It made the development of Web applications much easier as
compared to classic Java frameworks and Application Programming Interfaces (APIs), such as Java
database connectivity(JDBC), JavaServer Pages(JSP), and Java Servlet.

Evolution of Spring Framework


The framework was first released under the Apache 2.0 license in June 2003. After that there has been
a significant major revision, such as Spring 2.0 provided XML namespaces and AspectJ support, Spring
2.5 provide annotation-driven configuration, Spring 3.0 provided a Java-based @Configuration model.
The latest release of the spring framework is 4.0. it is released with the support for Java 8 and Java EE
7 technologies. Though you can still use Spring with an older version of java, the minimum
requirement is restricted to Java SE 6. Spring 4.0 also supports Java EE 7 technologies, such as java
message service (JMS) 2.0, java persistence API (JPA) 2.1, Bean validation 1.1, servlet 3.1, and JCache.

Spring Framework Architecture

The Spring framework consists of seven modules which are shown in the above Figure. These modules
are Spring Core, Spring AOP, Spring Web MVC, Spring DAO, Spring ORM, Spring context, and Spring
Web flow. These modules provide different platforms to develop different enterprise applications; for
example, you can use Spring Web MVC module for developing MVC-based applications.

Spring : Fundamental Concepts


Spring is a widely used open-source framework for building Java-based enterprise applications.
Key Terms and concepts related to spring:
Dependency Injection (DI): Dependency Injection is a design pattern used to remove hard-coded
dependencies between classes by externalizing the creation and management of objects
(dependencies).
 Instead of an object creating its dependencies itself, it relies on an external entity (container) to
provide the required dependencies.
 This promotes loose coupling and improves the flexibility and testability of the code.
Inversion of Control (IoC): Inversion of Control is a principle closely related to Dependency
Injection. It refers to the reversal of the flow of control in a program. In traditional programming, a
class directly controls the creation and management of its dependencies.
 In IoC, the control is shifted to an external entity (the IoC container, in this case, Spring) that
manages the creation and injection of dependencies. The IoC container creates and wires the
objects together, allowing objects to focus on their main responsibilities.
Spring Bean: In Spring, a bean is an object that is managed by the Spring IoC container.
 Beans are Java objects that are instantiated, assembled, and managed by the Spring framework.
 They represent the basic building blocks of a Spring application. Beans can be defined using XML
configuration or annotated with Spring annotations.
Spring Container: The Spring Container, also known as the IoC container, is responsible for
managing the Spring beans and the dependencies between them.
 It is the core of the Spring framework. The container reads the bean definitions (from XML files or
annotations), creates bean instances, and manages their lifecycle.
 There are two main types of Spring containers: BeanFactory and ApplicationContext.
 ApplicationContext is a more feature-rich container that includes all the functionality of
BeanFactory along with additional enterprise-level features.
Spring Configuration: Spring configuration defines how beans are created, wired, and managed.
 Configuration can be done using XML-based configuration or Java-based configuration (using
annotations or Java config classes).
Spring annotations are like special keywords that you can use in your Java code to tell the Spring
framework how to do certain things automatically. They make it easier to work with Spring and save
you from writing a lot of repetitive code.
Why use Spring?
 Simplifies Development: Spring provides a comprehensive and consistent framework that
simplifies the development of Java applications.
 Inversion of Control (IoC) and Dependency Injection (DI): Promotes loose coupling and
makes applications easier to maintain and test.
 Comprehensive Ecosystem: Offers a wide range of modules and extensions (e.g., Spring Boot,
Spring Data, Spring Security) for various application needs.
 Integration Friendly: Seamlessly integrates with other technologies and frameworks, making it
easy to leverage existing tools and libraries.
Understanding Differences in key concepts
Annotations vs XML
Annotations and XML are two different approaches used in the Spring framework for configuring and
customizing applications. Both serve the purpose of defining the behavior and dependencies of Spring
components, but they have some key differences :
Annotations:
1. Readability and Ease of Use: They are embedded directly in the Java code alongside classes,
methods, or fields. Annotations are typically more concise and easier to read since they are
integrated directly into the Java code. This makes the code more self-explanatory and reduces the
need for separate configuration files.
2. Limited Flexibility: While annotations are powerful and flexible in many cases, there are
scenarios where the complexity of configurations may require additional XML configuration or are
simply not achievable with annotations alone.
XML:
XML (Extensible Markup Language) is a separate markup language that uses tags to define
configuration elements. Spring configuration in XML is typically done in separate XML files, often
named [Link].

1. Explicit Configuration: XML configuration provides explicit and detailed control over the
configuration of Spring components. Developers can specify beans, dependencies, and other
settings in a structured and well-defined format.
2. Flexibility: XML allows for more complex and dynamic configurations since it is not tied to the Java
language. XML configuration can be externalized from the code, which is useful in scenarios where
configurations need to be modified without touching the application’s source code.
Which One to Use?
In modern Spring applications, annotations are often favored due to their simplicity, readability, and
compile-time checking. They promote a more “code-centric” approach to configuration, making it
easier to manage and understand.
However, XML configuration can still be useful, especially in cases where complex or dynamic
configurations are required, or when externalizing configurations is a priority.

Bean vs IOC Container


Bean:
 It is a Java object that is created based on a configuration and can be accessed and used
throughout the application.
 Beans are the building blocks of a Spring application, representing various components such as
services, data sources, controllers, and more. Each bean is uniquely identified within the IoC
container by its name or ID.
 Beans can be defined using XML-based configuration files or through annotations in Java-based
configuration classes. The configuration specifies how to create the bean, its dependencies, and
other properties.
IoC Container (Inversion of Control Container):
 The IoC Container is the core of the Spring framework responsible for managing the lifecycle of
beans and handling their dependencies. It implements the principle of Inversion of Control (IoC),
where the control of creating and managing objects is shifted from the application code to the
container.
 Instead of objects creating and managing their own dependencies, the IoC container takes charge
of creating, assembling, and injecting the required dependencies into the beans.
 The IoC container allows developers to define beans, their relationships, and configurations in a
declarative manner, either through XML files or using annotations and Java-based configurations.

Bean Scopes
When you create a bean definition, you create a recipe for creating actual instances of the class defined by that
bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you
can create many object instances from a single recipe.
You can control not only the various dependencies and configuration values that are to be plugged into an object
that is created from a particular bean definition but also control the scope of the objects created from a particular
bean definition. This approach is powerful and flexible, because you can choose the scope of the objects you create
through configuration instead of having to bake in the scope of an object at the Java class level. Beans can be
defined to be deployed in one of a number of scopes. The Spring Framework supports six scopes, four of which are
available only if you use a web-aware ApplicationContext. You can also create a custom scope.
The following table describes the supported scopes:
Scope Description

singleton (Default) Scopes a single bean definition to a single object instance for each Spring IoC
Scope Description

container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP
request has its own instance of a bean created off the back of a single bean definition. Only
valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the
context of a web-aware Spring ApplicationContext.
applicatio Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in
n the context of a web-aware Spring ApplicationContext.
websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context
of a web-aware Spring ApplicationContext.
A thread scope is available but is not registered by default. For more information, see the documentation
for SimpleThreadScope. For instructions on how to register this or any other custom scope, see Using a Custom
Scope.

The Singleton Scope


Only one shared instance of a singleton bean is managed, and all requests for beans with an ID or IDs that match
that bean definition result in that one specific bean instance being returned by the Spring container.
To put it another way, when you define a bean definition and it is scoped as a singleton, the Spring IoC container
creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache
of such singleton beans, and all subsequent requests and references for that named bean return the cached object.
The following image shows how the singleton scope works:

Spring’s concept of a singleton bean differs from the singleton pattern as defined in the Gang of Four (GoF) patterns
book. The GoF singleton hard-codes the scope of an object such that one and only one instance of a particular class
is created per ClassLoader. The scope of the Spring singleton is best described as being per-container and per-
bean. This means that, if you define one bean for a particular class in a single Spring container, the Spring
container creates one and only one instance of the class defined by that bean definition. The singleton scope is the
default scope in Spring. To define a bean as a singleton in XML, you can define a bean as shown in the following
example:
<bean id="accountService" class="[Link]"/>

<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="[Link]"
scope="singleton"/>
Copied!
The Prototype Scope
The non-singleton prototype scope of bean deployment results in the creation of a new bean instance every time a
request for that specific bean is made. That is, the bean is injected into another bean or you request it through
a getBean() method call on the container. As a rule, you should use the prototype scope for all stateful beans and
the singleton scope for stateless beans.
The following diagram illustrates the Spring prototype scope:

(A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any
conversational state. It was easier for us to reuse the core of the singleton diagram.)
The following example defines a bean as a prototype in XML:
<bean id="accountService" class="[Link]"
scope="prototype"/>
Copied!
In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean. The container
instantiates, configures, and otherwise assembles a prototype object and hands it to the client, with no further
record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects
regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client
code must clean up prototype-scoped objects and release expensive resources that the prototype beans hold. To
get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-
processor which holds a reference to beans that need to be cleaned up.
In some respects, the Spring container’s role in regard to a prototype-scoped bean is a replacement for the
Java new operator. All lifecycle management past that point must be handled by the client. (For details on the
lifecycle of a bean in the Spring container, see Lifecycle Callbacks.)

Singleton Beans with Prototype-bean Dependencies


When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies are
resolved at instantiation time. Thus, if you dependency-inject a prototype-scoped bean into a singleton-scoped
bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype
instance is the sole instance that is ever supplied to the singleton-scoped bean.
However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean
repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean, because
that injection occurs only once, when the Spring container instantiates the singleton bean and resolves and injects
its dependencies. If you need a new instance of a prototype bean at runtime more than once, see Method Injection.

Request, Session, Application, and WebSocket Scopes


The request, session, application, and websocket scopes are available only if you use a web-aware
Spring ApplicationContext implementation (such as XmlWebApplicationContext). If you use these scopes with regular
Spring IoC containers, such as the ClassPathXmlApplicationContext, an IllegalStateException that complains about an
unknown bean scope is thrown.

Initial Web Configuration


To support the scoping of beans at the request, session, application, and websocket levels (web-scoped beans), some
minor initial configuration is required before you define your beans. (This initial setup is not required for the
standard scopes: singleton and prototype.)
How you accomplish this initial setup depends on your particular Servlet environment.
If you access scoped beans within Spring Web MVC, in effect, within a request that is processed by the
Spring DispatcherServlet, no special setup is necessary. DispatcherServlet already exposes all relevant state.
If you use a Servlet web container, with requests processed outside of Spring’s DispatcherServlet (for example, when
using JSF), you need to register
the [Link] ServletRequestListener. This can be done
programmatically by using the WebApplicationInitializer interface. Alternatively, add the following declaration to your
web application’s [Link] file:
<web-app>
...
<listener>
<listener-class>

[Link]
</listener-class>
</listener>
...
</web-app>
Copied!
Alternatively, if there are issues with your listener setup, consider using Spring’s RequestContextFilter. The filter
mapping depends on the surrounding web application configuration, so you have to change it as appropriate. The
following listing shows the filter part of a web application:
<web-app>
...
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>[Link]</filter-
class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
Copied!
DispatcherServlet, RequestContextListener, and RequestContextFilter all do exactly the same thing, namely bind the
HTTP request object to the Thread that is servicing that request. This makes beans that are request- and session-
scoped available further down the call chain.

Request scope
Consider the following XML configuration for a bean definition:
<bean id="loginAction" class="[Link]" scope="request"/>
Copied!
The Spring container creates a new instance of the LoginAction bean by using the loginAction bean definition for
each and every HTTP request. That is, the loginAction bean is scoped at the HTTP request level. You can change the
internal state of the instance that is created as much as you want, because other instances created from the
same loginAction bean definition do not see these changes in state. They are particular to an individual request.
When the request completes processing, the bean that is scoped to the request is discarded.
When using annotation-driven components or Java configuration, the @RequestScope annotation can be used to
assign a component to the request scope. The following example shows how to do so:

@RequestScope
@Component
public class LoginAction {
// ...
}
Copied!

Session Scope
Consider the following XML configuration for a bean definition:
<bean id="userPreferences" class="[Link]" scope="session"/>
Copied!
The Spring container creates a new instance of the UserPreferences bean by using the userPreferences bean
definition for the lifetime of a single HTTP Session. In other words, the userPreferences bean is effectively scoped at
the HTTP Session level. As with request-scoped beans, you can change the internal state of the instance that is
created as much as you want, knowing that other HTTP Session instances that are also using instances created from
the same userPreferences bean definition do not see these changes in state, because they are particular to an
individual HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped to that particular
HTTP Session is also discarded.
When using annotation-driven components or Java configuration, you can use the @SessionScope annotation to
assign a component to the session scope.
@SessionScope
@Component
public class UserPreferences {
// ...
}
Copied!

Application Scope
Consider the following XML configuration for a bean definition:
<bean id="appPreferences" class="[Link]" scope="application"/>
Copied!
The Spring container creates a new instance of the AppPreferences bean by using the appPreferences bean definition
once for the entire web application. That is, the appPreferences bean is scoped at the ServletContext level and stored
as a regular ServletContext attribute. This is somewhat similar to a Spring singleton bean but differs in two
important ways: It is a singleton per ServletContext, not per Spring ApplicationContext (for which there may be
several in any given web application), and it is actually exposed and therefore visible as a ServletContext attribute.
When using annotation-driven components or Java configuration, you can use the @ApplicationScope annotation to
assign a component to the application scope. The following example shows how to do so:
@ApplicationScope
@Component
public class AppPreferences {
// ...
}
Copied!

WebSocket Scope
Each WebSocket session has a map of attributes. The map is attached as a header to inbound client messages and
may be accessed from a controller method, as the following example shows:
@Controller
public class MyController {

@MessageMapping("/action")
public void handle(SimpMessageHeaderAccessor headerAccessor) {
Map<String, Object> attrs = [Link]();
// ...
}
}
Copied!
You can declare a Spring-managed bean in the websocket scope. You can inject WebSocket-scoped beans into
controllers and any channel interceptors registered on the clientInboundChannel. Those are typically singletons and
live longer than any individual WebSocket session. Therefore, you need to use a scope proxy mode for WebSocket-
scoped beans, as the following example shows:
@Component
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyBean {

@PostConstruct
public void init() {
// Invoked after dependencies injected
}

// ...

@PreDestroy
public void destroy() {
// Invoked when the WebSocket session ends
}
}

@Controller
public class MyController {

private final MyBean myBean;


@Autowired
public MyController(MyBean myBean) {
[Link] = myBean;
}

@MessageMapping("/action")
public void handle() {
// [Link] from the current WebSocket session
}
}
Copied!
As with any custom scope, Spring initializes a new MyBean instance the first time it is accessed from the controller
and stores the instance in the WebSocket session attributes. The same instance is subsequently returned until the
session ends. WebSocket-scoped beans have all Spring lifecycle methods invoked, as shown in the preceding
examples.

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

This mode tells the framework that autowiring is not


No supposed to be done. It is the 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.

It injects the required dependencies by invoking the


Constructor
constructor.

The autodetect mode uses two other modes for


Autodetect
autowiring – constructor and byType.

1. No
This mode tells the framework that autowiring is not supposed to be done. It is the default mode used by Spring.
<bean id="state" class="[Link]">
<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]"></bean>
2. byName
It uses the name of the bean for injecting dependencies. However, it requires that the name of the property and bean must
be the same. It invokes the setter method internally for autowiring.
<bean id="state" class="[Link]">
<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" 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="[Link]">
<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" 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="[Link]">
<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" 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="[Link]">
<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" autowire="autodetect"></bean>

Spring Framework Annotations


Spring framework is one of the most popular Java EE frameworks. It is an open-source lightweight framework
that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This
framework mainly focuses on providing various ways to help you manage your business objects. Now talking
about Spring Annotation, Spring Annotations are a form of metadata that provides data about a program.
Annotations are used to provide supplemental information about a program. It does not have a direct effect
on the operation of the code they annotate. It does not change the action of the compiled program. So in this
article, we are going to discuss what are the main types of annotation that are available in the spring
framework with some examples.

Types of Spring Framework Annotations

Basically, there are 6 types of annotation available in the whole spring framework.
1. Spring Core Annotations
2. Spring Web Annotations
3. Spring Boot Annotations
4. Spring Scheduling Annotations
5. Spring Data Annotations
6. Spring Bean Annotations
Type 1: Spring Core Annotations
Spring annotations present in
the [Link] and [Link]
packages are commonly known as Spring Core annotations. We can divide them into two categories:
 DI-Related Annotations
o @Autowired
o @Qualifier
o @Primary
o @Bean
o @Lazy
o @Required
o @Value
o @Scope
o @Lookup, etc.
 Context Configuration Annotations
o @Profile
o @Import
o @ImportResource
o @PropertySource, etc.
A DI (Dependency Injection) Related Annotations

Type 2: Spring Web Annotations


Spring annotations present in the [Link] packages are commonly known as Spring
Web annotations. Some of the annotations that are available in this category are:
o @RequestMapping
o @RequestBody
o @PathVariable
o @RequestParam
o Response Handling Annotations
o @ResponseBody
o @ExceptionHandler
o @ResponseStatus
o @Controller
o @RestController
o @ModelAttribute
o @CrossOrigin

Type 3: Spring Boot Annotations


Spring annotations present in
the [Link] and [Link] packages are
commonly known as Spring Boot annotations. Some of the annotations that are available in this category are:
 @SpringBootApplication
 @EnableAutoConfiguration
 Auto-Configuration Conditions
o @ConditionalOnClass, and @ConditionalOnMissingClass
o @ConditionalOnBean, and @ConditionalOnMissingBean
o @ConditionalOnProperty
o @ConditionalOnResource
o @ConditionalOnWebApplication and @ConditionalOnNotWebApplication
o @ConditionalExpression
o @Conditional

Type 4: Spring Scheduling Annotations


Spring annotations present in the [Link] packages are commonly known as
Spring Scheduling annotations. Some of the annotations that are available in this category are:
o @EnableAsync
o @EnableScheduling
o @Async
o @Scheduled
o @Schedules
Type 5: Spring Data Annotations
Spring Data provides an abstraction over data storage technologies. Hence the business logic code can be much more
independent of the underlying persistence implementation. Some of the annotations that are available in this category are:
 Common Spring Data Annotations
o @Transactional
o @NoRepositoryBean
o @Param
o @Id
o @Transient
o @CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate
 Spring Data JPA Annotations
o @Query
o @Procedure
o @Lock
o @Modifying
o @EnableJpaRepositories
 Spring Data Mongo Annotations
o @Document
o @Field
o @Query
o @EnableMongoRepositories
Type 6: Spring Bean Annotations
There’re several ways to configure beans in a Spring container. You can declare them using XML configuration or you can
declare beans using the @Bean annotation in a configuration class or you can mark the class with one of the annotations
from the [Link] package and leave the rest to component scanning. Some of the annotations
that are available in this category are:
 @ComponentScan
 @Configuration
 Stereotype Annotations
o @Component
o @Service
o @Repository
o @Controller
Life Cycle Call backs:- Bean lifecycle simply means you want to execute callbacks before the spring
bean is available to use and similarly execute callbacks before the bean is destroyed.

There are several ways to configure the Spring bean lifecycle callbacks as listed below.

1. The JSR-250 specification using @PostConstruct and @PreDestroy annotations. This is the recommended way.
2. Using the lifecycle callbacks in <bean/> or @bean declarations.
3. Using the default initialization and destroy methods.
4. Startup and Shutdown callbacks from the Lifecycle interface.

Spring Bean creation and destruction phases


Before exploring the ways to invoke lifecycle callbacks, it is important to understand the different phases a Spring Bean goes
through before it is ready to use and before it is destroyed.

The below diagram shows the different stages spring bean goes through before it is ready to use. If you carefully observe the
diagram below, the last 3 phases are mentioned in the above discussion about several ways to specify bean lifecycle callbacks.

Spring Bean Creation Phases

Initialization callbacks
The [Link] interface specifies a single method −
void afterPropertiesSet() throws Exception;
Thus, you can simply implement the above interface and initialization work can be done inside afterPropertiesSet() method
as follows −
public class ExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}
In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the
method that has a void no-argument signature. For example −
<bean id = "exampleBean" class = "[Link]" init-method = "init"/>

Following is the class definition −

public class ExampleBean {


public void init() {
// do some initialization work
}
}

Destruction callbacks
The [Link] interface specifies a single method −
void destroy() throws Exception;

Thus, you can simply implement the above interface and finalization work can be done inside destroy() method as follows −

public class ExampleBean implements DisposableBean {


public void destroy() {
// do some destruction work
}
}
In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the
method that has a void no-argument signature. For example −
<bean id = "exampleBean" class = "[Link]" destroy-method = "destroy"/>

Following is the class definition −

public class ExampleBean {


public void destroy() {
// do some destruction work
}
}

If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop
environment, you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant
destroy methods on your singleton beans so that all resources are released.

It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives
much flexibility in terms of naming your method.

Bean Configuration styles: - To create a Spring Bean in 3 different ways as follows:


1. Creating Bean Inside an XML Configuration File ([Link])
2. Using @Component Annotation
3. Using @Bean Annotation

Method 1: Creating Bean Inside an XML Configuration File ([Link])

One of the most popular ways to create a spring bean is to define a bean in an XML configuration file something like this.

<bean id="AnyUniqueId" class="YourClassName">


</bean>
Let us create a simple class Student having two attributes id and studentName and later creating a simple method to print
the details of the student.
Example
// Java Program to Illustrate Student Class

// Class
public class Student {

// Class data members


private int id;
private String studentName;

// Method
public void displayInfo()
{
// Print statement
[Link]("Student Name is " + studentName
+ " and Roll Number is " + id);
}
}
Now let’s create an XML file named [Link] file in the project classpath. And inside this [Link] file, we have to
define our Student bean something like this. And that’s it. In this way, you can create beans in spring.

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="[Link] "
xmlns:xsi="[Link] "
xsi:schemaLocation="[Link]
[Link] ">
<bean id="studentAmiya" class="Student">

</bean>

</beans>

Method 2: Using @Component Annotation

Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide
supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It
does not change the action of the compiled program. @Component is an annotation that allows Spring to automatically
detect the custom beans.
Example: Suppose we have already a Java project and all the Spring JAR files are imported into that project. Now let’s
create a simple class named College and inside the class, we have a simple method. Below is the code for
the [Link] file.
A. File: [Link]
// Java Program to Illustrate College Class

package ComponentAnnotation;

// Class
public class College {

// Method
public void test()
{
// Print statement
// whenever this method is called
[Link]("Test College Method");
}
}
Now let’s create a Bean for this class. So we can use @Component annotation for doing the same task. So we can modify
our [Link] file something like this. And that’s it.
B. [Link]
// Java Program to Illustrate College Class

package ComponentAnnotation;

// Importing required classes


import [Link];

@Component("collegeBean")

// Class
public class College {

// Method
public void test()
{
// Print statement
[Link]("Test College Method");
}
}

Method 3: Using @Bean Annotation

One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it
returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes
methods.
Suppose we have already a Java project and all the Spring JAR files are imported into that project. Now let’s create a
simple class named College and inside the class, we have a simple method. Below is the code for the [Link] file.
A. [Link]
package BeanAnnotation;

import [Link];

public class College {

public void test(){


[Link]("Test College Method");
}
}
Now let’s create a Configuration class named CollegeConfig. Below is the code for the [Link] file
B. [Link]
package ComponentAnnotation;

import [Link];
import [Link];

@Configuration
public class CollegeConfig {

Spring Boot: - Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can
"just run".

We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot
applications need minimal Spring configuration.

If you’re looking for information about a specific version, or instructions about how to upgrade from an earlier release, check out the project
release notes section on our wiki.

Features
 Create stand-alone Spring applications
 Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
 Provide opinionated 'starter' dependencies to simplify your build configuration
 Automatically configure Spring and 3rd party libraries whenever possible
 Provide production-ready features such as metrics, health checks, and externalized configuration
 Absolutely no code generation and no requirement for XML configuration

Spring Boot Build Systems:-In Spring Boot, choosing a build system is an important task. We
recommend Maven or Gradle as they provide a good support for dependency management. Spring does not support well
other build systems.

 Dependency Management

 Spring Boot team provides a list of dependencies to support the Spring Boot version for its every release. You do
not need to provide a version for dependencies in the build configuration file. Spring Boot automatically
configures the dependencies version based on the release. Remember that when you upgrade the Spring Boot
version, dependencies also will upgrade automatically.
 Note − If you want to specify the version for dependency, you can specify it in your configuration file. However,
the Spring Boot team highly recommends that it is not needed to specify the version for dependency.

 Maven Dependency
 For Maven configuration, we should inherit the Spring Boot Starter parent project to manage the Spring Boot
Starters dependencies. For this, simply we can inherit the starter parent in our [Link] file as shown below.
<parent>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>[Link]</version>
</parent>

 We should specify the version number for Spring Boot Parent Starter dependency. Then for other starter
dependencies, we do not need to specify the Spring Boot version number. Observe the code given below −

<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

 Learn Spring Boot in-depth with real-world projects through our Spring Boot certification course. Enroll and
become a certified expert to boost your career.

 Gradle Dependency
 We can import the Spring Boot Starters dependencies directly into [Link] file. We do not need Spring Boot
start Parent dependency like Maven for Gradle. Observe the code given below −
buildscript {
ext {
springBootVersion = '[Link]'
}
repositories {
mavenCentral()
}
dependencies {
classpath("[Link]:spring-boot-gradle-plugin:${springBootVersion}")
}
}

 Similarly, in Gradle, we need not specify the Spring Boot version number for dependencies. Spring Boot
automatically configures the dependency based on the version.

dependencies {
compile('[Link]:spring-boot-starter-web')
}

Spring Boot Code Structure:- There is no specific layout or code structure for Spring Boot
Projects. However, there are some best practices followed by developers that will help us too. You can divide your project
into layers like service layer, entity layer, repository layer,, etc. You can also divide the project into modules. For example,
the parent project has two child modules. The first module is for the data layer and the second module is for the web layer.
You can also divide the project into features.
Note: Avoid Default Package
It is. because a class is said to be in a default package when it does not include a package declaration. It is not a best
practice to include a class in the default package. It is because Spring scans the classes in packages and sub-packages
mentioned in the annotations like @ComponentScan, @EntityScan, @SpringBootApplication etc.
Note: It is recommended to use Java’s package naming conventions with a reverse domain name. For
example, [Link].
 Main Application Class
It is recommended to place the Main Application class in the root package with annotations
like @SpringBootApplication or @ComponentScan or @EnableAutoConfiguration. It allows the Spring to scan all
classes in the root package and sub-packages. For example, if you are writing a JPA application similar to the below layout
example, the [Link] is placed in the root package and all Customer-related classes in the sub-
package [Link] and Order related classes in the [Link].
Layout Structure is as follows:
Let us discuss two approaches that are typically used by most developers to structure their spring boot projects.
1. Structure by Feature
2. Structure by Layer
Structure 1: By feature
In this approach, all classes pertaining to a certain feature are placed in the same package. The structure by feature looks
is shown in below example
Example
com
+- gfg
+- demo
+- [Link]
|
+- customer
| +- [Link]
| +- [Link]
| +- [Link]
| +- [Link]
|
+- order
+- [Link]
+- [Link]
+- [Link]
+- [Link]
The advantages of this structure is as follows:
 Find a class to be modified is easy.
 By deleting a particular sub-package, all the classes related to a certain feature can be deleted.
 Testing and Refactoring is easy.
 Features can be shipped separately.
Structure 2: By Layer
Another way to place the classes is by layer i.e; all controllers can be placed in controllers package and services under
services package and all entities under domain or model etc.
Example
com
+- gfg
+- demo
+- [Link]
|
+- domain
| +- [Link]
| +- [Link]
|
+- controllers
| +- [Link]
| +- [Link]
|
+- services
| +- [Link]
| +- [Link]
|
+- repositories
+- [Link]
+- [Link]
Though the above structure looks feasible and easy to locate classes by a layer. It has few disadvantages when compared
to Structure by Feature.
 Features or Modules cannot be shipped separately.
 Hard to locate a class pertaining to a certain feature.
 Code Refactoring on a certain feature is difficult since the feature classes located in every layer.
 It causes merge conflicts among developers using GitHub, BitBucket, etc. for Collaboration.
Now let us wrap up by acquiring the location of [Link]. as in both the structures proposed above we have
seen that the [Link] is placed in the root package with @SpringBootApplication annotation. It s as
shown below in as a sample example which is as follows:
Example
@SpringBootApplication
public class MyApplication {

public static void main(String[] args) {


[Link]([Link], args);
}

Spring Boot Runners:- Application Runner and Command Line Runner interfaces lets you to
execute the code after the Spring Boot application is started. You can use these interfaces to perform any actions
immediately after the application has started. This chapter talks about them in detail.

Application Runner

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

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
public static void main(String[] args) {
[Link]([Link], args);
}
@Override
public void run(ApplicationArguments arg0) throws Exception {
[Link]("Hello World from Application Runner");
}
}

Command Line Runner

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

package [Link];

import [Link];
import [Link];
import [Link];

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
[Link]([Link], args);
}
@Override
public void run(String... arg0) throws Exception {
[Link]("Hello world from Command Line Runner");
}
}

Logger:-Logger in Spring Boot plays a vital role in Spring Boot applications for recording information, actions,
and events within the app. It is also used for monitoring the performance of an application, understanding the behavior of
the application, and recognizing the issues within the application. Spring Boot offers flexible logging capabilities by
providing various logging frameworks and also provides ways to manage and configure the logs.
Why to use Spring Boot – Logging?
A good logging infrastructure is necessary for any software project as it not only helps in understanding what’s going on
with the application but also to trace any unusual incident or error present in the project. This article covers several ways in
which logging can be enabled in a spring boot project through easy and simple configurations. Let’s first do the initial setup
to explore each option in more depth.
Elements of Logging Framework
 Logger: It captures the messages.
 Formatter: It formats the messages which are captured by loggers.
 Handler: It prints messages on the console, stores them in a file or sends an email, etc.
Java provides several logging frameworks, some of which are:
1. Logback Configuration logging
2. Log4j2 Configuration logging
3. Logging with Lombok
4. @Slf4j and @CommonsLog

BUILDING RESTFUL WEB SERVICES:- REST stands


for REpresentational State Transfer. It is developed by Roy Thomas Fielding, who also developed HTTP. The main
goal of RESTful web services is to make web services more effective. RESTful web services try to define services using the
different concepts that are already present in HTTP. REST is an architectural approach, not a protocol.

It does not define the standard message exchange format. We can build REST services with both XML and JSON. JSON is
more popular format with REST. The key abstraction is a resource in REST. A resource can be anything. It can be
accessed through a Uniform Resource Identifier (URI). For example:
The resource has representations like XML, HTML, and JSON. The current state capture by representational resource. When
we request a resource, we provide the representation of the resource. The important methods of HTTP are:
o GET: It reads a resource.
o PUT: It updates an existing resource.
o POST: It creates a new resource.
o DELETE: It deletes the resource.
For example, if we want to perform the following actions in the social media application, we get the corresponding results.
POST /users: It creates a user.
GET /users/{id}: It retrieves the detail of a user.
GET /users: It retrieves the detail of all users.
DELETE /users: It deletes all users.
DELETE /users/{id}: It deletes a user.
GET /users/{id}/posts/post_id: It retrieve the detail of a specific post.
POST / users/{id}/ posts: It creates a post of the user.
Further, we will implement these URI in our project.
HTTP also defines the following standard status code:
o 404: RESOURCE NOT FOUND
o 200: SUCCESS
o 201: CREATED
o 401: UNAUTHORIZED
o 500: SERVER ERROR

RESTful Service Constraints


o There must be a service producer and service consumer.
o The service is stateless.
o The service result must be cacheable.
o The interface is uniform and exposing resources.
o The service should assume a layered architecture.

Advantages of RESTful web services


o RESTful web services are platform-independent.
o It can be written in any programming language and can be executed on any platform.
o It provides different data format like JSON, text, HTML, and XML.
o It is fast in comparison to SOAP because there is no strict specification like SOAP.
o These are reusable.
o They are language neutral.

Rest Controller:- RestController is used for making restful web services with the help of the
@RestController annotation. This annotation is used at the class level and allows the class to handle the requests made
by the client. Let’s understand @RestController annotation using an example. The RestController allows to handle all
REST APIs such as GET, POST, Delete, PUT requests.
Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also
provides various different features for the projects expressed in a metadata model. This model allows us to configure the
list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer
and then use an IDE to create a sample GET route. Therefore, to do this, the following steps are followed sequentially as
follows.

Step by Step Implementation

Step 1: Go to Spring Initializr


Fill in the details as per the requirements. For this application:

Project: Maven
Language: Java
Spring Boot: 2.2.8
Packaging: JAR
Java: 8
Dependencies: Spring Web
Step 2: Click on Generate which will download the starter project
Step 3: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-
boot-app and select [Link]. Click on import changes on prompt and wait for the project to sync as pictorially depicted
below as follows:

Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while
creating the project.
Step 4: Go to src > main > java > [Link], create a java class with the name Controller and add the
annotation @RestController and other class named as Details.

Request Mapping :- ne of the most important annotations in spring is


the @RequestMapping Annotation which is used to map HTTP requests to handler methods of MVC and REST
controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP
requests to handler methods of controllers. When configuring Spring MVC, you need to specify the mappings between the
requests and handler methods. To configure the mapping of web requests, we use the @RequestMapping annotation.
The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. RequestMapping can
be applied to the controller class as well as methods. Today we will look into various usage of this annotation with example
and other annotations @PathVariable and @RequestParam.
Spring @RequestMapping
1. @RequestMapping with Class: We can use it with class definition to create the base URI. For example:
@Controller
@RequestMapping("/home")
public class HomeController {

Now /home is the URI for which this controller will be used. This concept is very similar to servlet context of a web application.
2. @RequestMapping with Method: We can use it with method to provide the URI pattern for which handler method will be used. For
example:
@RequestMapping(value="/method0")
@ResponseBody
public String method0(){
return "method0";
}
Above annotation can also be written as @RequestMapping("/method0"). On a side note, I am using @ResponseBody to send
the String response for this web request, this is done to keep the example simple. Like I always do, I will use these methods in
Spring MVC application and test them with a simple program or script.
3. @RequestMapping with Multiple URI: We can use a single method for handling multiple URIs, for example:

@RequestMapping(value={"/method1","/method1/second"})
@ResponseBody
public String method1(){
return "method1";
}
If you will look at the source code of RequestMapping annotation, you will see that all of it’s variables are arrays. We can create
String array for the URI mappings for the handler method.
4. @RequestMapping with HTTP Method: Sometimes we want to perform different operations based on the HTTP method used,
even though request URI remains same. We can use @RequestMapping method variable to narrow down the HTTP methods for
which this method will be invoked. For example:
@RequestMapping(value="/method2", method=[Link])
@ResponseBody
public String method2(){
return "method2";
}

@RequestMapping(value="/method3", method={[Link],[Link]})
@ResponseBody
public String method3(){
return "method3";
}
5. @RequestMapping with Headers: We can specify the headers that should be present to invoke the handler method. For example:
@RequestMapping(value="/method4", headers="name=pankaj")
@ResponseBody
public String method4(){
return "method4";
}

@RequestMapping(value="/method5", headers={"name=pankaj", "id=1"})


@ResponseBody
public String method5(){
return "method5";
}
6. @RequestMapping with Produces and Consumes: We can use header Content-Type and Accept to find out request contents
and what is the mime message it wants in response. For clarity, @RequestMapping provides produces and consumes variables
where we can specify the request content-type for which method will be invoked and the response content type. For example:
@RequestMapping(value="/method6", produces={"application/json","application/xml"}, consumes="text/html")
@ResponseBody
public String method6(){
return "method6";
}
Above method can consume message only with Content-Type as text/html and is able to produce messages of
type application/json and application/xml.

Path Variable :-The @PathVariable annotation is used to extract data from the URL path. It allows you to
define placeholders in your request mapping URL and bind those placeholders to method parameters. Let’s consider an
example where you have a REST API endpoint for retrieving a user’s details by their ID:

@RestController
@RequestMapping("/users")
public class UserController {

@GetMapping("/{userId}")
public ResponseEntity<User> getUserDetails(@PathVariable Long userId) {
// Implementation to fetch user details based on the provided userId
// ...
return [Link](user);
}
}
In the above code, the @PathVariable annotation is used to extract the userId from the URL path. The {userId} placeholder
is defined in the @GetMapping annotation’s URL mapping. The value of the {userId} placeholder will be extracted and
passed as the userId method parameter. When a request is made to /users/123, the value 123 will be passed to the
getUserDetails method as the userId parameter. You can then use this ID to fetch the user details from a database or any
other data source.

Request Parameter:- The RequestParam annotation is used to extract data from the query
parameters in the request URL. Query parameters are the key-value pairs that appear after the ? in a URL. Let’s consider
an example where you have a REST API endpoint for searching users based on a query parameter:
@RestController
@RequestMapping("/users")
public class UserController {

@GetMapping("/search")
public ResponseEntity<List<User>> searchUsers(@RequestParam("name")
String name) {
// Implementation to search users based on the provided name
// ...
return [Link](users);
}
}
In the above code, the @RequestParam annotation is used to extract the name parameter from the query parameters. The
name parameter is specified as an argument of the @RequestParam annotation. When a request is made to
/users/search?name=John, the value John will be passed to the searchUsers method as the name parameter. You can
then use this parameter to perform a search operation based on the provided name.

Spring Boot CRUD Operations


What is the CRUD operation?
The CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the four basic functions of the persistence
storage.

The CRUD operation can be defined as user interface conventions that allow view, search, and modify information through
computer-based forms and reports. CRUD is data-oriented and the standardized use of HTTP action verbs. HTTP has a
few important verbs.

o POST: Creates a new resource


o GET: Reads a resource
o PUT: Updates an existing resource
o DELETE: Deletes a resource
Within a database, each of these operations maps directly to a series of commands. However, their relationship with a
RESTful API is slightly more complex.

Standard CRUD Operation


o CREATE Operation: It performs the INSERT statement to create a new record.
o READ Operation: It reads table records based on the input parameter.
o UPDATE Operation: It executes an update statement on the table. It is based on the input parameter.
o DELETE Operation: It deletes a specified row in the table. It is also based on the input parameter.

How CRUD Operations Works

CRUD operations are at the foundation of the most dynamic websites. Therefore, we should differentiate CRUD from
the HTTP action verbs.

Suppose, if we want to create a new record, we should use HTTP action verb POST. To update a record, we should use
the PUT verb. Similarly, if we want to delete a record, we should use the DELETE verb. Through CRUD operations, users
and administrators have the right to retrieve, create, edit, and delete records online.

We have many options for executing CRUD operations. One of the most efficient choices is to create a set of stored
procedures in SQL to execute operations.

The CRUD operations refer to all major functions that are implemented in relational database applications. Each letter of
the CRUD can map to a SQL statement and HTTP methods.

Operation SQL HTTP verbs RESTful Web Service

Create INSERT PUT/POST POST

Read SELECT GET GET

Update UPDATE PUT/POST/PATCH PUT

Delete DELETE DELETE DELETE

Build Web Applications:-This guide provides a sampling of how Spring Boot helps you accelerate
application development. As you read more Spring Getting Started guides, you will see more use cases for Spring Boot. This guide is meant
to give you a quick taste of Spring Boot. If you want to create your own Spring Boot-based project, visit Spring Initializr, fill in your project
details, pick your options, and download a bundled up project as a zip file.
What You Will build
You will build a simple web application with Spring Boot and add some useful services to it.
What You Need
 About 15 minutes
 A favorite text editor or IDE
 Java 17 or later
 Gradle 7.5+ or Maven 3.5+
 You can also import the code straight into your IDE:
 Spring Tool Suite (STS)
 IntelliJ IDEA
 VSCode
How to complete this guide
Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are
already familiar to you. Either way, you end up with working code.
To start from scratch, move on to Starting with Spring Initializr.
To skip the basics, do the following:
 Download and unzip the source repository for this guide, or clone it using Git: git
clone [Link]
 cd into gs-spring-boot/initial
 Jump ahead to Create a Simple Web Application.
When you finish, you can check your results against the code in gs-spring-boot/complete .

Learn What You Can Do with Spring Boot


Spring Boot offers a fast way to build applications. It looks at your classpath and at the beans you have configured, makes reasonable
assumptions about what you are missing, and adds those items. With Spring Boot, you can focus more on business features and less on
infrastructure.
The following examples show what Spring Boot can do for you:
 Is Spring MVC on the classpath? There are several specific beans you almost always need, and Spring Boot adds them automatically. A
Spring MVC application also needs a servlet container, so Spring Boot automatically configures embedded Tomcat.
 Is Jetty on the classpath? If so, you probably do NOT want Tomcat but instead want embedded Jetty. Spring Boot handles that for you.
 Is Thymeleaf on the classpath? If so, there are a few beans that must always be added to your application context. Spring Boot adds them
for you.
These are just a few examples of the automatic configuration Spring Boot provides. At the same time, Spring Boot does not get in
your way. For example, if Thymeleaf is on your path, Spring Boot automatically adds a SpringTemplateEngine to your
application context. But if you define your own SpringTemplateEngine with your own settings, Spring Boot does not add one.
This leaves you in control with little effort on your part.
Spring Boot does not generate code or make edits to your files. Instead, when you start your application,
Spring Boot dynamically wires up beans and settings and applies them to your application context.

You might also like