100% found this document useful (1 vote)
3K views

Spring by Durgesh

The document discusses Spring Framework concepts including dependency injection, inversion of control, and the Spring core module. It explains that dependency injection connects objects by injecting dependencies rather than having objects create their own dependencies. The Spring container manages object lifecycles and handles dependency injection through configuration metadata. Dependencies can be injected via constructors or setters.

Uploaded by

Lalit
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
3K views

Spring by Durgesh

The document discusses Spring Framework concepts including dependency injection, inversion of control, and the Spring core module. It explains that dependency injection connects objects by injecting dependencies rather than having objects create their own dependencies. The Spring container manages object lifecycles and handles dependency injection through configuration metadata. Dependencies can be injected via constructors or setters.

Uploaded by

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

Spring

What is Spring Framework | Dependency


Injection | Inversion of Control | Spring
Core Module
What Is Dependency Injection?

 Dependency injection is a pattern we can use to implement IoC, where the control being
inverted is setting an object's dependencies.
 Connecting objects with other objects, or “injecting” objects into other objects, is done by an
assembler rather than by the objects themselves.

 Here Geeta object is dependent on Ramu object. So we don't required to create Geeta object.
We give control to spring to create object of Geeta and spring inject Geeta object into Ramu
Object. This process called Inversion of Control (IOC).
What Is Inversion of Control?
Inversion of Control is a principle in software engineering which transfers
the control of objects or portions of a program to a container or framework.
We most often use it in the context of object-oriented programming.

In contrast with traditional programming, in which our custom code makes


calls to a library, IoC enables a framework to take control of the flow of a
program and make calls to our custom code. To enable this, frameworks use
abstractions with additional behavior built in. If we want to add our own
behavior, we need to extend the classes of the framework or plugin our own
classes.

The advantages of this architecture are:

 decoupling the execution of a task from its implementation

 making it easier to switch between different implementations

 greater modularity of a program

 greater ease in testing a program by isolating a component or mocking


its dependencies, and allowing components to communicate through
contracts

We can achieve Inversion of Control through various mechanisms such as:


Strategy design pattern, Service Locator pattern, Factory pattern, and
Dependency Injection (DI).

 We used to create DAO layer in jdbc to connect with database where we create every object
with new keyword. In DAO layer we create methods with database queries and in
Business/service layer we write logical code and create DAO object in business layer with new
keyword which is tight coupling . If we change DAO layer then we have to change all in business
layer. So we don't recommend to create object with new keyword, that's why we used spring to
create automatic object. Which inject one object into another object by xml file or by
annotation.
Overview of Spring Framework Modules | Spring
Core | Spring Data Integration | Spring Web

 Core and beans for object dependency injection.


 Context for spring container and dependency injection.
 Context extend beans. It take dependency injection from beans.
 Spring jdbc for connectivity with databse.
 Spring ORM for hibernate ORM and others tools.
 Spring OXM for xml configuration .
 Web module for Rest api.

The Spring IoC Container

 An IoC container is a common characteristic of frameworks that


implement IoC.
 In the Spring framework, the interface ApplicationContext represents
the IoC container. The Spring container is responsible for
instantiating, configuring and assembling objects known as beans, as
well as managing their life cycles.
 Spring container responsible for object creation and hold the objects
in memory and inject one object into another object as required.
 It work as Garbage collector. It maintain life cycle of object from
object creation to destroy object. We don't require to do anything.
 We have to tell only two things to spring container one is bean means
which beans/POJO classes we will use and second is which bean is
dependent on which beans and set those classes in Xml configuration
file.
 Main application get objects from spring container and then it can use.

 The Spring framework provides several implementations of


the ApplicationContext interface: ClassPathXmlApplicationContext and 
 FileSystemXmlApplicationContext for standalone applications,
and WebApplicationContext for web applications.
 In order to assemble beans, the container uses configuration metadata,
which can be in the form of XML configuration or annotations.

Application context:
 It is an interface represents spring IOC container.
 It extends beanFactory.
 It has its own properties and beanFactory properties.
 We can access all values of object present in spring container with the
help of Application Context. But it is an interface so we have to make
a class which implements Application Context interface.
 So we have three classes for access data which implement Application
Context interface.
1. ClassPathXmlApplicationContext – this class search xml
configuration in java class path.
2. FileSystemXmlApplicationContext – this class search xml
configuration from file.
3. AnnotationConfigApplicationContext – this class search those
beans on which we used annotation.

The ApplicationContext Interface

