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

What Is Spring

Spring is a lightweight Java framework that simplifies application development by providing tools for dependency injection, object management, and web development. It includes features like Spring Core, Spring MVC, and Spring Boot, allowing for efficient creation of various application types. The Spring Container manages the lifecycle of beans, handling their creation, dependency injection, and destruction, while supporting both XML-based and Java-based configurations.

Uploaded by

Sarthak Jadhav
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)
2 views47 pages

What Is Spring

Spring is a lightweight Java framework that simplifies application development by providing tools for dependency injection, object management, and web development. It includes features like Spring Core, Spring MVC, and Spring Boot, allowing for efficient creation of various application types. The Spring Container manages the lifecycle of beans, handling their creation, dependency injection, and destruction, while supporting both XML-based and Java-based configurations.

Uploaded by

Sarthak Jadhav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

What is Spring?

(Simple Explanation)
Spring is a Java framework that helps developers build powerful and efficient applications. It
provides tools and features to make coding easier, faster, and more organized.using spring
we can create any type of application like as console-based,databased application,web
application,enterprise application.

It is a powerful and light weighted framework of java.

Why Use Spring?

• Saves Time – Reduces the amount of code you need to write.

• Manages Objects – Automatically creates and manages objects in your


program.provide loose coupling

• Flexible – Works with databases, web applications, security, and more.

• Supports Web Development – Helps create websites and REST APIs.

• Provide the predefined libraries and templates.

• Manage the dependency injection and IOC container manually

Key Features of Spring:

1. Spring Core – Manages objects in your application (Dependency Injection).

2. Spring MVC – Helps build web applications.

3. Spring Boot – Simplifies Spring projects (no need for complex configurations).

4. Spring Data – Makes database operations easier.

5. Spring Security – Adds security (login, roles, permissions).

6. Spring Cloud – Used for building microservices.

Example: Instead of writing long Java code to connect to a database, Spring does it for you in
just a few lines!

What is a Spring Container? (Simple Explanation)


A Spring Container is like a manager that creates and controls objects (called beans) in a
Spring application. It takes care of:
Creating objects (beans)
Managing dependencies (how objects connect with each other)
Destroying objects when they are no longer needed
How Does It Work?

1. You tell Spring which objects (beans) you need.

2. Spring automatically creates those objects.

3. If one object depends on another, Spring connects them (Dependency Injection).

4. When the application ends, Spring cleans up the objects.

Types of Spring Containers:


1. BeanFactory – Basic container, used in small applications.

2. ApplicationContext – More powerful, used in web and enterprise applications.

Example:

Imagine you own a restaurant. The Spring Container is like the kitchen manager who:

• Prepares ingredients (creates beans)

• Assembles the dish (injects dependencies)


• Cleans up after cooking (destroys beans)

Responsibilities of the Spring Container

The Spring Container is responsible for managing the entire lifecycle of objects (beans) in a
Spring application. Here are its main responsibilities:

1. Creating Objects (Beans)

• The container creates objects based on the configuration (XML, Annotations, or Java-
based).

• You don’t need to manually create objects using new, Spring does it for you.

2. Managing Dependencies (Dependency Injection)

• If one object needs another, the container automatically connects them.

• This removes the need for complex object management in your code.

3. Configuring Beans

• The container sets values and properties of beans based on the provided
configuration.

4. Handling Bean Lifecycle

• Creating the bean.

• Initializing the bean (calling setup methods).

• Using the bean in the application.

• Destroying the bean when it’s no longer needed.

5. Providing Different Scopes

• Singleton (one instance per application).

• Prototype (new instance each time).

• Request, Session, and more (for web applications).

6. Enabling AOP (Aspect-Oriented Programming)

• Helps with features like logging, security, and transaction management without
modifying main code.

7. Managing Transactions

• The container helps handle database transactions automatically.

8. Supporting Event Handling


• Components in the application can communicate with each other using Spring
Events.

Steps to Create a Bean Object in Spring


There are three ways to create a bean in Spring:

1.XML-Based Configuration (Old Method)


Spring reads an XML file to know which objects (beans) to create.

• Application.context.XML-Standard name.
• Spring Configuration File.
• Provide Instruction for Spring Container.

What is XML-Based Configuration?

XML-Based Configuration is a method where bean definitions (objects and their


dependencies) are written in an XML file. The Spring Container reads this XML file, creates
objects, and manages their lifecycle.

How XML-Based Configuration Works?

1. Spring reads the XML file during application startup.

2. It finds bean definitions that specify which classes should be instantiated as beans.

3. The container creates objects (beans) based on the XML definitions.

