[Go to site: main page, start]

0% found this document useful (0 votes)
8 views9 pages

Introduction to Spring Framework Basics

The document provides an overview of the Spring Framework, highlighting its benefits such as simplified development, loose coupling, and scalability. It explains key features like Dependency Injection, Aspect-Oriented Programming, and various Spring modules including Spring MVC and Spring Security. Additionally, it covers concepts related to POJOs, IoC containers, and different types of Dependency Injection, including Setter and Constructor Injection, along with autowiring modes.

Uploaded by

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

Introduction to Spring Framework Basics

The document provides an overview of the Spring Framework, highlighting its benefits such as simplified development, loose coupling, and scalability. It explains key features like Dependency Injection, Aspect-Oriented Programming, and various Spring modules including Spring MVC and Spring Security. Additionally, it covers concepts related to POJOs, IoC containers, and different types of Dependency Injection, including Setter and Constructor Injection, along with autowiring modes.

Uploaded by

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

Java Unit 3

Introduction to Spring Framework


The Spring Framework is a lightweight Java framework widely used for building scalable,
maintainable enterprise applications. It offers a comprehensive programming and configuration
model for Java-based development.

Benefits of Using Spring Framework


• Simplified Development: Spring reduces boilerplate code with features like Dependency
Injection and AOP, making development faster and easier.
• Loose Coupling: Dependency Injection ensures components are loosely coupled, improving
maintainability and testability.
• Modular: Spring's modular architecture allows developers to use only the required
components, improving flexibility and efficiency.
• Integration Support: Spring provides built-in support for various technologies like JDBC,
JMS and JPA, making integration with other systems seamless.
• Scalability: Spring's lightweight nature and support for various web and enterprise
components make it highly scalable for large applications.

Key Features of Spring Framework

• Dependency Injection: Dependency Injection is a design pattern where the Spring


container automatically provides the required dependencies to a class, instead of the class
creating them itself. This promotes loose coupling, easier testing and better maintainability
by decoupling the object creation and usage.
• Aspect-Oriented Programming (AOP): AOP allows developers to separate cross-cutting
concerns (such as logging, security and transaction management) from the business logic.
• Transaction Management: Spring provides a consistent abstraction for managing
transactions across various databases and message services.
• Spring MVC: It is a powerful framework for building web applications that follow the
Model-View-Controller pattern.
• Spring Security: Spring Security provides comprehensive security features including
authentication, authorization and protection against common vulnerabilities.
• Spring Data: Spring Data is a part of the Spring Framework that simplifies database access
by providing easy-to-use abstractions for working with relational and non-relational
databases.
• Spring Batch: Spring Batch is a framework in Spring for handling large-scale batch
processing, such as reading, processing and writing data in bulk.
• Integration with Other Frameworks: Spring integrates seamlessly with other technologies
like Hibernate, JPA, JMS and more, making it versatile for various enterprise applications.

POJO
A POJO (Plain Old Java Object) is a simple Java object that is not bound by any special restriction
other than those enforced by the Java Language Specification. It does not require any specific
framework or classpath dependency.
POJOs were introduced by Sun Microsystems with EJB 3.0 to simplify enterprise Java development
by removing the heavy restrictions of earlier Enterprise JavaBeans (EJB) components.

Properties of a POJO
A class is considered a POJO if it does not:
• Extend any predefined class (e.g., HttpServlet, EntityBean, etc.)
• Implement any predefined interface (e.g., [Link])
• Contain framework-specific annotations (e.g., @Entity, @Component)
POJOs are used to represent entities in business logic, for example:
// Employee POJO class
public class Employee {
// default field
String name;
// public field
public String id;
// private field
private double salary;
// parameterized constructor
public Employee(String name, String id, double salary) {
[Link] = name;
[Link] = id;
[Link] = salary;
}
// getter methods
public String getName() {
return name;
}
public String getId() {
return id;
}
public Double getSalary() {
return salary;
}
}
Note :- There are no restrictions on access modifiers. Fields can be private, protected, public, or
default.
• A constructor is optional.
• It can contain business logic and represent entities directly in the application.

Spring - IoC Container


The Spring framework is a powerful framework for building Java applications. It can be
considered a collection of sub-frameworks, also referred to as layers, such as Spring AOP, Spring
ORM, Spring Web Flow, and Spring Web MVC. We can use any of these modules separately
while constructing a Web application. The modules may also be grouped to provide better
functionalities in a web application.
Spring Container
The core component of the spring framework is the Inversion of Control (IOC) container, which is
responsible for managing the lifecycle of objects called beans and their dependencies. Spring
provides two types of containers:
• BeanFactory Container
• This is the basic container that provides support for dependency injection.
• In this, beans are instantiated only when explicitly requested.
• It is lightweight and suitable for resource-constrained environments.
• ApplicationContext Container
• This is an advanced container built on top of the BeanFactory.
• It includes all the features of BeanFactory and adds extra functionalities such as
internationalization, event propagation, and integration with other Spring modules.
• In this, beans are created and configured at startup.

Key feature of Spring Framework


The features of the Spring framework, such as IoC, AOP, and transaction management, make it
unique among Java frameworks. Some of the most important features include:
• IoC Container
• Data Access Framework (JDBC abstraction layer)
• Spring MVC
• Transaction Management
• Spring Web Services
• Spring TestContext Framework

Spring IOC Container