One of the main features of the Spring framework is the IoC (Inversion of
Control) container. The Spring IoC container is responsible for managing the
objects of an application. It uses dependency injection to achieve inversion
of control.
The interfaces BeanFactory and ApplicationContext represent the Spring IoC
container. Here, BeanFactory is the root interface for accessing the Spring
container. It provides basic functionalities for managing beans.
On the other hand, the ApplicationContext is a sub-interface of
the BeanFactory. Therefore, it offers all the functionalities of BeanFactory.
Furthermore, it provides more enterprise-specific functionalities. The
important features of ApplicationContext are resolving messages, supporting
internationalization, publishing events, and application-layer specific
contexts. This is why we use it as the default Spring container.

What Is a Spring Bean?


Before we dive deeper into the ApplicationContext container, it's important
to know about Spring beans. In Spring, a bean is an object that the Spring
container instantiates, assembles, and manages.

So should we configure all of the objects of our application as Spring beans?


Well, as a best practice, we shouldn't.

As per Spring documentation in general, we should define beans for service


layer objects, data access objects (DAOs), presentation objects,
infrastructure objects such as Hibernate SessionFactories, JMS Queues, and so
forth.

Also, typically, we shouldn't configure fine-grained domain objects in the


container. It's usually the responsibility of DAOs and business logic to
create and load domain objects.
Ways of Injecting dependencies | Types of
dependencies handled by IOC Container
 Spring container create one object and inject it into another object
automatically at Runtime. All injection happen at Runtime.
 Spring container responsible for to put values of object into another
object.

Despondency injection can be done in two ways:


1. Setter injection/property injection (setter methods)
2. Constructor injection
Setter-Based Dependency Injection:

For setter-based DI, the container will call setter methods of our
class after invoking a no-argument constructor or no-argument static factory
method to instantiate the bean. Let's create this configuration using
annotations:
Constructor-Based Dependency Injection
In the case of constructor-based dependency injection, the container will
invoke a constructor with arguments each representing a dependency we want to
set.

Spring resolves each argument primarily by type, followed by name of the


attribute, and index for disambiguation. Let's see the configuration of a
bean and its dependencies using annotations:
 The @Configuration annotation indicates that the class is a source of
bean definitions. We can also add it to multiple configuration classes.

 We use the @Bean annotation on a method to define a bean. If we don't


specify a custom name, then the bean name will default to the method
name.

 For a bean with the default singleton scope, Spring first checks if a


cached instance of the bean already exists, and only creates a new one
if it doesn't. If we're using the prototype scope, the container
returns a new bean instance for each method call.

 Another way to create the configuration of the beans is through XML


configuration:

 We can combine constructor-based and setter-based types of injection


for the same bean. The Spring documentation recommends using
constructor-based injection for mandatory dependencies, and setter-
based injection for optional ones.
New Maven Project | Adding Spring Dependencies |
Create Config File | Setter Injection
Bean class/Pojo class:

package com.spring.MavenProjectSpring.beans;

public class Student {


private int studentId;
private String studentName;
private String studentAddress;

public Student(int id, String name, String address) {


super();
this.studentId = id;
this.studentName = name;
this.studentAddress = address;
}

public Student() {
super();
// TODO Auto-generated constructor stub
}

public int getId() {


return studentId;
}

public void setId(int id) {


this.studentId = id;
}

public String getName() {


return studentName;
}

public void setName(String name) {


this.studentName = name;
}

public String getAddress() {


return studentAddress;
}

public void setAddress(String address) {


this.studentAddress = address;
}

@Override
public String toString() {
return "Student [id=" + studentId + ", name=" + studentName + ", address=" + studentAddress + "]";
}

}
Spring.config.xml file:

 We declare bean in configuration xml file.


 If we are setting field/bean class using <property> tag in <bean> tag
that means we are using setter dependency injection. In <value> tag we
add class properties values. In <property> tag name should be same as
class properties name.

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


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<bean class="com.spring.MavenProjectSpring.beans.Student" name="student1">


<property name="studentId">
<value>121</value>
</property>

<property name="studentNmae">
<value>Lalit</value>
</property>

<property name="studentAddress">
<value>Panipat</value>
</property>

</bean>

</beans>

In this file we can change properties values any time.

This is the way add primitive data types properties.

Main application file (main method):

package com.spring.MavenProjectSpring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.MavenProjectSpring.Student;

public class App {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.config.xml");
System.out.println("Hello world");

Object bean = context.getBean("student1");


Student s1 = (Student)bean;
System.out.println(s1);
}
}
 We pull out student object from spring container using context. We get