4. Beans are stored in the ApplicationContext and can be retrieved whenever needed.

JAR Files Required for Spring XML-Based Configuration

To use Spring XML configuration, we need some Spring Core JAR files. These files provide
the necessary classes and interfaces for Spring to work.

1.spring-core.jar

Contains the main classes of the Spring framework.


Provides features like BeanFactory, ApplicationContext, and Dependency Injection.
Required for every Spring project.
2.spring-beans.jar

Supports bean creation and dependency injection.


Contains classes related to <bean> and <property> tags in XML configuration.

3.spring-context.jar

Provides the ApplicationContext interface.


Supports advanced features like internationalization, event handling, and annotation
processing.
Needed for ClassPathXmlApplicationContext.

4.spring-expression.jar (Spring Expression Language - SpEL)

Allows using Spring Expression Language (SpEL) for dynamic values in beans.
Helps in setting properties dynamically inside XML files.

5.commons-logging.jar

Provides logging support for Spring applications.


Required if you use loggers in Spring.

Steps to Create a Bean Using XML-Based Configuration


Step 1: Create a POJO (Plain Old Java Object) or Java Bean Class

A POJO (Plain Old Java Object) is a simple Java class that follows standard conventions:
It has private properties (fields).
It has public getter and setter methods.
It has a default constructor (optional but recommended).

Step 2: Create the XML Configuration File

To tell Spring which beans to create, we need to define them inside an XML file (e.g.,
beans.xml).
2.1: Copy XML Schema

To create a valid Spring XML configuration file, we need to include the XML schema.

The XML schema defines the structure of the Spring configuration file.
We can find the schema by searching:
Google → "Spring Configuration file XML schema"

2.2: Create an XML File (beans.xml) and Define Beans

Once we have the XML schema, we create the configuration file and define beans inside it.

<bean> tag is used to define a bean (object) in Spring.


id="myBean" is the name of the bean used to retrieve it later.
class="MyBean" tells Spring to create an object of MyBean.
<property> sets the value of the message field using the setter method.

If we not pass the value into the property tag then automatically set default value.

Step 3: Create the Spring Container (Load XML and Get Bean Object)

Once we have our XML file, we need to tell Spring to read it and create objects (beans).
ClassPathXmlApplicationContext("beans.xml") → Loads the Spring Container and reads
the XML file.
context.getBean("myBean", MyBean.class) → Retrieves the bean object from Spring.

myBean→id

MyBean.class→POJO class name


obj.getMessage() → Calls a method on the Spring-managed object.

Java-Based Configuration in Spring (Recommended Method) – Simple


Explanation
In Java-based configuration, we do not use an XML file to define beans. Instead, we use Java
classes with annotations to tell Spring which objects (beans) to create and manage.

Why Use Java-Based Configuration?

No need for XML – Everything is in Java code.


Easier to read and maintain – No large XML files.
Faster development – Uses annotations like @Configuration and @Bean.
More control – Java code gives more flexibility than XML.

Step 1: Create a POJO (Plain Old Java Object) Class

What is a POJO?

A POJO (Plain Old Java Object) is a simple Java class with:


Private fields (variables)
Public getter and setter methods (if needed)
A default or parameterized constructor
No special restrictions (like extending a class or implementing an interface)

Why do we need a POJO?

Spring needs objects (beans) to manage in the application.


The POJO will be converted into a Spring bean using Java-based configuration.

Step 2: Create a Java Configuration Class


What is a Java Configuration Class?

A Java Configuration Class is a regular Java class that uses Spring annotations to define
bean objects instead of XML.

Key Annotations in Java Configuration

1. @Configuration

o Marks the class as a Spring configuration class.

o Similar to an XML configuration file (beans.xml).

o Tells Spring that this class contains bean definitions.

2. @Bean

o Marks a method as a Spring bean definition.

o The method returns an object, which Spring registers as a bean.

o The bean is managed by the Spring Container.

What is a Bean in Spring?


A Bean in Spring is an object that is created, managed, and controlled by the Spring
Container.

Key Points:

Beans are Java objects that are part of a Spring application.


Spring creates and manages these objects automatically.
Beans are defined using XML configuration or Java-based configuration (@Bean,
@Component).
They help in Dependency Injection (DI) by allowing objects to be injected into other
objects.

Note: you can set a value (inject data) into a bean using @Bean and a setter method.

Step 3: Load Spring and Get the Bean


Note: we can provide bean name.

Annotation-Based Configuration: Java or XML?


Annotation-based configuration mainly uses Java files, but it can also work with XML files.
Let's explore both approaches.