Spring IoC is a design principle where the control of object creation and lifecycle is transferred
from the developer to the framework. The IoC container is responsible for:
1. Creating objects (Beans)
2. Configuring dependencies via Dependency Injection (DI)
3. Managing the entire lifecycle of beans, from instantiation to destruction
4. Reading configuration metadata (XML, Java Config, or Annotations)
Note: The objects managed by the container are called beans.

The below diagram demonstrates how the Container makes use of Configuration metadata and Java
POJO classes to manage beans.

Working of IoC Container


• The container reads configuration metadata (XML, Java annotations, or Java-based
configuration) to understand how beans should be creates and wired together.
• It uses Dependency Injection (DI) to inject dependencies into beans at runtime.
• The container manages the entire lifecycle of beans, from instantiation to destruction.

Spring Dependency Injection with Example


Dependency Injection (DI) is a design pattern in which objects receive their dependencies from an
external source rather than creating them internally. It promotes loose coupling, easier testing, and
better code maintainability. In Spring, DI is achieved mainly through Constructor Injection or Setter
Injection.

Need for Dependency Injection


• Suppose class One requires an object of class Two to perform its operations. It means class
One is dependent on class Two.
• While such dependency may seem acceptable, in real-world applications, it can lead to Tight
coupling, Difficulty in maintenance, reduced testability or potential system failures.
• Therefore, direct dependencies should be avoided.
• Spring IoC (Inversion of Control) resolves such dependency issues using Dependency
Injection (DI).
• Dependency Injection makes the code easier to test and reuse.
• Loose coupling between classes is achieved by defining interfaces for common functionality
or Letting the injector (Spring container) provide the appropriate implementation.
• The task of instantiating objects is done by the container according to the configurations
specified by the developer.
Types of Spring Dependency Injection
There are two primary types of Spring Dependency Injection:
1. Setter Dependency Injection (SDI):
Setter DI involves injecting dependencies via setter methods. To configure SDI, the @Autowired
annotation is used along with setter methods and the property is set through the <property> tag
in the bean configuration file.
package [Link];
import [Link];
import [Link];
public class GFG {
// The object of the interface IGeek
private IGeek geek;
// Setter method for property geek with @Autowired annotation
@Autowired
public void setGeek(IGeek geek) {
[Link] = geek;
}
}
Bean Configuration:
<beans
xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="
[Link]
[Link]
<bean id="GFG" class="[Link]">
<property name="geek" ref ="CsvGFG" />
</bean>
<bean id="CsvGFG" class="[Link]" />
<bean id="JsonGFG" class="[Link]" />
</beans>
This injects the CsvGFG bean into the GFG object using the setter method (setGeek).

2. Constructor Dependency Injection (CDI):


Constructor DI involves injecting dependencies through constructors. To configure CDI, the
<constructor-arg> tag is used in the bean configuration file.

package [Link];
import [Link];
public class GFG {
// The object of the interface IGeek
private IGeek geek;
// Constructor to set the CDI
public GFG(IGeek geek) {
[Link] = geek;
}
}
Bean Configuration
<beans
xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="
[Link]
[Link]
<bean id="GFG" class="[Link]">
<constructor-arg>
<bean class="[Link]" />
</constructor-arg>
</bean>
<bean id="CsvGFG" class="[Link]" />
<bean id="JsonGFG" class="[Link]" />
</beans>
Setter Dependency Injection (SDI) vs. Constructor Dependency Injection (CDI)
Setter DI Constructor DI
Creates mutable objects. Dependencies can be Creates immutable objects. Dependencies can't
modified after creation. be modified after creation.
Dependencies can be injected later. All dependencies must be provided at creation.
@Autowired annotation is not needed.
Requires addition of @Autowired annotation.
It results in circular dependencies or partial It too can have circular dependencies, it just fails
dependencies. faster and more explicitly.
Requires framework or manual setter calls for Easier unit testing - can create objects directly
dependency injection in tests. with mock dependencies.

Spring - Autowiring
Autowiring in the Spring framework can inject dependencies automatically. The Spring container
detects those dependencies specified in the configuration file and the relationship between the
beans. This is referred to as Autowiring in Spring. 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 supposed to be done. It is the
No
default mode used by Spring.

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

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

Constructor It injects the required dependencies by invoking the constructor.

Autodetect The autodetect mode uses two other modes for 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>
Example of Autowiring

Sample Program for the byType Mode


[Link]:
public class State {
private String name;
public String getName() { return name; }
public void setName(String s) { [Link] = s; }
}
[Link]:
class City {
private int id;
private String name;
@Autowired
private State s;
public int getID() {
return id;
}
public void setId(int eid) {
[Link] = eid;
}
public String getName() {
return name;
}
public void setName(String st) {
[Link] = st;
}
public State getState() {
return s;
}
public void showCityDetails() {
[Link]("City Id : " + id);
[Link]("City Name : " + name);
[Link]("State : " + [Link]());
}
}
Spring bean configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:context="[Link]
xsi:schemaLocation="[Link]
[Link]
[Link]
[Link]
[Link]
[Link]">
<bean id="state" class="[Link]">
<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" autowire="byName"></bean>
</beans>
Test Program file: [Link]
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
[Link]([Link], args);
ApplicationContext context = new
ClassPathXmlApplicationContext("[Link]");
City cty = [Link]("city", [Link]);
[Link](01);
[Link]("Varanasi");
State st = [Link]("state", [Link]);
[Link]("UP");
[Link](st);
[Link]();
}
}

You might also like