student object by getBean() method and we have to put that name in
getBean() method which we mention in <bean> tag. getBean() method
return object and we have to do type casting.

Property injection using p Schema and


using value as attribute

Set properties values using value attribute:


 We can use <value> tag as value attribute in <property> tag and in that
value attribute we can put properties values.
 We can <property> tag as self closing tag <property name="" value="" />

Spring.config.xml file:

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


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<!-- 1st bean -->


<bean class="com.spring.MavenProjectSpring.Student" name="student1">
<property name="studentId" value="121"/>

<property name="studentNmae" value="Lalit"/>

<property name="studentAddress" value="Panipat"/>


<!-- 2nd bean -->
</bean>

<bean class="com.spring.MavenProjectSpring.Student" name="student2">


<property name="studentId" value="122"/>

<property name="studentNmae" value="Amit"/>

<property name="studentAddress" value="Delhi"/>

</bean>

</beans>

Main application file:

package com.spring.MavenProjectSpring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.MavenProjectSpring.Student;

public class App {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.config.xml");
System.out.println("Hello world");

Object bean = context.getBean("student1");


Student s1 = (Student)bean;
Student s2 = (Student)context.getBean("Student2");
System.out.println(s1);
System.out.println(s2);
}
}
 Every time we have to use getBean() method to get bean from the spring
container via context.

Set properties values using value p-schema:


 1st declared p-schema in config.xml file.
 Remove all <property> tag present in <bean> tag.
 Use self closing tag of <bean> tag as <bean/>.

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


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<!-- 1st bean -->


<bean class="com.spring.MavenProjectSpring.Student" name="student1" p:studenID="121"
p:studentName="Lalit" p:studentAddress="Panipat"/>
<!-- 2nd bean -->

<bean class="com.spring.MavenProjectSpring.Student" name="student2" p:studenID="122" p:studentName="Amit"


p:studentAddress="Delhi"/>

</beans>

How to inject collection types List , Set ,


Map and Properties 
Collection.config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<bean class="com.sprin.core.collections.Employee" name="emp1">


<property name="name" value="lalit" />
<property name="phones">
<list>
<value>123456</value>
<value>344432</value>
<value>1234446356</value>
</list>
</property>

<property name="addresses">
<set>
<value>Panipat</value>
<value>Delhi</value>
<value>Mumbai</value>
</set>
</property>

<property name="courses">
<map>
<entry key="java" value="2 months"/>
<entry key="python" value="6 months"/>
<entry key="Spring" value="3months"/>
</map>
</property>

</bean>
</beans>

Employee bean/pojo file:


package com.sprin.core.collections;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class Employee {


private String name;
private List<String> phones;
private Set<String> addresses;
private Map<String, String> courses;

public Employee(String name, List<String> phones, Set<String> addresses, Map<String, String> courses) {
super();
this.name = name;
this.phones = phones;
this.addresses = addresses;
this.courses = courses;
}
public Employee() {
super();
// TODO Auto-generated constructor stub
}

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPhones() {
return phones;
}
public void setPhones(List<String> phones) {
this.phones = phones;
}
public Set<String> getAddresses() {
return addresses;
}
public void setAddresses(Set<String> addresses) {
this.addresses = addresses;
}
public Map<String, String> getCourses() {
return courses;
}
public void setCourses(Map<String, String> courses) {
this.courses = courses;
}

Main application file:


package com.sprin.core.collections;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {


public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("com/sprin/core/collections/collection.config.xml");

Employee emp1 = (Employee) context.getBean("emp1");

System.out.println(emp1.getName());
System.out.println(emp1.getPhones());
System.out.println(emp1.getAddresses());
System.out.println(emp1.getCourses());
}
}

Injecting Reference Type


reference.config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<bean class="com.spring.core.reference.B" name="bRef">

<property name="y" value="10"/>

</bean>

<bean class="com.spring.core.reference.A" name="aRef" p:x="20" p:b-ref="bRef"/>

<!-- <bean class="com.spring.core.reference.A" name="aRef">

<property name="x" value="20"/>

<property name="b"> <ref bean="bRef"/> </property>

<property name="b" ref="bRef"/>

</bean> -->

</beans>
A bean/pojo file:
package com.spring.core.reference;