1.Using Annotations with XML (Hybrid Approach)

In the hybrid approach, we use both annotations and XML configuration together. This helps
if you are migrating from an old XML-based Spring project but still want to use modern
annotations.

How It Works?

1.We write Java classes and mark them with annotations like @Component, @Service,
@Repository, etc.
2.Instead of defining beans manually in XML, we enable Component Scanning in an XML file.
3.Spring automatically detects and creates objects (beans) based on annotations.
Key Components in the Hybrid Approach

1.Annotations in Java Classes – We use annotations like @Component, @Autowired, etc. to


define and manage objects.

2.XML Configuration (applicationContext.xml) – Instead of defining beans manually, we tell


Spring to scan for annotated classes.

Example Workflow (Step-by-Step)

1.Write Java Classes with Annotations

• Instead of defining beans in XML, we mark Java classes with @Component.

2.Enable Component Scanning in XML

• Instead of manually defining each bean, we add <context:component-scan> in XML


to scan and detect annotated classes.

3.Load XML in Java Code

• In the main method, we load the XML configuration to start the Spring container.
Note: setting properties for beans using annotations, you can use @Value for injecting
values.

2. Using Only Java Files (Recommended)


In Java-based configuration, we create a Spring application without XML. Instead, we use
Java classes and annotations to set up everything. Here’s how it works:

1.Mark Java classes as Spring components using @Component

We tell Spring which classes should be created as objects (beans) using @Component.
✔ This makes the class part of the Spring container (Spring will manage it).
2.Enable Component Scanning using @ComponentScan

What does this mean?


We tell Spring, "Please look for all classes marked with @Component and create their
objects automatically."

✔ We do this in a separate configuration class using @ComponentScan.

• @Configuration: This tells Spring that this class contains configuration settings (like
an XML file but in Java).
• @ComponentScan("in.sp.beans"):
This tells Spring to scan the package in.sp.beans for classes marked with
@Component, @Service, or @Repository.
Spring will automatically create objects (beans) of those classes.

3.Run the Application using a Spring Container

What does this mean?


To use Spring, we need to start it using a special class called
AnnotationConfigApplicationContext.
✔ This will create objects and connect dependencies automatically.

AnnotationConfigApplicationContext(SpringConfigFile.class):
This loads the Spring configuration from SpringConfigFile.
It scans for components (classes annotated with @Component inside the specified
package).

context.getBean("student"):
Retrieves the bean named "student" from the Spring container.
The name "student" is usually the class name in lowercase if @Component is used
without a custom name.
Typecasting to (Student) ensures the correct type.
What are the init-method and destroy-method in the bean lifecycle?
• init-method → Called after bean creation for initialization.

• destroy-method → Called before bean destruction for cleanup.

How Does Spring Handle Singleton and Prototype Bean Scopes?


In Spring Framework, a bean scope defines how the Spring container creates and manages
beans. The two most commonly used scopes are:

1⃣ Singleton Scope (Default)


2⃣ Prototype Scope

1⃣ Singleton Scope (Default in Spring)

Definition:

• In Singleton scope, only one instance of a bean is created per Spring container.

• Every time you request the bean, the same instance is returned.

• Best for stateless objects (e.g., service classes).

How it Works Internally?

1. When the Spring container starts, it creates one instance of the singleton bean and
stores it in memory.

2. Whenever you request that bean, Spring returns the same instance instead of
creating a new one.

3. If multiple objects use the same bean, they all share the same instance.
2⃣ Prototype Scope

Definition:

• In Prototype scope, a new instance of the bean is created every time it is requested.

• Best suited for stateful objects that need separate instances.

• Unlike singleton, prototype beans are not managed after creation (i.e., Spring does
not destroy them).

How it Works Internally?

1. When the Spring container starts, it does not create the prototype bean
immediately.

2. Every time you request the bean, a new instance is created and returned.

3. Each object gets a fresh instance, so they do not share data.

Example of Prototype Scope


What is lazy initialization in Spring? How do you enable it?
Lazy Initialization in Spring means that a bean is not created at the time of application
startup but is created only when it is needed for the first time.

By default, Singleton Beans in Spring are eagerly initialized, meaning they are created at the
time of application startup. However, using lazy initialization, we can delay bean creation
until it is actually required.

How Does Lazy Initialization Work?

1⃣ Eager Initialization (Default Behavior)


• Spring creates all singleton beans at the time of application startup.

• This ensures that the beans are ready to use but can slow down application startup.

2⃣ Lazy Initialization (Enabled Manually)

