What Is Spring
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.
3. Spring Boot – Simplifies Spring projects (no need for complex configurations).
Example: Instead of writing long Java code to connect to a database, Spring does it for you in
just a few lines!
Example:
Imagine you own a restaurant. The Spring Container is like the kitchen manager who:
The Spring Container is responsible for managing the entire lifecycle of objects (beans) in a
Spring application. Here are its main responsibilities:
• 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.
• 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.
• Helps with features like logging, security, and transaction management without
modifying main code.
7. Managing Transactions
• Application.context.XML-Standard name.
• Spring Configuration File.
• Provide Instruction for Spring Container.
2. It finds bean definitions that specify which classes should be instantiated as beans.
4. Beans are stored in the ApplicationContext and can be retrieved whenever needed.
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
3.spring-context.jar
Allows using Spring Expression Language (SpEL) for dynamic values in beans.
Helps in setting properties dynamically inside XML files.
5.commons-logging.jar
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).
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"
Once we have the XML schema, we create the configuration file and define beans inside it.
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
What is a POJO?
A Java Configuration Class is a regular Java class that uses Spring annotations to define
bean objects instead of XML.
1. @Configuration
2. @Bean
Key Points:
Note: you can set a value (inject data) into a bean using @Bean and a setter method.
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
• 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.
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
• @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.
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.
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.
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.
• Unlike singleton, prototype beans are not managed after creation (i.e., Spring does
not destroy them).
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.
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.
• This ensures that the beans are ready to use but can slow down application startup.
• 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.
You can use @Lazy annotation at the class level or bean level to enable lazy initialization.
1⃣ What is happening?
• After loading the bean definitions, Spring creates objects of the beans.
• If a constructor with parameters is present, Spring will use it (if dependencies are
available).
1⃣ What is happening?
• After the bean object is created, Spring initializes it by setting its properties.
1⃣ What is happening?
1⃣ What is happening?
• When the application closes, Spring removes the bean from memory.
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.
1. Setter Method DI
2. Constructor DI
This class has three fields: houseno, city, and pincode. It has setter methods for each field.
• Setter methods are used to set values for houseno, city, and pincode.
• setRollno(), setName(), and setAddress() are setter methods that Spring will use to
inject values.
• display() prints the student details, including the injected Address object.
2. stdId bean is created for Student and assigned rollno and name.
3. Setter Injection is used:
Now, we load beans.xml using the Spring container and fetch the Student bean.
• It creates objects (beans) automatically based on the <bean> definitions in the XML
file.
• Spring first creates the Address bean (addrId) and sets the values:
o houseno = 111
o city = Chandigarh
o pincode = 123456
o rollno = 101
o name = Deepak
o address = addrId (This is dependency injection!)
• This means that when the Spring container creates the object, it passes the required
dependencies through the constructor.
• This class has three private fields: houseno, city, and pincode.
• The Student class has three private fields: rollno, name, and address (which is an
Address object).
• We need a Main Class to load the Spring container and retrieve the Student object.
• 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.
• This class has three private fields: houseno, city, and pincode.
• The Student class has three private fields: rollno, name, and address (which is an
Address object).
• We need a Main Class to load the Spring container and retrieve the Student object.
✔ 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-by-Step Execution
Best Practice:
✔ Use Constructor Injection for mandatory dependencies.
✔ Use Setter Injection for optional dependencies.
• The Setter Injection will override the Constructor Injection only if explicitly called.
What happens?
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.
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:
• 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.
• Spring स्वतःच योग्य Bean शोधतो आणण ती Dependency Inject करतो, त्यार्ुळे
आपल्याला Bean र्ॅन्युअली तयार करण्याची गरज पडत नाही.
➡ 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 करे ल.
@Qualifier is used in Spring to tell the system which object to use when there are multiple
options.
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.
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.
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 करतो.
2. Object Creation:
o If multiple Beans of the same type exist, Spring throws an error (it won’t
know which one to inject).
o इथे Bean चे नाव (ID) पाहत नाही, फक्त त्याचा data type (class) तपासतो.
o जर Address class चा एकच Bean असेल, तर Spring त्याला Student र्ध्ये inject
करतो.
• This means Spring will not consider this Bean for dependency injection.
3. Spring selects addr2 (Pune) for injection because it is the only valid candidate.
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.
5. When the display() method is called, it prints the details of both Student and
Address.
5. जेव्हा display() कॉल करतो, तेव्हा Student चे आणण Address चे डडटे ल्स प्प्रंट होतात.
• 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.
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.
• म्हणजेच, Spring एखाद्या क्लासचे (Bean चे) ऑब्जेक्ट तयार करताना त्याच्या
Constructor र्ध्ये आवश्यक डेटा आणण अन्य Beans inject करते.
• यार्ध्ये setter method चा वापर होत नाही, फक्त Constructor च्या र्दतीने
Dependency Injection होते.
• For example, if a Student must always have an Address, and it should not be
modified later, Constructor Injection is a good option.
• It helps manage dependencies, build projects, and automate tasks like compiling,
testing, and packaging Java applications.
• 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.
• Maven reads this file to download dependencies and automate the build process.
• If a dependency is not available locally, Maven downloads it once and stores it for
future use.
Advantages of Maven