public class A {
private int x;
private B b;

public A(int x, B b) {
super();
this.x = x;
this.b = b;
}

public A() {
super();
// TODO Auto-generated constructor stub
}

public int getX() {


return x;
}

public void setX(int x) {


this.x = x;
}

public B getB() {
return b;
}

public void setB(B b) {


this.b = b;
}

@Override
public String toString() {
return "A [x=" + x + ", b=" + b + "]";
}

B bean/pojo file: depend on A


package com.spring.core.reference;

public class B {
private int y;

public B(int y) {
super();
this.y = y;
}

public B() {
super();
// TODO Auto-generated constructor stub
}

public int getY() {


return y;
}

public void setY(int y) {


this.y = y;
}

@Override
public String toString() {
return "B [y=" + y + "]";
}

Main application file:

package com.spring.core.reference;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public static void main(String[] args) {


ApplicationContext context = new ClassPathXmlApplicationContext
("com/spring/core/reference/ref.config.xml");
A a = (A)context.getBean("aRef");
System.out.println(a); // we get A object
System.out.println(a.getX()); // we get x property of A object
System.out.println(a.getB()); // we get B object which is property of A object
System.out.println(a.getB().getY()); //we get y property of B object.

}
Constructor Injection:

1. Use <constructor-args> tag in <bean> tag to call constructor of bean.


2. One <constructor-args> tag means one property call.

Constructor.config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xmlns:c="https://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<!-- using c schema -->


<bean class="com.spring.constructor.injection.Certificate" name="certificate1" c:certiId="1"
c:certificate="puthon"/>
<bean class="com.spring.constructor.injection.Person" name="person1" c:id="111" c:name="Lalit"
c:certificate-ref="certificate1"/>

<!-- using attribute values -->


<!-- <bean class="com.spring.constructor.injection.Certificate" name="certificate1">

<constructor-arg value="1" type="int"/>


<constructor-arg value="Java" type="String"/>
</bean>

<bean class="com.spring.constructor.injection.Person" name="person1">

<constructor-arg value="111" type="int"/>


<constructor-arg value="Lalit" type="String"/>
<constructor-arg ref="certificate1"></constructor-arg>

<constructor-arg>
<value>"111"</value>
</constructor-arg>

<constructor-arg>
<value>"Lalit"</value>
</constructor-arg>

</bean> -->
</beans>

Person bean/pojo file:


package com.spring.constructor.injection;

public class Person {


private int id;
private String name;
private Certificate certificate;

public Person(int id, String name, Certificate certificate) {


super();
this.id = id;
this.name = name;
this.certificate = certificate;
}

@Override
public String toString() {
return this.name + ":" + this.id + ":" + this.certificate;
}

}
Certificate bean/pojo file:
package com.spring.constructor.injection;

public class Certificate {


private int certiId;
private String certificate;

public Certificate(int certiId, String certificate) {


super();
this.certiId = certiId;
this.certificate = certificate;
}

@Override
public String toString() {
return " " + this.certificate;
}

Main application file:S


package com.spring.constructor.injection;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public static void main(String[] args) {


ApplicationContext context = new ClassPathXmlApplicationContext(
"com/spring/constructor/injection/constructor.config.xml");
Person p1 = (Person) context.getBean("person1");
System.out.println(p1); // we will get person object.
}

}
Ambiguity Problem and its Solution with Constructor
Injection
 In <constructor-args> tag every property treated as String. If in
corresponding class has String arguments constructor that constructor
called by spring. If not String arguments constructor then 1st top
contstructor will be called by spring.
 If we want a specific constructor will call by spring then we have to
put 'type' attribute in <constructor-args> tag.

<constructor-arg value="111" type="int"/>

<constructor-arg value="Lalit" type="String"/>