• Spring delays the creation of a bean until it is accessed for the first time.

• This reduces startup time and memory usage if a bean is not required immediately.

How to Enable Lazy Initialization in Spring?

1⃣ Using @Lazy Annotation (Java Configuration)

You can use @Lazy annotation at the class level or bean level to enable lazy initialization.

Spring Bean Life Cycle


The Spring Bean Life Cycle is the process that a Spring-managed object (bean) goes through
from creation to destruction. Spring automatically manages the lifecycle of beans so that
developers don’t have to worry about object creation, initialization, or cleanup.

Step 1: Loading Bean Definitions (Simplified Explanation)


1⃣ What is happening?

• Spring loads bean definitions from different sources:

o XML configuration files (if using XML-based configuration)

o Java configuration classes (if using annotation-based configuration)

o Component scanning (if using @Component, @Service, etc.)

2⃣ Why is this important?

• These bean definitions tell Spring:

o What objects (beans) should be created.

o What dependencies the beans need.

o Any additional configurations like scope (singleton or prototype).

Step 2: Bean Instantiation (Simplified Explanation)

1⃣ What is happening?

• After loading the bean definitions, Spring creates objects of the beans.

• It calls the constructor of the bean class to make an actual instance.

2⃣ How does it work?

• If no constructor is provided, Spring uses the default constructor.

• If a constructor with parameters is present, Spring will use it (if dependencies are
available).

• Set the default value.

• Provide the unique id.

Step 3: Bean Initialization (Simplified Explanation)

1⃣ What is happening?

• After the bean object is created, Spring initializes it by setting its properties.

2⃣ How does Spring set values?

• Using constructor arguments (if a constructor is present)

• Using setter methods (if no constructor arguments are provided)

• Using field injection (@Autowired) to inject dependencies automatically


Step 4: Using the Bean Object (Simplified Explanation)

1⃣ What is happening?

• After the bean is initialized, we can use it in our application.

• We call its methods to perform required operations.

Step 5: Destroying the Bean Object (Simplified Explanation)

1⃣ What is happening?

• When the application closes, Spring removes the bean from memory.

• If a custom destroy method is specified, Spring calls it before destruction.

2⃣ How to Define a Destroy Method?

• Using @PreDestroy (Recommended)

• Using destroyMethod in XML

What is a Java Bean Class?


A Java Bean is a special type of Java class that follows specific rules. It is used to store and
manage data, mainly in Java frameworks like Spring.

Rules of a Java Bean Class:

1.Must have a default (no-argument) constructor

• Allows frameworks like Spring to create objects easily.


2.All fields (variables) should be private

• This ensures data encapsulation (hiding data from direct access).

3.Public getter and setter methods

• Used to read (get) and modify (set) private variables.

4.Should be Serializable (optional but recommended)

• Helps in saving and transferring object data.

What is Dependency Injection (DI)?


Definition:
"DI is the process by which we can inject one bean object into another bean object."

In simple terms, instead of creating objects manually inside a class, we provide (inject) them
from outside. This helps make the code more flexible, maintainable, and testable.

Depedency Injection achieve loose coupling.

What are the different types of Dependency Injection in Spring?


Spring provides three types of Dependency Injection:

1. Constructor Injection → Injects dependencies using the class constructor.

2. Setter Injection → Injects dependencies using setter methods.

3. Field Injection (using @Autowired annotation) → Injects dependencies directly into


fields without using setters or constructors.

Ways to Achieve Dependency Injection (DI)


Dependency Injection can be achieved in two ways:

1. Setter Method DI

2. Constructor DI

1. Setter Method Dependency Injection (XML Configuration)


Step 1: Understanding the Classes

We have two classes:

1. Address – Contains house number, city, and pincode.

2. Student – Contains roll number, name, and an Address object.

Class 1: Address (Dependent Bean)

This class has three fields: houseno, city, and pincode. It has setter methods for each field.

What happens here?

• Address is a dependent class that contains three fields.

• Setter methods are used to set values for houseno, city, and pincode.

• toString() is overridden to print the address.

Class 2: Student (Main Bean)

The Student class contains:

• Basic details: rollno, name

• An Address object (which will be injected via setter injection).


What happens here?

• setRollno(), setName(), and setAddress() are setter methods that Spring will use to
inject values.

• display() prints the student details, including the injected Address object.

Step 2: XML Configuration (beans.xml)

This XML file creates and configures beans.

What happens here?

1. addrId bean is created for Address and assigned values.

2. stdId bean is created for Student and assigned rollno and name.
3. Setter Injection is used:

o <property name="address" ref="addrId"/> injects the Address bean into


Student.

Step 3: Load Spring Configuration and Run the Application

Now, we load beans.xml using the Spring container and fetch the Student bean.

What happens when we run this?


1.Spring reads beans.xml and creates beans.
2.It calls setter methods and injects values.
3.display() prints the student details:

ow This Example Works Theoretically?

1⃣ Object Creation in Spring Container

• The Spring container (ApplicationContext) reads the beans.xml configuration file.

• It creates objects (beans) automatically based on the <bean> definitions in the XML
file.

2⃣ Creating and Injecting Dependencies

• Spring first creates the Address bean (addrId) and sets the values:

o houseno = 111

o city = Chandigarh

o pincode = 123456

• Then, Spring creates the Student bean (stdId) and injects:

o rollno = 101

o name = Deepak
o address = addrId (This is dependency injection!)

3⃣ Calling Setter Methods for Injection

Spring calls setter methods while creating objects:

1. For Address bean (addrId):

o setHouseno(111) → Sets house number

o setCity("Chandigarh") → Sets city

o setPincode(123456) → Sets pincode

2. For Student bean (stdId):

o setRollno(101) → Sets roll number

o setName("Deepak") → Sets name

o setAddress(Address object) → Injects Address dependency

4⃣ Getting the Bean and Using It

• In Main.java, we get the Student object from the Spring container:

2. Constructor-Based Dependency Injection (XML Configuration)


What is Constructor-Based Dependency Injection?

• Constructor Dependency Injection (DI) is a method in which Spring injects


dependencies into a class using its constructor.

• This means that when the Spring container creates the object, it passes the required
dependencies through the constructor.

How Does Constructor-Based DI Work? (Step by Step Explanation)

Step 1: Define the Address Class

• This class has three private fields: houseno, city, and pincode.

• Instead of setter methods, it has a constructor to initialize these fields.


Step 2: Define the Student Class

• The Student class has three private fields: rollno, name, and address (which is an
Address object).

• The constructor receives all values, including the Address object.

Step 3: Configure beans.xml for Constructor Injection

• In XML, we use <constructor-arg> instead of <property> to pass values to the


constructor.
Step 4: Load Spring Container and Retrieve Beans

• We need a Main Class to load the Spring container and retrieve the Student object.

3. Setter Method Dependency Injection (Java Configuration)


What is Setter-Based Dependency Injection?

• Setter Dependency Injection (DI) is a method where Spring injects dependencies into
an object using setter methods.

• Spring first creates an object using a default constructor and then calls setter
methods to set values.

How Does Setter-Based DI Work? (Step by Step Explanation)

Step 1:Define the Address Class

• This class has three private fields: houseno, city, and pincode.

• Instead of a constructor, we use setter methods to inject values.

Java Code for Address Class


Step 2:Define the Student Class

• The Student class has three private fields: rollno, name, and address (which is an
Address object).

• Instead of a constructor, we use setter methods to set values.

Step 3:Create Java-Based Configuration Class

• Instead of an XML file, we use Java-based configuration to define Spring beans.

Java Configuration Class


1. Spring scans AppConfig.java and finds the @Configuration class.
2. Spring identifies the @Bean methods and creates objects for Address and Student.
3. The addressBean() method executes first, creating an Address object.
4. The studentBean() method executes next, creating a Student object and injecting the
Address bean into it.
5. When we request the Student bean from the Spring container, we get a fully
configured object with its dependencies injected.

Step 4:Load Spring Container and Retrieve Beans

• We need a Main Class to load the Spring container and retrieve the Student object.

4. Constructor Dependency Injection (Java Configuration)


Step 1: Address Class (Address.java)
✔ Defines the Address class with a constructor to accept values.
✔ Does not have setter methods because we are using constructor injection.

Step 2:Student Class (Student.java)

✔ Defines the Student class with a constructor to accept rollno, name, and Address.
✔ Does not have setter methods because values are set through the constructor.
✔ display() method prints student details.

Step 3:.Java Configuration Class (AppConfig.java)


✔ @Configuration → Marks this class as a Spring configuration.
✔ @Bean methods → Create and manage beans (Address and Student).
✔ Uses constructors instead of setter methods for dependency injection.

Step-by-Step Execution

1⃣ Spring scans AppConfig.java and finds @Configuration and @Bean methods.


2⃣ Spring first executes addressBean(), creating an Address object.
3⃣ Spring then executes studentBean(), passing the Address object into the Student
constructor.
4⃣ When we request the Student bean, Spring returns a fully initialized object with Address
injected.

Step 4:Main Class (MainApp.java) to Test