 We can change order of arguments by using 'index' attribute

<constructor-arg value="111" type="int" index="1"/>

<constructor-arg value="Lalit" type="String" index="0"/>


Life Cycle methods of Spring Bean
Implementing Lifecycle methods Using XML
 Spring 1st create object then setting all properties inside the the
object.
 After that spring call init() method to initialize the object.
 After all process at end spring call destroy method.
 We have to create AbstractApplicationContext object which is a abstract
class of ConfigurableApplicationContext interface contains
shutDownHook() method which call destroy method.
 We can change method name of init() and destroy().
 We have to configure the init-method="name of Init() method present in
bean class" and destroy-method=" name of destroy() method present in
bean class "

Configuration.xml file:

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


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<bean class="com.springCore.lifeCycle.Samosa" name="samosa" init-method="init" destroy-method="destroy">


<property name="price" value="10"/>

</bean>
</beans>

Bean/pojo class:
package com.springCore.lifeCycle;

public class Samosa {


private double price;

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
System.out.println("Setting property");
}

public Samosa() {
super();
// TODO Auto-generated constructor stub
}

@Override
public String toString() {
return " " + price;
}

public void init() {


System.out.println("Inside init()");
}
public void destroy() {
System.out.println("Inside destroy()");
}

Main application class:


package com.springCore.lifeCycle;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {


public static void main(String[] args) {
AbstractApplicationContext context = new
ClassPathXmlApplicationContext("com/springCore/lifeCycle/config.xml");
Samosa s = (Samosa) context.getBean("samosa");
System.out.println(s);

// registering shutdown hook method which call destroy method


context.registerShutdownHook();

}
}

Implementing bean life cycle using interfaces |


IntializingBean | DisposableBean
1. IntializingBean is an interface which provide functionality of
initializing the bean.
2. DesposableBean is an interface which provide functionality of destroy
the bean.
3. We have to implement IntializingBean interface in bean class and add
unimplemented method in the bean class which 'afterSetProperties()'
method ( it works as init() method which was providing functionality
after set properties in the object).
4. We have to implement DesposableBean interface in bean class and add
unimplemented method in the bean class which 'destroy()' method.
5. We have to call shutDownHook() method on context object for destroying
object.

Bean/pojo class:
package com.springCore.lifeCycle;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class Pepsi implements InitializingBean, DisposableBean {


private int price;

public int getPrice() {


return price;
}

public void setPrice(int price) {


this.price = price;
}

public Pepsi() {
super();
// TODO Auto-generated constructor stub
}

@Override
public String toString() {
return "Pepsi [price=" + price + "]";
}

public void afterPropertiesSet() throws Exception {


System.out.println("taking pepsi- intializing bean");
System.out.println("afterSetProperties() method works as init() method");
}

public void destroy() throws Exception {


System.out.println("destroying bean");

Config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<bean class="com.springCore.lifeCycle.Pepsi" name="pepsi">
<property name="price" value="90" />
</bean>
</beans>

Main application file:


package com.springCore.lifeCycle;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {


public static void main(String[] args) {
AbstractApplicationContext context = new
ClassPathXmlApplicationContext("com/springCore/lifeCycle/config.xml");
Pepsi p = (Pepsi) context.getBean("pepsi");
System.out.println(p);

// registering shutdown hook method which call destroy method


context.registerShutdownHook();

}
}

Implementing Bean LifeCyle using Annotations |


@PostConstruct | @PreDestroy

1. @PostConstruct: this annotation which provide functionality of


init() method initializing the bean. Spring calls the methods
annotated with @PostConstruct only once, just after the
initialization of bean properties. Keep in mind that these methods
will run even if there's nothing to initialize.

The method annotated with @PostConstruct can have any access level,


but it can't be static.

2. @PreDestroy: this annotation which provide functionality of


destroy() method of the bean.

A method annotated with @PreDestroy runs only once, just before


Spring removes our bean from the application context. The purpose of
this method should be to release resources or perform other cleanup
tasks, such as closing a database connection, before the bean gets
destroyed.

Note that both the @PostConstruct and @PreDestroy annotations are


part of Java EE. Since Java EE was deprecated in Java 9, and removed
in Java 11, we have to add an additional dependency to use these
annotations:

<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>

3. If we are using java version 8 then we can use @PostConstruct and


@PreDestroy annotation directly on the methods. But if we are using
from java 9 onwards then we have to add dependency in pom.xml file
and then we can write these annotation on methods.
4. These annotations are disabled by default, so we have to enable them
in configuration file by <bean
class="org.springframework.context.annotation.CommonAnnotation
BeanPostProcessor"/>.
Bean/pojo class:
package com.springCore.lifeCycle;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Example {


private String example;

public String getExample() {


return example;
}

public void setExample(String example) {


this.example = example;
}

public Example() {
super();
// TODO Auto-generated constructor stub
}

@Override
public String toString() {
return "Example [example=" + example + "]";
}

@PostConstruct
public void start() {
System.out.println("this method works as init() method");
}

@PreDestroy
public void end() {
System.out.println("this method works as destroy() method");
}
}

Config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>

<bean class="com.springCore.lifeCycle.Example" name="example">


<property name="example" value="This a example of Chemistry" />
</bean>

</beans>

Main application file:


package com.springCore.lifeCycle;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {


public static void main(String[] args) {
AbstractApplicationContext context = new
ClassPathXmlApplicationContext("com/springCore/lifeCycle/config.xml");
Example ex = (Example) context.getBean("example");
System.out.println(ex);

// registering shutdown hook method which call destroy method


context.registerShutdownHook();

}
}

Autowiring in Spring Framework


Autowiring using XML complete Session | byName
| byType | byConstructor
 byname: we have to put one bean name (in config.xml) and another bean's
property object's reference name put same on configuration file.
 If we write autowire:"byName" in <bean> tag then spring will check that
bean name of the dependent object and in main object spring will check
dependent object reference name and then spring will check name of bean
of dependent object in bean tag is matched or not.

If it is matched then we will get object information otherwise we will get


error.

Bean/pojo class:
Employee class:
package com.spring.core.autowire;

public class Employee {

private Address address;

public Address getAddress() {


return address;
}
public void setAddress(Address address) {
this.address = address;
}

public Employee() {
super();
// TODO Auto-generated constructor stub
}

public Employee(Address address) {


super();
this.address = address;
}

@Override
public String toString() {
return "Employee [address=" + address + "]";
}

Address class:
package com.spring.core.autowire;

public class Address {


private String street;
public String getStreet() {
return street;
}

public void setStreet(String street) {


this.street = street;
}

private String address;

public String getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}

@Override
public String toString() {
return "Address [street=" + street + ", address=" + address + "]";
}

configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<bean class="com.spring.core.autowire.Address" name="address">


<property name="address" value="Panipat"/>
<property name="street" value="56"/>
</bean>

<bean class="com.spring.core.autowire.Employee" name="emp" autowire="byName"/>


</beans>

byType:

 If we write autwire="byType" in <bean> tag then spring will check in


that corresponding bean only type of bean i.e object.
 We can write different name of dependent object in <bean> tag from
object reference in main object.

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


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<bean class="com.spring.core.autowire.Address" name="address1">


<property name="address" value="Panipat"/>
<property name="street" value="56"/>
</bean>

<bean class="com.spring.core.autowire.Employee" name="emp" autowire="byType"/>


</beans>

There could be multiple bean with same type. So we use autowire:"byName"

Constructor:

 If we write autowire="constructor" then spring will call directly


constructor of that bean.

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


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="
https://www.springframework.org/schema/context"
xmlns:p="https://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<bean class="com.spring.core.autowire.Address" name="address1">


<property name="address" value="Panipat"/>
<property name="street" value="56"/>
</bean>

<bean class="com.spring.core.autowire.Address" name="address2">


<property name="address" value="Delhi"/>
<property name="street" value="100"/>
</bean>

<bean class="com.spring.core.autowire.Employee" name="emp" autowire="constructor"/>


</beans>

package com.spring.core.autowire;

public class Employee {

private Address address1;

private Address address2;

public Address getAddress() {


return address1;
}

public void setAddress(Address address) {


this.address1 = address;
}

public Address getAddress2() {


return address2;
}

public void setAddress2(Address address2) {


this.address2 = address2;
}

public Employee() {
super();
// TODO Auto-generated constructor stub
}

public Employee(Address address1, Address address2) {


super();
this.address1 = address1;
this.address2 = address2;
}

@Override
public String toString() {
return "Employee [address1=" + address1 + ", address2=" + address2 + "]";
}

}
@Autowired Annotation for Autowiring  
 We have to enable @Autowire annotation in configuration file.

 Annotation-Based Configuration

 We can use @Autowire annotation on property, setter method and constructor.


 If we use annotation on property then spring will inject that object in another object.
 If we use annotation setter method then spring will call setter method directly.
 If we use annotation then spring will execute constructor directly.

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


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<context:annotation-config/>

<bean class="com.spring.core.autowire.annotation.Address1" name="address">


<property name="address" value="Panipat"/>
<property name="street" value="56"/>
</bean>

<bean class="com.spring.core.autowire.annotation.Employee1" name="emp" autowire="constructor"/>


</beans>
@Qualifier Annotation with Autowiring
By using the @Qualifier annotation, we can eliminate the issue of which bean needs to be injected.
Let's revisit our previous example to see how we solve the problem by including
the @Qualifier annotation to indicate which bean we want to use:

By including the @Qualifier annotation, together with the name of the specific implementation we


want to use, we can avoid ambiguity when Spring finds multiple beans of the same type.

Bean class:
package com.spring.core.autowire.annotation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Employee1 {

@Autowired
@Qualifier("address2")
private Address1 address;

public Address1 getAddress() {


return address;
}

public void setAddress(Address1 address) {


this.address = address;
}

public Employee1() {
super();
// TODO Auto-generated constructor stub
}

public Employee1(Address1 address) {


super();
this.address = address;
}

@Override
public String toString() {
return "Employee [address=" + address + "]";
}

Xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<context:annotation-config/>

<bean class="com.spring.core.autowire.annotation.Address1" name="address1">


<property name="address" value="Panipat"/>
<property name="street" value="56"/>
</bean>

<bean class="com.spring.core.autowire.annotation.Address1" name="address2">


<property name="address" value="Delhi"/>
<property name="street" value="28"/>
</bean>

<bean class="com.spring.core.autowire.annotation.Employee1" name="emp" autowire="constructor"/>


</beans>

Spring Standalone Collections[List,Map,Properties] |


Util Schema in Spring
 We use stand alone application if we want to use list,set and map
reused.
 We can define util schema in configuration file.
 We can define which collection we want to use gain and again.

Bean/pojo class:
package com.standalone.application;

import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Person {


private List<String> friends;
private Map<String, Integer> feeStr;
private Properties properties;

public Map<String, Integer> getFeeStr() {


return feeStr;
}

public void setFeeStr(Map<String, Integer> feeStr) {


this.feeStr = feeStr;
}

public List<String> getFriends() {


return friends;
}

public void setFriends(List<String> friends) {


this.friends = friends;
}

public Properties getProperties() {


return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}

@Override
public String toString() {
return "Person [friends=" + friends + ", feeStr=" + feeStr + ", properties=" + properties + "]";
}

Xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<!-- stand-alone list -->

<util:list list-class="java.util.LinkedList" id="mybestfreind">


<value>Amit</value>
<value>Ankit</value>
<value>Rohit</value>
<value>Mohit</value>
</util:list>

<!-- stand-alone Map -->

<util:map map-class="java.util.HashMap" id="fees">


<entry key="Java frameworks" value="8000"/>
<entry key="Pyhton frameworks" value="5000"/>
<entry key="Hibernate frameworks" value="3000"/>
<entry key="Spring frameworks" value="4000"/>
</util:map>

<!-- stand-alone Properties -->


<util:properties id="dbconfig">
<prop key="driver">com.mysql.jdbc.Driver</prop>
<prop key="username">root</prop>
<prop key="password">Lalit@12Bizlain#34</prop>
<prop key="url">mysql:jdbc://localhost:3306/databse</prop>
</util:properties>

<bean class="com.standalone.application.Person" name="person1">


<property name="friends">
<ref bean="mybestfreind"/>
</property>
</bean>

<bean class="com.standalone.application.Person" name="person2">


<property name="friends">
<ref bean="mybestfreind"/>
</property>
</bean>

<bean class="com.standalone.application.Person" name="person3">


<property name="friends">
<ref bean="mybestfreind"/>
</property>

<property name="feeStr">
<ref bean="fees"/>
</property>

<property name="properties">
<ref bean="dbconfig"/>
</property>
</bean>
</beans>

Main application file:

package com.standalone.application;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"com/standalone/application/stand_alone.config.xml");
Person p1 = context.getBean("person1", Person.class);
System.out.println(p1);

Person p2 = context.getBean("person2", Person.class);


System.out.println(p2);

System.out.println(p1.getFriends().getClass().getName());

Person p3 = context.getBean("person3", Person.class);


System.out.println(p3);
}
}

Stereotype Annotations | @Component Annotation |


@Value Annotation
 @Component is an annotation that allows Spring to automatically
detect our custom beans means it declare bean automatically. We
don't need to write explicitly in xml file.

 We can set properties with help of @Value annotation. We don't


need to write explicitly in xml file.

 We can change our bean name with the help of @Component("Our own
bean name"). otherwise @Component annotation will take Class name
in camel case.

In other words, without having to write any explicit code, Spring will:
 Scan our application for classes annotated with @Component
 Instantiate them and inject any specified dependencies into them
 Inject them wherever needed

Spring has provided a few specialized stereotype


annotations: @Controller, @Service and @Repository. They all provide
the same function as @Component.

They all act the same because they are all composed annotations
with @Component as a meta-annotation for each of them. They are
like @Component aliases with specialized uses and meaning outside of
Spring auto-detection or dependency injection.

If we really wanted to, we could theoretically choose to


use @Component exclusively for our bean auto-detection needs. On the
flip side, we could also compose our own specialized annotations that
use @Component.

However, there are other areas of Spring that look specifically for
Spring's specialized annotations to provide additional automation
benefits. So, we should probably just stick with using the established
specializations most of the time.
Bean/pojo class:

package com.spring.core.stereotype;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("student1")
public class Student {
@Value("Lalit")
private String name;
@Value("panipat")
private String city;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

@Override
public String toString() {
return "Student [name=" + name + ", city=" + city + "]";
}

}
Xml file:

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


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<context:component-scan base-package="com.spring.core.stereotype"/>

</beans>

Main application file:

package com.spring.core.stereotype;

import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("com/spring/core/stereotype/stereo.conf
ig.xml");
Student s1 = context.getBean("student", Student.class);
System.out.println(s1);
}

Collections with @Value


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd">

<context:component-scan base-package="com.spring.core.stereotype"/>

<util:list list-class="java.util.LinkedList" id="list">


<value>India</value>
<value>USA</value>
<value>Germany</value>
<value>Sri Lanka</value>

</util:list>
</beans>

package com.spring.core.stereotype;

import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("student1")
public class Student {
@Value("Lalit")
private String name;
@Value("panipat")
private String city;

@Value("#{list}")
private List<String> country;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

public List<String> getCountry() {


return country;
}

public void setCountry(List<String> country) {


this.country = country;
}

@Override
public String toString() {
return "Student [name=" + name + ", city=" + city + ", country=" +
country + "]";
}

}
Removing Complete XML for Spring Configuration |
@Configuration | @ComponentScan | @Bean Annotation

1. If we want to remove xml file from our application then


following steps we have to follow:
2. We create a simple java class and we use @Configuration
annotation to tell spring container that this normal java
class is our configuration file.
3. Now we can use @ComponentScan(basePackages="") annotation
which scan the @Component annotation all classes and tell
to spring container in which package this class is present.
4. In main application file we have to create object of
AnnotationConfigApplicationContext which is specially
used for annotated configuration file.

 @ComponentScan
Before we rely completely on @Component, we must understand that it's
only a plain annotation. The annotation serves the purpose of
differentiating beans from other objects, such as domain objects.
However, Spring uses the @ComponentScan annotation to actually gather
them all into its ApplicationContext.

If we're writing a Spring Boot application, it is helpful to know


that @SpringBootApplication is a composed annotation that
includes @ComponentScan. As long as our @SpringBootApplication class is
at the root of our project, it will scan every @Component we define by
default.

But in case our @SpringBootApplication class can't be at the root of


our project or we want to scan outside sources, we can
configure @ComponentScan explicitly to look in whatever package we
specify, as long as it exists on the classpath.

Pojo/bean class:

package com.spring.core.javaconfig;

import org.springframework.stereotype.Component;

@Component("firstStudent")
public class Student {

}
Our own configuration file:
package com.spring.core.javaconfig;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.spring.core.javaconfig")
public class JavaConfig {

Main application file:


package com.spring.core.javaconfig;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {


public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(JavaConfig.class);
Student s1 = context.getBean("firstStudent", Student.class);
System.out.println(s1);

}
}

@Bean:
1. We can use @Bean annotation for declaring bean in our own
configuration file.
2. We want to get object of our pojo/class then we have to create a
method which return same object in our configuration file and use
@Bean annotation on that method.
3. From our pojo class we remove @Component annotation and from our
configuration file we remove @ComponentScan annotation.
4. Our bean name will be same as our method name.
5. But we can change our bean name by using @Bean(name= "bean_name")

Bean/pojo class:

package com.spring.core.javaconfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

public class Student {

@Value("Lalit")
private String firstName;
@Value("Bizlain")
private String lastName;

@Autowired
public Address address;

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

@Override
public String toString() {
return "Student [firstName=" + firstName + ", lastName=" + lastName + ", address=" +
address + "]";
}

package com.spring.core.javaconfig;

import org.springframework.beans.factory.annotation.Value;

public class Address {


@Value("Panipat")
private String add;

@Override
public String toString() {
return "Address [add=" + add + "]";
}

public String getAdd() {


return add;
}

public void setAdd(String add) {


this.add = add;
}
}

Our configuration file:


package com.spring.core.javaconfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JavaConfig {

@Bean
public Address getAddress() {
return new Address();
}

@Bean(name ="student")
public Student getStudent() {
return new Student();
}
}

Main application file:


package com.spring.core.javaconfig;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {


public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(JavaConfig.class);
Student s1 = context.getBean("student", Student.class);
System.out.println(s1);

}
}

There are some important implications we should note because of the


differences between @Component and @Bean.

 @Component is a class-level annotation, but @Bean is at the method


level, so @Component is only an option when a class's source code is
editable. @Bean can always be used, but it's more verbose.
 @Component is compatible with Spring's auto-detection,
but @Bean requires manual class instantiation.

 Using @Bean decouples the instantiation of the bean from its class


definition. This is why we can use it to make even third-party classes
into Spring beans. It also means we can introduce logic to decide which
of several possible instance options for a bean to use.

You might also like