Which Dependency Injection approach is better: Constructor or
Setter? Why?
• Constructor Injection is preferred when:
The dependency is mandatory.
You want to promote immutability (objects cannot be modified after creation).
It ensures that an object is always fully initialized.

• Setter Injection is preferred when:


The dependency is optional.
You need flexibility (changing dependencies at runtime).
You are dealing with legacy code where setter methods already exist.

Best Practice:
✔ Use Constructor Injection for mandatory dependencies.
✔ Use Setter Injection for optional dependencies.

What happens if a bean has both Constructor and Setter Injection?


• If both Constructor and Setter Injection are used for the same dependency, Spring
prioritizes Constructor Injection.

• The Setter Injection will override the Constructor Injection only if explicitly called.
What happens?

• First, Spring injects the Address dependency via Constructor Injection.

• Then, Spring overwrites it using Setter Injection if both exist.

What Happens Internally?

1. Spring first calls the constructor to inject rollNo and name.

2. Then, it checks if a setter method exists for any additional dependencies (like
Address).

3. If a setter method is present, Spring injects the dependency via that method.

4. Setter Injection can override Constructor Injection if both exist for the same
property.

What is Autowiring?
Autowiring in Spring automatically injects the required object (Bean) into another Bean
without manually creating it using new keyword.

Autowiring म्हणजे एक ऑब्जेक्ट (object) दस


ु ऱ्या ऑब्जेक्टमध्ये आपोआप जोडणे. आपण
Spring Framework मध्ये ऑब्जेक्ट जोडण्यासाठी (Inject करण्यासाठी) autowire हे गुणधर्म
(attribute) वापरतो.
How Does Autowiring Work?

When one Bean depends on another Bean, Spring automatically finds and injects the
required Bean instead of requiring manual configuration.

Example:
If the Student class needs an Address object, Spring will automatically inject the Address
Bean into Student.

Types of Autowiring:

1. @Autowired (Annotation-Based) – The easiest and most commonly used


method
What is @Autowired?

• @Autowired is an annotation in the Spring Framework used for Dependency


Injection (DI).

• It helps automatically inject one Bean into another Bean without manual
configuration.

• Spring automatically finds and injects the required Bean, so we don’t need to create
objects manually.

How Does @Autowired Work? (Step-by-Step Process)

1.Spring loads all Beans (Bean means an object in Spring).


2.Spring looks for @Autowired in fields, constructors, or setter methods.
3.Spring finds a matching Bean and injects it automatically.
4.Once injected, the object is ready for use.

@Autowired म्हणजे काय?

• Spring Framework र्ध्ये @Autowired हे Annotation आहे , जे Dependency Injection


साठी वापरले जाते.
• याचा उपयोग एक Bean दस
ु ऱ्या Bean र्ध्ये आपोआप (automatically) inject
करण्यासाठी केला जातो.

• Spring स्वतःच योग्य Bean शोधतो आणण ती Dependency Inject करतो, त्यार्ुळे
आपल्याला Bean र्ॅन्युअली तयार करण्याची गरज पडत नाही.

@Autowired कसे कार् करते? (Step-by-Step Process)

1.Spring सवम Beans लोड करतो (Bean म्हणजे एक Object)


2.Spring @Autowired असलेल्या Field / Constructor / Setter Method ला शोधतो.
3.Spring त्यासोबत जळ
ु णारा (matching) Bean शोधतो आणण inject करतो.
4.Bean Inject झाल्यावर, तो ऑब्जेक्ट वापरण्यास तयार असतो.

3.Three Ways to Use @Autowired

1) Field Injection (@Autowired directly on a variable)

➡ Here, @Autowired automatically injects the Address Bean into the Student class.
➡ Spring will create an Address object and inject it into Student.

➡ इथे @Autowired ने Address class चे object Student class र्ध्ये inject केले आहे .
➡ Spring Address class चे object तयार करे ल आणण Student र्ध्ये inject करे ल.

2) Constructor Injection (@Autowired on Constructor)


➡ Here, @Autowired is used on the constructor.
➡ Spring injects the Address Bean into the Student class’s constructor.

➡ इथे @Autowired Constructor वर वापरले आहे .


➡ Spring Address class चे object Student class च्या Constructor र्ध्ये inject करे ल.

3) Setter Injection (@Autowired on Setter Method)

What Is @Qualifier Annotation.

@Qualifier is used in Spring to tell the system which object to use when there are multiple
options.

Think of it like this:


Imagine you go to a restaurant and order juice. But there are two types—orange juice and
apple juice. The waiter is confused about which one you want. So, you clearly say "I want
orange juice."
In Spring, when there are multiple beans (objects) of the same type, @Qualifier helps
specify which one to use.

What is @Primary Annotation in Spring?

The @Primary annotation in Spring is used to specify a default bean when multiple beans of
the same type exist. If no specific bean is mentioned using @Qualifier, the bean marked with
@Primary is automatically injected.

How Does @Primary Work?

If multiple beans of the same type are available in the Spring container, and no @Qualifier is
used, then the bean marked with @Primary will be automatically selected.

Rules for Using @Primary

@Primary is only used when @Qualifier is not specified.


If multiple beans of the same type exist, the one marked with @Primary is injected
automatically.
It is applied at the bean declaration level.
2. byType (XML Based) – Injects Bean based on data type

byType is a mode of autowiring in Spring that injects a Bean based on its data type (class
type) instead of its name.

autowire="byType" हे Spring च्या Dependency Injection (DI) र्धील एक प्रकार आहे , जो data
type (class type) वरून Bean inject करतो.

Step-by-Step Working of byType:

1. Spring Container Reads Configuration:

o It scans the XML file to check which Beans are declared.

2. Object Creation:

o Spring first creates objects of all the Beans.

3. Finding a Match by Type:

o If a Bean has a dependency (e.g., Student depends on Address), Spring looks


for another Bean of the same type (Address).
o It does NOT check the Bean ID, only the class type.

4. Injecting the Matching Bean:

o If one matching Bean is found, it is automatically injected into the dependent


Bean.

o If multiple Beans of the same type exist, Spring throws an error (it won’t
know which one to inject).

हे कसे कार् करते? (Step-by-Step)

1. Spring XML फाइल वाचते:

o त्यात ददलेल्या Bean ची र्ादहती घेत.े

2. Spring सवम Beans तयार करते:

o प्रत्येक Bean साठी त्याचा object तयार करते.

3. Spring dependent Bean र्धील property चा data type पाहते:

o जर Student क्लासर्ध्ये Address नावाची property असेल, तर Spring XML र्ध्ये


Address class चा Bean शोधतो.

o इथे Bean चे नाव (ID) पाहत नाही, फक्त त्याचा data type (class) तपासतो.

4. Bean सापडला तर inject करतो:

o जर Address class चा एकच Bean असेल, तर Spring त्याला Student र्ध्ये inject
करतो.

o जर एकाहून अधधक Address Bean असतील, तर Spring गोंधळून जातो आणण


error दे तो.
What is Autowire Candidate? (In Simple Words)

In Spring, @Autowired annotation is used to inject dependencies. To decide which Bean


should be injected, we use autowire-candidate.

What does autowire-candidate="false" mean?

• If we want to exclude a specific Bean from automatic autowiring, we set autowire-


candidate="false".

• This means Spring will not consider this Bean for dependency injection.

How It Works Internally?

1. Spring creates two Address Beans (addr1 and addr2).

2. Since addr1 has autowire-candidate="false", it is NOT considered for autowiring.

3. Spring selects addr2 (Pune) for injection because it is the only valid candidate.

4. When display() is called, Student prints the address.

3. byName (XML Based) – Injects Bean based on its name (ID in XML)

• When autowire="byName" is given, Spring automatically injects the Bean if the Bean
ID and the property name in the class are the same.

• This means that if the Student class has a property named address, Spring will search
for a Bean in the XML configuration with id="address" and inject it into Student.

• autowire="byName" ददल्यास, Spring Bean चा id आणण क्लासर्धील property चे नाव


सारखे असल्यास ते Bean आपोआप Inject होते.
• म्हणजेच, जर Student क्लासर्ध्ये address नावाची property असेल, तर Spring XML र्ध्ये
id="address" असलेल्या Bean ला शोधून ती Student र्ध्ये inject करे ल.
How does this work? (Step-by-Step)

1. Spring Container creates the Student Bean.

2. It checks if there is a property named address in Student.

3. Spring searches for a Bean with id="address" in the XML configuration.

4. If the Bean is found, it is automatically injected into Student.

5. When the display() method is called, it prints the details of both Student and
Address.

हे कसं कार् करतं? (Step-by-Step)

1. Spring Container Student Bean तयार करतो.

2. त्यात address नावाची property आहे का ते पाहतो.

3. Spring XML र्ध्ये id="address" असलेला Bean शोधतो.

4. Bean सापडला तर Student र्ध्ये address आपोआप inject करतो.

5. जेव्हा display() कॉल करतो, तेव्हा Student चे आणण Address चे डडटे ल्स प्प्रंट होतात.

Note:- Internally used the setter method DI


4. constructor (XML Based) – Injects dependency using the constructor

What is Constructor Injection?

• Constructor Injection means injecting dependencies into a class using its constructor.
• In simple terms, when Spring creates an object of a class (Bean), it injects the
required dependencies through the constructor.

• Here, we do not use setter methods; instead, we inject dependencies directly


through the constructor.

How Does Constructor Injection Work? (Step-by-Step Explanation)

1.Spring reads the XML Configuration file and looks for Beans.
2.Spring checks if the Bean requires any dependencies through the constructor.
3.If a Bean requires another Bean as a dependency, Spring looks for it and injects it.
4.Spring uses the given arguments to create the object and injects the required data.
5.After injecting dependencies, the Bean is ready for use.

Constructor Injection म्हणजे काय?

• Constructor Injection म्हणजे Constructor च्या र्दतीने Dependency Injection करणे.

• म्हणजेच, Spring एखाद्या क्लासचे (Bean चे) ऑब्जेक्ट तयार करताना त्याच्या
Constructor र्ध्ये आवश्यक डेटा आणण अन्य Beans inject करते.

• यार्ध्ये setter method चा वापर होत नाही, फक्त Constructor च्या र्दतीने
Dependency Injection होते.

Constructor Injection कसे कार् करते? (Step-by-Step सर्जावून घ्या)

1.Spring XML Configuration वाचतो आणण Beans शोधतो.


2.Spring प्रत्येक Bean साठी Constructor पाहतो आणण त्याला लागणाऱ्या dependencies
शोधतो.
3.जर एखाद्या Bean च्या Constructor ला दस
ु ऱ्या Bean ची गरज असेल, तर Spring त्याला
inject करतो.
4. Spring योग्य arguments चा वापर करून object तयार करतो आणण inject केलेले data
वापरण्यास तयार होते.
Constructor Injection का वापरावा?

• जर एखाद्या Object साठी dependency आवश्यक असेल आणण ती नंतर बदलायची


नसेल, तर Constructor Injection सवोत्तर् आहे .

• उदाहरणाथम, जर Student साठी Address आवश्यक असेल आणण तो नंतर बदलायचा


नसेल, तर Constructor Injection चांगला पयामय आहे .

Why Should You Use Constructor Injection?

• If an object requires mandatory dependencies at the time of creation and those


dependencies should not change later, Constructor Injection is the best choice.

• For example, if a Student must always have an Address, and it should not be
modified later, Constructor Injection is a good option.

What is Maven? (Simple Explanation)

• Maven is a build automation tool used for Java projects.

• It helps manage dependencies, build projects, and automate tasks like compiling,
testing, and packaging Java applications.

• It makes project setup easy by handling libraries and configurations automatically.


How Does Maven Work? (Step-by-Step Process)

1.Maven Reads the pom.xml File

• The pom.xml (Project Object Model) file contains project details, dependencies, and
build configurations.

• It tells Maven what libraries (dependencies) are needed and how to build the project.

• pom.xml (Project Object Model) is the main configuration file in a Maven project.

• It defines project details, dependencies, plugins, and build settings.

• Maven reads this file to download dependencies and automate the build process.

Key Elements in pom.xml

1⃣ groupId → Project’s unique identifier (e.g., company or project name)


2⃣ artifactId → Name of the JAR/WAR file when built
3⃣ version → Project version (e.g., 1.0-SNAPSHOT)
4⃣ dependencies → List of required libraries (Maven downloads them automatically)

2.Maven Downloads Dependencies

• Instead of manually downloading JAR files, Maven automatically fetches


dependencies from an online repository (Maven Central).

• If a dependency is not available locally, Maven downloads it once and stores it for
future use.

3.Maven Follows a Build Lifecycle

• Maven builds the project step by step:

o Compile → Converts Java files to bytecode.


o Test → Runs unit tests.

o Package → Creates a JAR or WAR file.

o Install → Saves the built project in the local repository.

o Deploy → Uploads the project to a remote server.

Advantages of Maven

Manages Dependencies Automatically (No need to download JARs manually)


Follows a Standard Project Structure (Easy collaboration)
Automates Build Process (Compiling, testing, and packaging)
Works with Many Java Frameworks (Spring, Hibernate, etc.)
Supports Plugins (For testing, deployment, and documentation)

What is Spring JDBC?


Spring JDBC is a tool in the Spring Framework that helps us work with databases easily. It
removes the extra code we need to write when using plain JDBC.

Difference Between Spring JDBC and Plain JDBC

You might also like