You are on page 1of 330

Workshoplink: https://attendee.gotowebinar.

com/register/2348474801872643416

SPRING
—-----------

Java Frameworks

1. Hibernate
2. Spring
3. Spring Boot
4. Microservices
5. Web Services

MAVEN, LOG4J

7:00AM to 8:30AM 8:30AM to 10:00AM


Spring
—----
Hibernate —------
—---- Spring Boot
—----- —------
Web Services —-------
Microservices

Spring:
—---------
1. Introduction
2. Steps to prepare Spring Application
3. Core Module —-----> Core Java
4. Spring DAO/JDBC module —---> JDBC
5. Spring AOP Module —-----------> Core Java
6. Spring Transaction —------------> Core Java, JDBC,....
7. Spring ORM —----------------------> Hibernate
8. Spring WEB Module —-----------> Struts, JSF
9. Spring Web MVC Module —----> Servlets, JSPs, Struts and JSF
10. Spring Security —--------------> Servlets and JSPs
[Authentication And Authorization Services]
Enterprise: It is a Group of organizations that come under a single label, it is a business
organization.

Enterprise Application: It is a software application , it will simplify the business


processing of an enterprise.

To prepare an Enterprise application we have to provide the following layers.

User Interface Layer / Presentation Layer:


—----------------------------------------------------
1. It will provide a starting point to the users in order to interact with the application.
2. It will improve the look and feel of enterprise applications.
3. It is acting as an user interface between Users and Server side applications in
order to transfer data from users to the Server side applications and from Server
side applications to the Users.
4. It will provide a very good environment to perform Client Side Data validations
with Java script functions.
5. It will provide a very good environment to specify different types of requests like
GET, POST, OPTIONS, PUT, HEAD, DELETE,....
6. To prepare the user interface layer we will use a separate logic that is
“Presentation Logic”.
7. To prepare presentation logic, we will use a set of technologies like Html, CSS,
Java Script, Bootstrap, Awt, SWING, JSPs,......

Business Processing Layer / Business Layer:


—----------------------------------------------------------
1. It is the heart of the enterprise application.
2. It will provide a very good environment to implement all business rules and
regulations which are required by the client really.
3. To prepare a Business Processing Layer we will use a separate logic called
“Business Logic”.
4. To prepare Business Logic we will use the components and technologies like
Java Beans, Service Components, Daos, Servlets, EJBs, Model,.........

Data Storage And Access Layer:


—-----------------------------------------
1. The main intention of the Data Storage and Access layer is to connect with
Databases and to perform database operations.

2. To prepare the Data Storage and Access layer we will use a separate logic called
“Persistence Logic”.

3. To prepare Persistence Login in Enterprise applications we will use the


technologies and tools like JDBC, Hibernate, JPA, EJBs Entity Beans.......

There are two types of Enterprise Applications.


1. Web Applications
2. Distributed Applications

Q)What are the differences between Web Applications and Distributed Applications?
—---------------------------------------------------------------------------------------------
Ans:
—---
1. Web Application is a Client-Server application, where the complete
application logic is provided at server machine.
Distributed application is a Client-Server application, where the complete
application logic is distributed over multiple machines that are Local Machine
and Remote machine.

2. In web applications, the Client is fixed, that is Browser.

In Distributed Applications, Client[Local Application] is not fixed, it may be


a normal java program with main() method, it may be a GUI application with
an applet, it may be a servlet , it may be a framework applications like
Struts, JSF, Spring,.....

3. To prepare Web applications we have to use a set of technologies called


“Web Technologies”.
EX: CGI, Servlets, JSPs, PHP, PERL, …….

To prepare Distributed Applications we have to use a set of technologies


called “Distributed Technologies”.
EX: Socket Programming, RMI, CORBA, EJBs, Web Services,.....

4. Web Applications are executed by both Web servers and Application


Servers.

Distributed applications are executed by only Application Servers.

5. Web Application is the collection of Web components, where web


components are executed by the web containers like Servlet container, JSP
container,..... in the Servers.

Distributed Application is the collection of Distributed components like Java


Beans, EJB components,..... Where the distributed components are executed
by the Distributed Containers like EJB Container,...... in the Servers.
6. Web applications are mainly for static response and a little bit dynamic
response from Servers.

Distributed applications are having main concentration on the in


in order to consume remote services from Local machines.

In general, Enterprise Application is the combination of Web Layer and Distributed


Application Layer, Where Web Layer is mainly for presentation in enterprise
application and Distributed Application layer is mainly for Business logic.

Enterprise Application = Web Layer + Distributed Layer

To prepare web applications we will use the following models.


1. Model-I Architecture
2. Model-II Architecture

Model-I Web Application Architecture:


—------------------------------------------------
1. In Model - I Arch we will use a JSP page as controller and View part , We will
use a java bean as model part to include business logic.
2. Model - I Web application Architecture is also called “Page Centric Architecture”,
because a single JSP page is controlling the complete web application.
3. Model - I Web Application Architecture is also called “Jsp Front Architecture '',
because a single JSP page is acting as a Front Controller in order to take
requests from clients and process that requests.
4. In the Model-I web application arch , there is no clear cut separation between
Controller logic and View logic.
5. IN web applications, if we use Model-I Arch then we have to use a JSP page as
controller, its existing features are not sufficient to achieve all the controller
responsibilities , where we need to write java code inside JSp pages to achieve
controller responsibilities, it is against the JSP rules and regulations.

Model - II Web Application Architecture[MVC Arch]:


—-----------------------------------------------------------------
1. In Model - II web application Architecture , we will use a servlet as controller , a
set of JSP pages as view part and a set of Business components as Model.
2. IN Model - II web application Architecture a servlet is acting as Front controller ,
so this arch is called “Servlet-Front Arch”.
3. In Model - II web application Architecture a servlet is controlling the complete
web application , so this arch is also called “Servlet-Centric Arch”.
4. In Model - II web application Arch , Controller component and view components
are separated, it will provide loosely coupled design to the applications.
5. In Model - II arch, a servlet is acting as controller, that is a java program is
performing all the controller activities.
Note: Struts , JSF , Spring Web MVC frameworks are designed on the top of Model - II
web application Arch, that is MVC.

Rules and Regulations in MVC based web applications:


—-----------------------------------------------------------------------
1. In MVC Based web applications , we will use a servlet as controller and a set of
JSP pages as view part, we must not interchange controller and view
components, because Controller component and View component are having
their own responsibilities in MVC based web applications.

2. In MVC based web applications, Every request must be received by Controller


only and Every response must be provided by View only.

3. In MVC based web applications, the controller component will interact with the
Model component for setting data as part of executing business logic and View
components will interact with the Model component for getting the data from the
Model components.
4. In MVC Based web applications, both Controller and View components are not
eligible to interact with Databases directly, they must interact with databases
through Model components.
5. In MVC based web applications , we may use a number of JSP pages in the view
part, but all the JSP pages must be Java code-less pages.

6. In MVC based web applications, we may use a number of pages as the view
part, where we must not provide “Page-To-Page” navigation directly, where we
must provide “Page-Controller-Page” navigation.

Frameworks:
—--------------
Q)To prepare Web applications we have already
1. Server side technologies like Servlets, JSPs,..... To prepare web applications
2. Server softwares like Tomcat, Weblogic, Wildflye,.... To execute web applications.
3. IDEs like Eclipse, Intellij Idea,.... To develop applications in the easiest way
4. Web Application Design models like MVC design pattern to provide a template
for the applications
5. Real time tools like MAVEN, Loig4j,.... For simplifying all the development
activities
—----
—----
—----
What is the requiremt to go for Frameworks?
—------------------------------------------------------------------------------------
Ans:
—---
In general, in all the web applications some components are very much common
and some generic services are very much common.
1. ControllerServlet is common in all the MVC based applications
2. Services like Exception Handling, data Validations, Security,
Transactions,...... very much common from module to module in an
application and from application to application.

The above common elements and common services may take 70% of the development
in an application.
In the above context, 70% of the common implementation and the client specific 30% of
the implementation are provided by the developers explicitly then developers are able to
get the following problems.

1. Development Time will be increased.


2. Development cost will be increased.
3. Needs more manpower
4. Less Parallel development
5. Productivity will be very less.
—----
—----
To overcome the above problems, we need an alternative solution where the 70% of the
common implementation must be provided as a predefined or inbuilt support, in this
case, Developers will focus more on the client specific 30% of the implementation.

In the above situation, Some third party organizations have provided their own products
to provide the common 70% of the implementation as predefined , here the third party
organizations provided products are called “Frameworks”.

With the Frameworks we are able to get the following advantages.


1. Less Development Time.
2. Less Development Cost
3. More Productivity.
4. Provides a standard template for application development.
5. Provides a standard flow of execution for the applications.
6. Provides all common elements like Controllers, Request Processors,.... As
predefined.
7. Provides all the generic services like Exceptions Handling, Internationalization,
Security, data Validations,..... As predefined.
8. Reduces boilerplate code.
9. Able to provide an environment for parallel development.
—---------
—----------
Def1:
Framework is a pre fabricated software component that programmers can reuse, share
and customize in order to simplify application development.

Def2:
Framework is a semi implemented application, it can be used to prepare the
applications as per the developers convenience.

Def3:
Framework is the collection of tools and APIs, it can be used to prepare the application
in a much simplified manner.

There are two types of Frameworks .


1. Web Frameworks
2. Application Framework
Q)What is the difference between Web Frameworks and Application Frameworks?
—-----------------------------------------------------------------------------------------
Ans:
—--
Web Frameworks are able to provide a very good environment to prepare and execute
only web applications.
EX: Struts, JSF, XWork2

Application Frameworks are able to provide a very good environment to prepare the
following types of applications.
1. Standalone Applications
2. Web applications
3. Database related applications
4. Distributed applications
—----
—----
EX: Spring
Q)What are the differences between Struts, JSF and Spring Frameworks?
—----------------------------------------------------------------------------------------------
Ans:
—---
1. Struts, JSF are web frameworks, which are used to prepare and execute only
web applications.

Spring Framework is an application Framework, it can be used to prepare all the


types of applications like
a. Standalone Applications
b. Web Applications
c. Distributed Applications
d. Database Related Applications
—----
—---

2. In the enterprise Application Development, Struts and JSF are able to


have a main focus on the presentation layer.

Spring is able to have a very good focus on all the layers of the enterprise
Applications like Presentation layer[WEB Module, WEB MVC Module], Business
Layer[Core Module, AOP, Module, J2EE Module], Persistence Layer[JDBC Module,
ORM Module, Transactions Module].

3. Struts and JSF are not layered or moduled Frameworks.

Spring Framework is a layered / Moduled Framework.

4. Struts and JSF Frameworks are Heavyweight Frameworks, to prepare simple web
applications like to display a simple welcome message the entire struts and JSF
frameworks must be loaded with or without the requirement.

Spring Framework is lightweight, because, In the case of Spring Framework, if we


prepare a simple application , only the required module libraries must be loaded, not
required to load the complete Spring Framework.

5. Struts and JSF are more API dependent, because Struts and JSF are using Action
classes to prepare application logic.

Spring Framework is less API dependent, because Spring Framework is able to use
POJO classes to define application logic.

6. In case of Struts and JSF Debugging and Testing are very much difficult as they are
more API dependent.

In the case of Spring Framework, Debugging and Testing are very simple as it is less
API dependent.

7. Struts and JSF are using only MVC and its co-related design patterns.

Spring WEB MVC module is only using MVC and its co-related design patterns,
remaining modules of Spring Framework are using other design patterns like IOC or
Dependency Injection, Factory Design Pattern, Singleton Design pattern,....

Spring History:
—----------------
Home : Interface1
Author : Rod Jahnson.
Objective : To simplify and Accelerate enterprise application development.
Initial Versions: 1.x
Latest Version : 5.x, 6.x
Type : Application Framework.
Freeware / Licensed : Freeware and Open source.
Website : www.spring.io
Designed On : J2SE, JDBC API, Servlets API, JSPs API,...

Spring Modules:
—--------------------
Spring 1.x :

Spring 2.x:
Spring 3.x

Spring 4.x:
Spring 5.x

Spring modules Overview:


—--------------------------------
1. Spring Core Module:
It provides the basic foundation for Spring Framework like Beans Management in
Spring Framework, IOC Containers, Dependency Injection ……

2. Spring Context Module:


Spring Core Module is able to provide support for only basic features like Beans
maintenance, Containers ,.... But it has not provided some advanced features
like “Internationalization”, Event Handling, Data Validations,..... These features
are provided by Spring Context Module.

3. Spring DAO Module:


Spring Framework provides a very good environment to implement the DAO
layer in MVC based applications, it defines Spring Framework's own Exception
classes hierarchy and it is converting normal checked exceptions which are
provided by JDBC to Spring Framework provided unchecked Exceptions.

4. Spring JDBC Module:


In plain JDBC , to perform Database operations we have to use the following
steps.
a. Load And Register Driver:
Class.forName(“com.mysql.cj.jdbc.Driver”);

b. Establish Connection between Java application and Database:


Connection con =
DriverManager.getConnection(“jdbc:mysql://localhost:3306/durgadb”);

c. Create Statement/PreparedStatement/CallableStatement as per the


requirement:
Statement st = con.createStatement();

d. Write and execute sql queries:


ResultSet rs = st.executeQuery(“select * from emp1”);
Or
int rowCount = st.executeUpdate(“update emp1 set ESAL = ESAL + 500
where ESAL < 10000”);

e. Close the Resources:


rs.close();
st.close();
con.close();

In all Jdbc applications, the steps like Load and Register Driver, Establish
connection, creating statement object and closing resources are common , only
the step Write and execute sql queries is variable from application to application.

In the above context, Spring JDBC Module is able to abstract all the common
steps of JDBC in the form of Template classes and it provides options to the
developers to only write and execute sql queries.

jdbcTemplate.query(“select * from emp1”);


jdbcTemplate.execute(“update emp1 set ESAL = ESAL + 500 where ESAL <
10000”);

5. Spring AOP Module:


It provides Aspect Orientation in Spring applications like
a. Creating Aspects and injecting aspects.
b. Creating Advices and implementing Advices.
c. Defining join points and pointcuts to inject Aspects.
—---
—---
6. Spring Transactions Module:
It simplifies the Transactions implementation activities like Atomicity,
Isolations,.... In the enterprise applications by having its own
predefined library in the form of TransactionManager,
TransactionState, TransactionDefinition,.......

7. Spring ORM Module:


Spring ORM module is able to provide a very good environment to
integrate ORM implemented applications with Enterprise applications
like integrating Hibernate applications with Spring applications.

In pain Hibernate applications, to perform database operations we


have to use the following steps.
a. Create Configuration class Object.
b. Create SessionFactory object
c. Create Session Object
d. Create a Transaction object as per the requirement.
e. Perform the database operation.
f. Perform either commit / rollback operation.
g. Close the session object
h. Close the SessionFactory object.
In the above , all the steps except ”Perform Database operations” are
common to all the Hibernate applications, it is boilerplate code, where
SPring Framework has provided an abstraction for the above
boilerplate code in the form of some Template classes and it is giving
an option to use to perform database operations directly.

8. Spring WEB Module:


Spring WEB module is providing a very good environment or bridge to integrate other
MVC frameworks applications like Struts, JSF to the Spring applications.

9. Spring WEB MVC Module:


Spring WEB MVC is a MVC based web framework like Struts and JSF, it can be used to
prepare web applications in the simplified manner.

10. Spring Test Module:


Spring Test module is able to provide a very good environment to integrate the unit
testing tools like JUnit, TestIng,.... With Spring applications in order to test spring
applications.
—---
—---

Steps To Prepare Spring Application:


—---------------------------------------------------
1. Download And Install Spring Framework
2. Download And Install Eclipse
3. Create a Java project in Eclipse IDE.
4. Add Spring Libraries to the Java Project.
5. In the Spring project prepare Bean components as per the requirement.
6. Prepare Spring Configuration File and provide beans configuration.
7. Prepare Test application
Download Spring Framework from the following link
https://repo.spring.io/ui/native/libs-milestone/org/springframework/spring/5.3.9/

Download Apache Commons-logging-version.jar file from the following link.

https://commons.apache.org/proper/commons-logging/download_logging.cgi
Add the following JAR files to the Java project:

Spring-beans-version.jar
Spring-core-Version.jar
Spring-context-version.jar
Spring-context-Support-version.jar
Spring-expression-version.jar
Commons-logging-version.jar

Beans in Spring Framework:


—------------------------------------
Bean is a reusable software component, it is able to manage the state of a particular
entity.

In Different frameworks and Tools, Beans will be used in different forms.


1. Struts : Action Forms
2. JSF : Backing Beans
3. Hibernate : Entities or POJOs
4. Spring : Beans or POJOs
5. EJBs : Session Beans, Entity Beans, ……

POJO is Plain Old Java Objects, these are beans which must not extend or implement
predefined Libraries except java.io.Serializable.

If we want to use Beans in java applications then we have to use the following rules and
regulations.
1. Every Bean class must be declared with public, non abstract and non final.

Where the main purpose to declare bean class as public is to make available the
scope of bean classes to the Containers, Frameworks,..... Inorder to create
objects.

Where the main purpose to declare a bean class as non abstract is to allow
Frameworks or containers to create objects.

Where the main purpose to declare a bean class as non-final is to allow


extending a bean class to another bean class in order to reuse one bean class
behavior in another bean class.
2. In the Bean class, we must provide a separate setXXX() method and getXXX()
method for every property.

3. In Bean class, declare all properties as private and declare all methods as public.

Note: The above points like 2nd and 3rd are able to improve Encapsulation in java
applications.

4. If we want to apply our own comparison mechanisms while comparing two


objects then we have to override the Object class provided equals() method in
the bean class.
5. If we want to generate hashcode values to the bean objects as per our
requirement then it is suggestible to override the Object class provided
hashCode() method in the bean class.

6. In general, in Bean classes if we want to provide a constructor then provide 0-arg


constructor, not suggestible to provide parameterized constructor.

In general, Containers, Frameworks and Servers will create objects for the bean
class, while creating objects for the bean classes Containers, servers ,
Frameworks will search and execute 0-arg constructor only, not any
parameterized constructor.

Spring Framework is using the above classes with the following conventions.
1. We will provide the total application logic inside the bean classes only.
2. We will use parameterized constructors in bean classes as per the requirement.
3. We will use Bean classes to provide application configuration details.

EX:
—---
Public class User{
public String sayHello(){
return “Hello User”;
}
}

Public class User{


private String uname;
public void setUname(String uname){
This.uname = uname;
}
public String getUname(){
Return uname;
}
public String sayHello(String uname){
return “Hello “+uname;
}
}

Spring Configuration File:


—-------------------------------
Spring Configuration file is an xml file, it must have all the bean classes configuration
details which are required by the Container in order to create Bean objects and in order
to supply that bean objects to the application.

To provide beans configuration in the Spring configuration file we have to use the
following tags.

<beans —-------XSD —------>


<bean id=”---” class=”---”/>
—----
—---
</beans>

Where “<beans>” is a root tag, it includes a number of bean configurations.

Where “<bean> tag is able to provide single bean class configuration.

Where “id” attribute in <bean> tag will provide identity for the bean object.

Where “class” attribute will take the fully qualified name of the bean class.

Note: In the Spring Configuration file we have to provide XSD , here we will get XSD
from the following resource.
E:\softwares\frameworks\Spring\spring-framework-5.3.9\docs\reference\html\core.html
[As per my File system]

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


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

EX:
SpringConfig.xml
—---------------------

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


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id=”helloBean” class=”com.durgasoft.beans.Hello”/>
</beans>

Prepare Test Application:


—-------------------------------
The main intention of Test application is
1. Create a Container.
2. Get a Bean object from Container.
3. Access Business methods of the respective Bean.

Creating a Container:
—--------------------------
The Main purpose of Container is to create bean objects and to manage bean objects
along with their identities.

Spring Framework has provided the following two types of Containers.


1. BeanFactory
2. ApplicationContext
To represent ApplicationContext containers, Spring Framework has provided a
predefined interface in the form of “ApplicationContext” and Spring Framework has
provided an implementation class for ApplicationContext in the form of
“ClassPathXmlApplicationContext”.

To create a ClassPathXmlApplicationContext object we have to use the following


Constructor.

public ClassPathXmlApplicationContext(String configFilePath)


EX:
ApplicationContext context = new ClassPathXmlApplicationContext(“SpringConfig.xml”);

When we create a Container object like above, Container will perform the following
actions.

1. Identify the spring configuration file.


2. When Spring Configuration is identified , Container will perform loading
Configuration file, parsing configuration file and reading the data from
Configuration file.
3. After getting data from the Configuration file, Container will recognize all the bean
configurations and Container will create objects for all the bean classes which
we configured in the spring configuration file.

4. After creating bean objects, Container will manage all the bean objects along
with their identity values [id attribute values].

Get a Bean object from Container


—------------------------------------------
To get a particular Bean object from Container we have to use the following method
from ApplicationContext.

public Object getBean(String idValue)


EX:
Hello hello = context.getBean(“helloBean”);

Access Business Method:


—--------------------------------
String msg = hello.sayHello();
System.out.println(msg);
EX:
—--
Hello.java

package com.durgasoft.beans;

public class Hello {

public String sayHello() {

return "Hello User!";

SpringConfig.xml

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

<beans
xmlns="http://www.springframework.org/schema/be
ans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-ins
tance"

xsi:schemaLocation="http://www.springframework.
org/schema/beans
https://www.springframework.org/schema/beans/sp
ring-beans.xsd">

<bean id="helloBean"
class="com.durgasoft.beans.Hello"/>

</beans>

Test.java
package com.durgasoft.test;

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

import com.durgasoft.beans.Hello;

public class Test {

public static void main(String[] args) {


ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Hello hello = (Hello) applicationContext.getBean("helloBean");
String message = hello.sayHello();
System.out.println(message);
}

}
If we provide properties and their respective setter and getter methods in bean class
then we have to configure these properties in the spring configuration file under bean
configurations.

To configure bean properties in the spring configuration file we have to use the following
tag under <bean> tag.

<property name=”--” value=”---”/>

Where the “name” attribute will take the property name which we define in the bean
class.

Where the “value” attribute will take the value of the property which we want to assign to
the property.

Note: If we provide property configurations in the bean configuration file, Container will
provide the specified values in the bean object by executing the respective setter
methods in bean class.

EX:
—---
Welcome.java

package com.durgasoft.beans;

public class Welcome {

private String name;

private String message;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getMessage() {

return message;

public void setMessage(String message) {

this.message = message;

}
public String sayWelcome() {

return "Hello "+name+", "+message;

SpringConfig.xml

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

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/be
ans

https://www.springframework.org/schema/beans/spring-beans.xs
d">

<bean id="welcomeBean" class="com.durgasoft.beans.Welcome">

<property name="name" value="Durga"/>

<property name="message" value="Welcome To Durgasoft!"/>

</bean>

</beans>

Test.java
package com.durgasoft.test;

import org.springframework.context.ApplicationContext;

import
org.springframework.context.support.ClassPathXmlApplicationC
ontext;

import com.durgasoft.beans.Welcome;

public class Test {

public static void main(String[] args) {

ApplicationContext applicationContext = new


ClassPathXmlApplicationContext("SpringConfig.xml");

Welcome welcome = (Welcome)


applicationContext.getBean("welcomeBean");

System.out.println(welcome.sayWelcome());

Ex3:
Employee.java

package com.durgasoft.beans;

public class Employee {


private int eno;

private String ename;

private float esal;

private String eaddr;

public int getEno() {

return eno;

public void setEno(int eno) {

this.eno = eno;

public String getEname() {

return ename;

public void setEname(String ename) {

this.ename = ename;

public float getEsal() {

return esal;

}
public void setEsal(float esal) {

this.esal = esal;

public String getEaddr() {

return eaddr;

public void setEaddr(String eaddr) {

this.eaddr = eaddr;

public void displayEmployeeDetails() {

System.out.println("Employee Details");

System.out.println("----------------------");

System.out.println("Employee Number : "+eno);

System.out.println("Employee Name : "+ename);

System.out.println("Employee Salary : "+esal);

System.out.println("Employee Address : "+eaddr);

}
}

SpringConfig.xml

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

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/be
ans

https://www.springframework.org/schema/beans/spring-beans.xs
d">

<bean id="employee"
class="com.durgasoft.beans.Employee">

<property name="eno" value="111"/>

<property name="ename" value="Durga"/>

<property name="esal" value="50000.345f"/>

<property name="eaddr" value="Hyd"/>

</bean>

</beans>

Test.java

package com.durgasoft.test;

import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationC
ontext;

import com.durgasoft.beans.Employee;

public class Test {

public static void main(String[] args) {

ApplicationContext applicationContext = new


ClassPathXmlApplicationContext("SpringConfig.xml");

Employee employee =
(Employee)applicationContext.getBean("employee");

employee.displayEmployeeDetails();

Locations to keep Spring Configuration file in Spring Applications.


1. By creating source folders like resources.
2. Directly Under “src”.
3. By creating a package like “com.durgasoft.config”.

In the first two cases, ApplicationContext is able to take only spring configuration file
name , because by default all source folder are existed in the “classpath” environment
variable.

In the 3rd case, we must provide the Spring Configuration file name and location as its
full address to the ApplicationContext.
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("com/durgasoft/config/SpringC
onfig.xml");

IOC Containers in Spring Framework:


—--------------------------------------------------
The main purpose of IOC Containers is to create Bean objects and to manage bean
objects.

There are two types of IOC Containers.


1. BeanFactory
2. ApplicationContext

BeanFactory:
—----------------
It is a Base container in spring framework.

It is providing only the basic functionalities like Creating bean objects and manatining
bean objects in SPring applications.
It is not providing advanced features like Internationalization, Event Handling, Data
Validations,......
To represent BeanFactory container Spring Framework has provided a predefined
interface in the form of “org.springframework.beans.factory.BeanFactory“ and
its implementation class was provided by Spring framework in the form of
“org.springframework.beans.factory.xml.XmlBeanFactory”

Note: XmlBeanFactory is deprecated in Spring 3.x version, it may not be available in the
feature releases.

To create an XmlBeanFactory object we have to use the following constructor.

public XmlBeanFactory(Resource resource)

Resource is an object, it is able to represent all the configuration details of the Spring
Configuration file.

To represent Resource , Spring Framework has provided a predefined interface in the


form of “org.springframework.core.io.Resource” and its implementation classes are
provided by Spring Framework like below.

1. ByteArrayResource: It is able to get all the spring configuration details from a


byte[].
2. ClassPathResource: It is able to get all the configuration details from a file which
is available in the classpath.
3. FileSystemResource: It is able to get all the spring configuration details from a
file which is in the system Hard disk.
4. UrlResource: It is able to get all the spring configuration details from a file which
is available in the network.
5. ServletContextResource: It is able to get all the spring configuration details from
a ServletContext object existing in a web application.
6. PortletContextResource:It is able to get all the spring configuration details from a
PortletContext object existing in a web application.
7. InputStreamResource: It is able to get all the spring configuration details from an
InputStream object.

EX: Resource resource = new ClassPathResource(“SpringConfig.xml”);


BeanFactory beanFactory = new XmlBeanFactory(resource);

After creating a BeanFactory object, to create and get a particular Bean object we have
to use the following method.
public Object getBean(String idValue)

EX:
Customer.java
package com.durgasoft.beans;

public class Customer {


private String cid;
private String cname;
private String caddr;

public String getCid() {


return cid;
}

public void setCid(String cid) {


this.cid = cid;
}

public String getCname() {


return cname;
}

public void setCname(String cname) {


this.cname = cname;
}

public String getCaddr() {


return caddr;
}

public void setCaddr(String caddr) {


this.caddr = caddr;
}
public void displayCustomerDetails(){
System.out.println("Customer Name");
System.out.println("------------------");
System.out.println("Customer Id : "+cid);
System.out.println("Customer Name :
"+cname);
System.out.println("Customer Address :
"+caddr);
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="customer" class="com.durgasoft.beans.Customer">
<property name="cid" value="C-111"/>
<property name="cname" value="Durga"/>
<property name="caddr" value="Hyd"/>
</bean>
</beans>

Main.java
import com.durgasoft.beans.Customer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
public class Main {
public static void main(String[] args) {
Resource resource = new ClassPathResource("SpringConfig.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);
Customer customer = (Customer)
beanFactory.getBean("customer");
customer.displayCustomerDetails();
}
}
Bean Factory Internal Flow:
—------------------------------------
When we create a BeanFactory object, BeanFactory will perform the following actions.
1. BeanFactory will take Resource object from the XmlBeanFactory constructor.
2. BeanFactory container will find the name and location of the Spring Configuration
file from the Resource object.
3. BeanFactory container will find the Spring Configuration file and BeanFactory
container will perform Spring configuration file loading, parsing , reading the
content and store the content in Resource object.

When we access the getBean() method on BeanFactory reference then BeanFactory


container will perform the following actions.
1. BeanFactory container will get the parameter value from getBean() method that
is the id attribute value of the bean class configuration.
2. BeanFactory container will search for the bean configuration in the resource
object on the basis of the provided id value.
3. In the Resource object, if any bean configuration is identified with the provided id
value then BeanFactory container will identify the name and location of the bean
class from “class” attribute in bean configuration.
4. BeanFactory container will identify the bean class and it will perform Loading
bean class bytecode, creating object for the bean class and initialized bean
object by executing setter() methods as per the <property> tags declaration in
bean configuration.
5. BeanFactory container will manage the generated Bean object along with its id
value and BeanFactory will return the generated bean object as return value.

ApplicationContext Container:
—------------------------------------------
It is an IOC Container, it is able to create bean objects and it is able to manage all the
bean objects in order to supply bean objets to the application.

ApplicationContext is a child container to the BeanFactory, it is able to support the


advanced features of the applications like I18N, Event Handling, Data Validations,.......
Along with the basic functionalities what BeanFactory is able to perform.
To represent ApplicationContext container , Spring Framework has provided a
predefined interface in the form of “org.springframework.context.ApplicationContext”
and its implementation classes provided by Spring Framework in the form of the
following classes.

1. ClassPathXmlApplicationContext: It is able to get all the Spring configuration


details from an XML file existing at the classpath environment variable referred
locations inside the present project.
2. FileSystemXmlApplicationContext : It is able to get all the Spring configuration
details from an xml file existing at a particular location in the System Hard Disk
outside of the present application.
3. WebXmlApplicationContext : It will be used in web applications and it is able
to get all the spring configuration details from an xml file existing in a web
application.

EX:
ApplicationContext context = new ClassPathXmlApplicationContext(“SpringConfig.xml”);

EX:
Customer.java
package com.durgasoft.beans;

public class Customer {


public Customer(){
System.out.println("Customer Bean Object is creating.....");
}
private String cid;
private String cname;
private String caddr;

public String getCid() {


return cid;
}

public void setCid(String cid) {


this.cid = cid;
}

public String getCname() {


return cname;
}

public void setCname(String cname) {


this.cname = cname;
}

public String getCaddr() {


return caddr;
}

public void setCaddr(String caddr) {


this.caddr = caddr;
}

public void displayCustomerDetails(){


System.out.println("Customer Name");
System.out.println("------------------");
System.out.println("Customer Id : "+cid);
System.out.println("Customer Name : "+cname);
System.out.println("Customer Address : "+caddr);
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="customer" class="com.durgasoft.beans.Customer">
<property name="cid" value="C-111"/>
<property name="cname" value="Durga"/>
<property name="caddr" value="Hyd"/>
</bean>
</beans>

Main.java
import com.durgasoft.beans.Customer;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
System.out.println("Before ApplicationContext
creating......");
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
System.out.println("After Creating
ApplicationContext........");
System.out.println("Before getBean()......");
Customer customer = (Customer)
applicationContext.getBean("customer");
System.out.println("After getBean().......");
customer.displayCustomerDetails();
}
}
ApplicationContext internal flow of execution:
—---------------------------------------------------------------
When we create an ApplicationContext Container object , Container will perform the
following actions.

1. Identify the spring configuration file.


2. When Spring Configuration is identified , Container will perform loading
Configuration file, parsing configuration file and reading the data from
Configuration file.
3. After getting data from the Configuration file, Container will recognize all
the bean configurations and Container will perform Bean class loading,
bean class instantiations and create objects for all the bean classes
which we configured in the spring configuration file.

4. After creating bean objects, Container will manage all the bean objects
along with their identity values [id attribute values].
5. If we access the getBean() method , the ApplicationContext container will
send the requested bean object to the application.

Q)What are the differences between BeanFactory and ApplicationContext


containers?
—------------------------------------------------------------------------------
Ans:
—---
1. BeanFactory is a base container in spring framework, it is able to provide basic
functionalities like creating bean objects and manage Bean objects.
ApplicationContext container is a child to BeanFactory container, it is able to
provide some advanced features like I18N, Event Handling, Data Validations,....
Along with all the functionalities which are provided by BeanFactory.

2. BeanFactory is an outdated container in Spring Framework, its


implementation class XmlBeanFactory is deprecated from Spring3.x version
onwards.

ApplicationContext container is not an outdated container, its implementation


classes are not deprecated.

3. BeanFactory Container is not supporting AOP programming in


Spring Framework inorder to integrate the services like Transactions,
Security,......

ApplicationContext Container is supporting AOP programming in


Spring Framework inorder to integrate the services like Transactions,
Security,......

4. BeanFactory container is not supporting Web Application development by


using Spring Web and Web MVC Modules.

ApplicationContext container is supporting web application development by using


the spring provided modules like Web Module and Web MVC Module.

5. BeanFactory is not supporting the spring modules like Spring ORM, Spring
Tx,....

ApplicationContext is able to support modules like Spring Transactions, Spring


ORM,.....

6. BeanFactory container is able to support Bean scopes only Singleton scope


and Prototype.

ApplicationContext is able to support all the types of Scopes for the bean objects
like Singleton scope, Prototype scope, request scope, session scope,
GlobalSession Scope,.....
7. BeanFactory is suitable for Standalone Applications.

ApplicationContext is suitable for all the types of applications.

8. BeanFactory container has only one implementation class that is


“XmlBeanFactory”.

ApplicationContext container has three implementation classes like


ClassPathXmlApplicationContext, FileSYstemXmlApplicationContext,
WebXmlApplicationContext.

Beans In Spring Framework:


—-----------------------------------
Bean is a reusable software component, it is able to manage the state of a particular
entity.

In Different frameworks and Tools, Beans will be used in different forms.


6. Struts : Action Forms
7. JSF : Backing Beans
8. Hibernate : Entities or POJOs
9. Spring : Beans or POJOs
10. EJBs : Session Beans, Entity Beans, Message Driven Beans……

POJO is Plain Old Java Objects, these are beans which must not extend or implement
predefined Libraries except java.io.Serializable.

If we want to use Beans in java applications then we have to use the following rules and
regulations.
1. Every Bean class must be declared with public, non abstract and non final.

Where the main purpose to declare bean class as public is to make available the
scope of bean classes to the Containers, Frameworks,..... Inorder to create
objects.

Where the main purpose to declare a bean class as non abstract is to allow
Frameworks or containers to create objects.

Where the main purpose to declare a bean class as non-final is to allow


extending a bean class to another bean class in order to reuse one bean class
behavior in another bean class.
2. In the Bean class, we must provide a separate setXXX() method and getXXX()
method for every property.

3. In Bean class, declare all properties as private and declare all methods as public.

Note: The above points like 2nd and 3rd are able to improve Encapsulation in java
applications.

4. If we want to apply our own comparison mechanisms while comparing two bean
objects then we have to override the Object class provided equals() method in
the bean class.

5. If we want to generate hashcode values to the bean objects as per our


requirement then it is suggestible to override the Object class provided
hashCode() method in the bean class.

6. In general, in Bean classes if we want to provide a constructor then provide 0-arg


constructor, not suggestible to provide parameterized constructor.

In general, Containers, Frameworks and Servers will create objects for the bean
class, while creating objects for the bean classes Containers, servers ,
Frameworks will search and execute 0-arg constructor only, not any
parameterized constructor.

Spring Framework is using the above classes with the following conventions.
4. We will provide the total application logic inside the bean classes only.
5. We will use parameterized constructors in bean classes as per the requirement.
6. We will use Bean classes to provide application configuration details.

In Spring applications, every bean class description/ metadata must be provided to the
IOC Containers in order to create Bean Objects .

There are three ways to send bean classes description or metadata to the IOC
Containers.

1. By Using an XML file configurations


2. By Using Java Based Configurations.
3. By Using Annotations Configurations.

Bean Configurations through XML file:


—------------------------------------------------
To provide any bean class configuration in the spring configuration file then we have to
use the following tags.

<beans>
<bean id=”--” name = “--” class=”--” scope=”--”>
—-----
</bean>
</beans>

Where the “id” attribute will take the identity value for the bean in order to search the
bean object in IOC Container.

Where the “name” attribute will take the identity of the Bean object in order to search for
the bean in IOC Container.

Q)What is the difference between “id” attribute and “name” attribute in bean
configurations in spring configuration file?
—-------------------------------------------------------------------------------------------------
Ans:
—---
“Id” attribute is able to take only one identity value for the bean object.

“Name” attribute is able to take one or more number of identity values to the Bean
object.

In Bean configuration, we will provide more than one identity value to the bean object by
providing either, or ; or space as separator.

Note: If we provide more than one value to “name” attribute then the first value is
treated as the actual identity for the bean and all the remaining values are treated as
alias names.

EX1:
<beans>
<bean id=”hello” class=”com.durgasoft.beans.Hello”/>
</beans>
Hello h = applicationContext.getBean(“hello”);
Status: Valid

EX2:
<beans>
<bean id=”hello1 hello2 hello3” class=”com.durgasoft.beans.Hello”/>
</beans>

Hello h1 = applicationContext.getBean(“hello1”); —---------------> Invalid


Hello h2 = applicationContext.getBean(“hello2”);-------------------> Invalid
Hello h3 = applicationContext.getBean(“hello3”);-------------------> Invalid
Hello h4 = applicationContext.getBean(“hello1 hello2 hello3”);---> Valid
Hello h4 = applicationContext.getBean(“hello1hello2hello3”);---->Invalid

EX3:
<beans>
<bean id=”hello1,hello2,hello3” class=”com.durgasoft.beans.Hello”/>
</beans>

Hello h1 = applicationContext.getBean(“hello1”); —---------------> Invalid


Hello h2 = applicationContext.getBean(“hello2”);-------------------> Invalid
Hello h3 = applicationContext.getBean(“hello3”);-------------------> Invalid
Hello h4 = applicationContext.getBean(“hello1,hello2,hello3”);---> Valid

EX4:
<beans>
<bean name=”hello” class=”com.durgasoft.beans.Hello”/>
</beans>

Hello h = applicationContext.getBean(“hello”);
Status: Valid

EX5:
<beans>
<bean name=”hello1 hello2 hello3” class=”com.durgasoft.beans.Hello”/>
</beans>

Hello h1 = applicationContext.getBean(“hello1”); —---------------> Valid


Hello h2 = applicationContext.getBean(“hello2”);-------------------> Valid
Hello h3 = applicationContext.getBean(“hello3”);-------------------> Valid
Hello h4 = applicationContext.getBean(“hello1 hello2 hello3”);---> INvalid
Hello h4 = applicationContext.getBean(“hello1hello2hello3”);---->Invalid

EX6:
<beans>
<bean name=”hello1,hello2,hello3” class=”com.durgasoft.beans.Hello”/>
</beans>

Hello h1 = applicationContext.getBean(“hello1”); —---------------> Valid


Hello h2 = applicationContext.getBean(“hello2”);-------------------> Valid
Hello h3 = applicationContext.getBean(“hello3”);-------------------> Valid
Hello h4 = applicationContext.getBean(“hello1,hello2,hello3”);---> Invalid

EX7:
<beans>
<bean name=”hello1;hello2;hello3” class=”com.durgasoft.beans.Hello”/>
</beans>

Hello h1 = applicationContext.getBean(“hello1”); —---------------> Valid


Hello h2 = applicationContext.getBean(“hello2”);-------------------> Valid
Hello h3 = applicationContext.getBean(“hello3”);-------------------> Valid
Hello h4 = applicationContext.getBean(“hello1;hello2;hello3”);---> Invalid

Q)Is it possible to provide both “id” attribute and “name” attribute for a single bean in a
Spring configuration file?
—-----------------------------------------------------------------------------------------
Ans:
—---
Yes, it is possible to provide both id attribute and name attribute for a single bean in
spring configuration file, where id attribute value is treated as the actual identity of the
bean and the name attribute value is treated as alias names to the bean object.

EX:
<beans>
<bean id=”hello” name=”hello1;hello2;hello3”
class=”com.durgasoft.beans.Hello”/>
</beans>

Hello hello = applicationContext.getbean(“hello”);----------------> valid


Hello h1 = applicationContext.getBean(“hello1”); —---------------> Valid
Hello h2 = applicationContext.getBean(“hello2”);-------------------> Valid
Hello h3 = applicationContext.getBean(“hello3”);-------------------> Valid

In the Spring configuration file, we are able to provide alias names to the beans
explicitly by using <alias> tag.

<alias name=”--” alias=”--”/>

Where “name” attribute will take the bean identity which we have already defined in the
Spring Configuration file.

Where the “alias” attribute will define the alias name for the bean identity.

EX:
<beans>
<bean id=”hello” class=”com.durgasoft.beans.Hello”/>
<alias name=”hello” alias=”hello1”/>
</beans>

Hello hello = applicationContext.getbean(“hello”);----------------> valid


Hello h1 = applicationContext.getBean(“hello1”); —---------------> Valid

EX:
Wish.java
package com.durgasoft.beans;

public class Wish {


private String name;
private String wishMessage;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getWishMessage() {


return wishMessage;
}

public void setWishMessage(String wishMessage) {


this.wishMessage = wishMessage;
}

public String sayWish(){


String message = "Hello "+name+", "+wishMessage;
return message;
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="wish" class="com.durgasoft.beans.Wish">
<property name="name" value="Durga"/>
<property name="wishMessage" value="Good Morning!"/>
</bean>
<alias name="wish" alias="wish1"/>
<alias name="wish1" alias="wish2"/>
<alias name="wish2" alias="wish3"/>
</beans>

Main.java
import com.durgasoft.beans.Wish;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");

Wish wish = (Wish) applicationContext.getBean("wish");


System.out.println(wish.sayWish());

Wish wish1 = (Wish) applicationContext.getBean("wish1");


System.out.println(wish1.sayWish());

Wish wish2 = (Wish) applicationContext.getBean("wish2");


System.out.println(wish2.sayWish());

Wish wish3 = (Wish) applicationContext.getBean("wish3");


System.out.println(wish3.sayWish());
}
}

Scopes for the Beans in Spring Configuration File:


—-----------------------------------------------------------------
In spring applications, we are able to define scopes to the beans by using the “scope“
attribute in the <bean> tag in the spring configuration file.

To define scopes to the beans, spring framework has provided the following scopes.

1. Singleton Scope
2. Prototype Scope
3. Request Scope
4. Application Scope
5. Session Scope
6. Global Session Scope
7. Websocket Scope

Singleton Scope: It will create a single bean object for every bean definition in the
Spring configuration file.
EX:
<beans>
<bean id=”wish” class=”com.durgasoft.beans.Wish” scope=”singleton”/>
</beans>

Wish wish1 = (wish)applicationContext.getBean(“wish”);


Wish wish2 = (wish)applicationContext.getBean(“wish”);
Wish wish3 = (wish)applicationContext.getBean(“wish”);

System.out.println(wish1);// Wish@abc123
System.out.println(wish2);// Wish@abc123
System.out.println(wish3);// Wish@abc123

Prototype Scope: It will create a separate new Bean object for every request of the
bean , that is, for every getBean() method call.
EX:
<beans>
<bean id=”wish” class=”com.durgasoft.beans.Wish” scope=”prototype”/>
</beans>

Wish wish1 = (wish)applicationContext.getBean(“wish”);


Wish wish2 = (wish)applicationContext.getBean(“wish”);
Wish wish3 = (wish)applicationContext.getBean(“wish”);

System.out.println(wish1);// Wish@a123
System.out.println(wish2);// Wish@b234
System.out.println(wish3);// Wish@c345

Request Scope: It will create a separate new bean object for every request.

Application Scope: It will create a separate new bean object for every ServletContext
object.

Session Scope: It will create a separate new Bean object for each and every Session
object.
GlobalSession Scope: It will create a separate new bean object for every portlet
lifecycle.

Websocket scope: It will create a separate bean object for every websocket lifecycle.

Q)In general, in ApplicationContext, all bean objects are created at the time of container
startup, in beans if we provide prototype scope then Bean objects will be created at the
time of calling getBean() method, If we provide prototype scope to a particular bean and
if we use ApplicationContext container then how bean object is created by the
ApplicationContext, is it created at the time of ApplicationContext startup or at the time
of calling getBean() method?
—-------------------------------------------------------------------------------------------------
Ans:
—---
If we provide prototype scope to a particular bean and if we use ApplicationContext then
the ApplicationContext container will not create a bean object at the time of
applicationContext startup, it will create a bean object the moment when we access the
getBean() method.

Q)Is it possible to define user defined scopes for the beans in Spring Framework?
—----------------------------------------------------------------------------------------
Ans:
—----
Yes, it is possible to define our own scope to the bean component, but we have to use
some Custom Scope configurations in the Spring Configuration file.

Thread Scope in Core Java Application:


class ThreadScope extends ThreadLocal<String>{

@Override
protected String initialValue() {
return "No Value Yet in this scope.....";
}

}
class A{
void m1(){
System.out.println("m1():
"+Thread.currentThread().getName()+": Thread1 Scope :
"+Thread1.threadScope.get());
System.out.println("m1():
"+Thread.currentThread().getName()+": Thread2 Scope :
"+Thread2.threadScope.get());
}
void m2(){
System.out.println("m2():
"+Thread.currentThread().getName()+": Thread2 Scope :
"+Thread2.threadScope.get());
System.out.println("m2():
"+Thread.currentThread().getName()+": Thread1 Scope :
"+Thread1.threadScope.get());
}
}
class Thread1 extends Thread{
static ThreadScope threadScope = new ThreadScope();
A a;
Thread1(A a){
this.a = a;
}
@Override
public void run() {
threadScope.set("Data In Thread1 Scope....");
a.m1();
}
}
class Thread2 extends Thread{
static ThreadScope threadScope = new ThreadScope();
A a;
Thread2(A a){
this.a = a;
}
@Override
public void run() {
threadScope.set("Data in Thread2 Scope...");
a.m2();
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
Thread1 t1 = new Thread1(a);
t1.setName("First Thread");
t1.start();

Thread2 t2 = new Thread2(a);


t2.setName("Second Thread");
t2.start();
}
}

Procedure To define User defined Scope in SPring Applications:


—------------------------------------------------------------------------------------------
1. Provide Scope through Threadlocal class.
2. Create a user defined class and implement “Scope” predefined interface in order
to keep Bean objects in the scope, in order to remove bean objects from the
scope.
3. Prepare Configuration file with the following configuration details.
a. Configure all the bean classes .
b. Configure the User defined Scope class as a bean in the spring
configuration file.
c. Configure CustomScopeConfigurer in the spring configuration file in order
to define scope name along with scope object and to submit scope details
to the Spring Framework.
d. Apply User defined scope to the respective bean definitions in the bean
configuration file.

4. Prepare Test Application

EX:
—---
Hello.java
package com.durgasoft.beans;

public class Hello {


public Hello(){
System.out.println("Bean Object is creating.....");
}
}
MyThreadeLocale.java
package com.durgasoft.scope;

import java.util.HashMap;
import java.util.Map;

public class MyThreadLocale extends ThreadLocal{


@Override
protected Object initialValue() {
Map<String, Object> scope = new HashMap<>();
return scope;
}
}

ThreadScope.java
package com.durgasoft.scope;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.Map;

public class ThreadScope implements Scope {


MyThreadLocale myThreadLocale = new MyThreadLocale();
Map<String, Object> scope = null;
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
scope = (Map<String, Object>) myThreadLocale.get();
Object obj = scope.get(name);
if(obj == null){
obj = objectFactory.getObject();
scope.put(name, obj);
}
return obj;
}

@Override
public Object remove(String name) {
Object obj = scope.remove(name);
return obj;
}

@Override
public void registerDestructionCallback(String s, Runnable
runnable) {

@Override
public Object resolveContextualObject(String s) {
return null;
}

@Override
public String getConversationId() {
return null;
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.durgasoft.beans.Hello"
scope="thread"/>
<bean id="threadScope" class="com.durgasoft.scope.ThreadScope"/>
<bean id = "scopeConfigurer"
class="org.springframework.beans.factory.config.CustomScopeConfigurer
">
<property name="scopes">
<map>
<entry key="thread" value-ref="threadScope"/>
</map>
</property>
</bean>
</beans>

Main.java
import com.durgasoft.beans.Hello;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import java.lang.ref.SoftReference;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Hello hello1 = (Hello) applicationContext.getBean("hello");
System.out.println(Thread.currentThread().getName()+"
"+hello1);
Hello hello2 = (Hello) applicationContext.getBean("hello");
System.out.println(Thread.currentThread().getName()+"
"+hello2);
System.out.println();

new Thread(()->{
Hello hello3 = (Hello)
applicationContext.getBean("hello");
System.out.println(Thread.currentThread().getName()+"
"+hello3);
Hello hello4 = (Hello)
applicationContext.getBean("hello");
System.out.println(Thread.currentThread().getName()+"
"+hello4);
System.out.println();
}).start();

new Thread(()->{
Hello hello5 = (Hello)
applicationContext.getBean("hello");
System.out.println(Thread.currentThread().getName()+"
"+hello5);
Hello hello6 = (Hello)
applicationContext.getBean("hello");
System.out.println(Thread.currentThread().getName()+"
"+hello6);
}).start();
}
}

Internal Flow:
—----------------
1. When we start ApplicationContext, it will not create any bean object if the bean
definitions are having user defined scopes like thread at its startup time.
2. When we access the getBean() method with an identity value, ApplicationContext
will perform the following actions.
a. ApplicationContext will take the getBean() method parameter.
b. ApplicationContext will search for the bean definition in
SpringConfiguration file on the basis of id value.
c. If any bean definition exists in SpringConfiguration file ApplicationContext
will take “scope” attribute value.
d. ApplicationContext will check whether the Scope exists or not in the
CustomScopeConfigurer, if it exists then ApplicationContext will take the
respective Scope class and access get() method in the SCope class.
e. Inside the get() method of Scope class, myThreadLocale.get() method will
generate a new Scope[Map] object for every new thread.
f. Inside the get() method of Scope class, ApplicationContext will perform
the following actions as per the implementation of get() method.
I. Check whether the Bean object exists in the Scope object or not.
II. If it exists then return the existing bean object to the getBean()
method which is called in Main class.
III. If the Bean object does not exist then getBean object from
ObjectFactory , keep this bean object in the Scope and return that
bean object to getBean() method which is accessed in Main class.

Java Based Configurations:


—--------------------------------------
The main purpose of Java based configurations is to provide all the bean configuration
details through a java program to the IOC Container without using Spring
Configuration File.

Steps:
1. Prepare Bean classes as per the requirement.
2. Prepare Configuration Class to provide bean configuration details to the
Container.
3. Prepare test application, Get all beans from Container and access business
methods.

In Java based configurations , we have to declare a java class as a configuration class


to provide bean configuration details to the Container, it must be marked with an
annotation like @Configuration.
In the Configuration class, we have to define a method to create and return a particular
bean object, here the method is called Bean method and it must be marked with @Bean
annotation

Note: In the Configuration class, we have to declare a separate method for each and
every bean class.

By Default, the bean method name is acting as an id value for the bean or if we want to
change the name of the bean identity then we have to provide a parameter to the
@Bean annotation.
EX: @Bean(“helloBean”)

Note: Once if we provide our own identity values to the bean like above then we must
use the same name to get the respective bean object from the Container, it is not
possible to use bean method name.

To recognize and to get bean configuration details from a Java class in Java based
configurations then we have to use a separate container class that is
“AnnotationConfigApplicationContext”, it is an implementation class to the
ApplicationContext interface.

EX:
ApplicationContext appCtx = new AnnotationConfigApplicationContext(
AppConfig.class);

When we execute the above instruction, AnnotationConfigApplicationContext is able to


perform the following actions.

1. AnnotationConfigApplicationContext will take the Configuration class .class file


name from the parameter.
2. It will search for the Configuration class, if it is identified then Container will
recognize @Configuration annotation and it will load and instantiate
Configuration class.
3. After the COnfiguration class instantiation , Container will recognize and execute
all the bean methods which are declared with @Bean annotation.
4. By the execution of all the bean methods, Container will create bean objects and
container will store all the generated bean objects along with their identity values.
Note: Container will search for the identity values in @Bean annotation first, if no
identity value is defined along with @Bean annotation then Container will take
bean method name as an identity value for the respective Bean.

5. After creating all the Bean objects, the container will manage all the bean objects
along with their respective identity values.

Note: The above process could be executed at the time of creating ApplicationContext
Container.

EX:
—---
Hello.java
package com.durgasoft.beans;

public class Hello {


public Hello(){
System.out.println("Hello Bean creating......");
}
public String sayHello(){
return "Hello User!";
}
}

Welcome.java
package com.durgasoft.beans;

public class Welcome {


public Welcome(){
System.out.println("Welcome Bean creating........");
}
public String sayWelcome(){
return "Welcome to Spring Framework!";
}
}

AppConfig.java
package com.durgasoft.config;

import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Welcome;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
static{
System.out.println("AppConfig Loading.......");
}
public AppConfig(){
System.out.println("AppConfig Instantiation.......");
}
@Bean
public Hello hello(){
System.out.println("Inside hello() method from
AppConfig.....");
Hello hello = new Hello();
return hello;
}

@Bean("welcomeBean")
public Welcome welcome(){
System.out.println("Inside welcome() method from
AppConfig.....");
Welcome welcome = new Welcome();
return welcome;
}
}

Main.java
import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Welcome;
import com.durgasoft.config.AppConfig;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicationCon
text;

public class Main {


public static void main(String[] args) {
System.out.println("Before ApplicationContext
startup.......");
ApplicationContext applicationContext = new
AnnotationConfigApplicationContext(AppConfig.class);
System.out.println("After ApplicationContext
startup........");

Hello hello = (Hello) applicationContext.getBean("hello");


System.out.println(hello.sayHello());

Welcome welcome = (Welcome)


applicationContext.getBean("welcomeBean");
System.out.println(welcome.sayWelcome());

}
}

Q)What advantages are we able to get from Java Based configurations over the XML
based Configurations?
—---------------------------------------------------------------------------------------------
Ans:
—---
1. No need for XML awareness.
2. XML based Configuration is required to perform XML loading, Parsing and
reading the content from XML file, it may take a lot of time, this process is not
required in java Based Configurations.
3. XML based Configurations required to manage more XML libraries internally, but
JAVA based configurations do not require XML libraries.
4. Java based configurations are able to reduce application execution time when
compared with XML based configurations.

Note: The limitation on Java based configurations is to provide more number


instructions for a single configuration in bean.

Note: If we want to provide more number of coinfigurations for a bean then it is


suggestible to use XML based configurations, if we have less number of configurations
for a bean then it is suggestible to use Java based configurations.

In Java based configurations , we are able to define scopes to the bean components by
using @Scope annotation.

Syntax: @Scope(“singleton/prototype”)

EX:
—--
Hello.java
package com.durgasoft.beans;

public class Hello {


public Hello(){
System.out.println("Hello Bean creating......");
}
public String sayHello(){
return "Hello User!";
}
}

Welcome.java
package com.durgasoft.beans;

public class Welcome {


public Welcome(){
System.out.println("Welcome Bean creating........");
}
public String sayWelcome(){
return "Welcome to Spring Framework!";
}
}

AppConfig.java
package com.durgasoft.config;

import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Welcome;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class AppConfig {
@Scope("singleton")
@Bean
public Hello hello(){

Hello hello = new Hello();


return hello;
}
@Scope("prototype")
@Bean("welcomeBean")
public Welcome welcome(){

Welcome welcome = new Welcome();


return welcome;
}
}

Main.java
import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Welcome;
import com.durgasoft.config.AppConfig;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicationCon
text;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
AnnotationConfigApplicationContext(AppConfig.class);

Hello hello1 = (Hello) applicationContext.getBean("hello");


System.out.println(hello1);
Hello hello2 = (Hello) applicationContext.getBean("hello");
System.out.println(hello2);
Hello hello3 = (Hello) applicationContext.getBean("hello");
System.out.println(hello3);
System.out.println();

Welcome welcome1 = (Welcome)


applicationContext.getBean("welcomeBean");
System.out.println(welcome1);
Welcome welcome2 = (Welcome)
applicationContext.getBean("welcomeBean");
System.out.println(welcome2);
Welcome welcome3 = (Welcome)
applicationContext.getBean("welcomeBean");
System.out.println(welcome3);
}
}
Output:
Hello Bean creating......
com.durgasoft.beans.Hello@67d48005
com.durgasoft.beans.Hello@67d48005
com.durgasoft.beans.Hello@67d48005

Welcome Bean creating........


com.durgasoft.beans.Welcome@5876a9af
Welcome Bean creating........
com.durgasoft.beans.Welcome@7ec7ffd3
Welcome Bean creating........
com.durgasoft.beans.Welcome@5b239d7d

If we want to define user defined scopes to the bean components in Java Based
configurations then we have to use the following steps.

1. Prepare a Bean method for “CustomScopeConfigurer” with the following


implementation in Configuration class.
a. Create a CustomScopeConfigurer class object.
b. Add a Map contains a key-value pair, where key is scope name and Value
is Scope object.
c. Set Map object to the CustomScopeConfigurer.
2. Create Scope class by implementing Scope interface.
3. Create a ThreadLocale class.
4. Provide user defined scope to a bean by using @Scope annotation
On the top of the respective bean method.

5. Access bean object in test class and access business method.

EX:
—--
Wish.java
package com.durgasoft.beans;

public class Wish {


public Wish(){
System.out.println("Wish Bean is creating......");
}
public String sayWish() {
return "Hello User, Good Morninig!";
}
}

Welcome.java
package com.durgasoft.beans;

public class Welcome {


public Welcome(){
System.out.println("Welcome Bean creating........");
}
public String sayWelcome(){
return "Welcome to Spring Framework!";
}
}

Hello.java
package com.durgasoft.beans;

public class Hello {


public Hello(){
System.out.println("Hello Bean creating......");
}
public String sayHello(){
return "Hello User!";
}
}

MyThreadLocale.java
package com.durgasoft.scope;

import java.util.HashMap;
import java.util.Map;

public class MyThreadLocale extends ThreadLocal{


@Override
protected Object initialValue() {
Map scope = new HashMap();
return scope;
}
}
ThreadSCope.java
package com.durgasoft.scope;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.Map;

public class ThreadScope implements Scope {


MyThreadLocale myThreadLocale = new MyThreadLocale();
Map scope;
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
scope = (Map) myThreadLocale.get();
Object obj = scope.get(name);
if(obj == null){
obj = objectFactory.getObject();
scope.put(name, obj);
}
return obj;
}

@Override
public Object remove(String name) {
Object obj = scope.remove(name);
return obj;
}

@Override
public void registerDestructionCallback(String s, Runnable
runnable) {

@Override
public Object resolveContextualObject(String s) {
return null;
}

@Override
public String getConversationId() {
return null;
}
}

AppConfig.java
package com.durgasoft.config;

import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Welcome;
import com.durgasoft.beans.Wish;
import com.durgasoft.scope.ThreadScope;
import
org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class AppConfig {

@Scope("singleton")
@Bean
public Hello hello(){
Hello hello = new Hello();
return hello;
}

@Scope("prototype")
@Bean("welcomeBean")
public Welcome welcome(){
Welcome welcome = new Welcome();
return welcome;
}

@Scope("thread")
@Bean
public Wish wish(){
Wish wish = new Wish();
return wish;
}
@Bean
public CustomScopeConfigurer scopeConfigurer(){
CustomScopeConfigurer customScopeConfigurer = new
CustomScopeConfigurer();
Map map = new HashMap();
map.put("thread", new ThreadScope());
customScopeConfigurer.setScopes(map);
return customScopeConfigurer;
}

Main.java
import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Welcome;
import com.durgasoft.beans.Wish;
import com.durgasoft.config.AppConfig;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicationCon
text;

public class Main {


public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new
AnnotationConfigApplicationContext(AppConfig.class);

Hello hello1 = (Hello) applicationContext.getBean("hello");


System.out.println(hello1);
Hello hello2 = (Hello) applicationContext.getBean("hello");
System.out.println(hello2);
Hello hello3 = (Hello) applicationContext.getBean("hello");
System.out.println(hello3);
System.out.println();

Welcome welcome1 = (Welcome)


applicationContext.getBean("welcomeBean");
System.out.println(welcome1);
Welcome welcome2 = (Welcome)
applicationContext.getBean("welcomeBean");
System.out.println(welcome2);
Welcome welcome3 = (Welcome)
applicationContext.getBean("welcomeBean");
System.out.println(welcome3);
System.out.println();

new Thread(()->{
Wish wish1 = (Wish) applicationContext.getBean("wish");
System.out.println("Thread1 : "+wish1);
Wish wish2 = (Wish) applicationContext.getBean("wish");
System.out.println("Thread1 : "+wish2);

}).start();

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
new Thread(()->{
Wish wish3 = (Wish) applicationContext.getBean("wish");
System.out.println("Thread2 : "+wish3);
Wish wish4 = (Wish) applicationContext.getBean("wish");
System.out.println("Thread2 : "+wish4);

}).start();
}
}

Beans Lifecycle:
—-------------------
In spring applications, Beans are having their own life cycle states.
1. Bean Loading
2. Bean Instantiation
3. Bean Initialization
4. Bean Destruction

Bean Loading:
—-----------------
In Spring applications, when the ApplicationContext container is started, automatically,
ApplicationContext will recognize all the bean configurations in the Configuration file or
in the Configuration class object. ApplicationContext will load all the bean classes
bytecode to the memory by using the following method.
public static Class forName(String beanClass)throws ClassNotFoundException
EX:Class cls = Class.forName(“com.durgasoft.beans.Welcome”);

2. Bean Instantiation:
—--------------------------
After loading bean classes bytecode to the memory, ApplicationContext container will
create objects for the bean classes.

In Spring , there are three ways to perform bean instantiation.


1. By Using Bean constructors
2. By Using Static Factory Method
3. By Using Instance Factory Method

Bean Instantiation through Constructor:


—--------------------------------------------------
If we define a 0-arg constructor or parameterized constructor in the bean class then
ApplicationContext will create a bean object by executing the respective bean class
constructor only.

Hello.java
public class Hello{
public Hello(){
—-----
}
}

SpringConfig.xml
<beans>
<bean id=”hello” class=”com.durgasoft.beans.Hello”/>

</beans>

Test.java
ApplicationContext appContext = new
ClassPathXmlApplicationContext(“SpringConfig.xmnl”);

If we want to execute a parameterized constructor in Bean Instantiation then we have to


use the following steps.
1. Define Bean class with a Parameterized constructor.
2. Configure Constructor parameters in bean configuration in Spring configuration
file.
3. Start ApplicationContext in Test class.

EX:
Welcome.java
public class Welcome{
private String name;
Private String message;

public Welcome(String name, String message){


this.name = name;
this.message = message;
}
—---
}

SpringConfig.xml
<beans>
<bean id=”welcome” class=”com.durgasoft.beans.Welcome”>
<constructor-arg value=”Durga”/>
<constructor-arg value=”Welcome To Durgasoft”/>
</bean>
</beans>

Test.java
ApplicationContext appContext = new
ClassPathXmlApplicationContext(“SpringConfig.xmnl”);

EX
—---
Hello.java
package com.durgasoft.beans;

public class Hello {


public Hello(){
System.out.println("Hello Object is creating......");
}
public String sayHello(){
return "Hello User!";
}
}

Welcome.java
package com.durgasoft.beans;

public class Welcome {


private String name;
private String message;

public Welcome(String name, String message){


this.name = name;
this.message = message;
System.out.println("Welcome Bean is Creating.....");
}
public String sayWelcome(){
return "Hello "+name+", "+message;
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.durgasoft.beans.Hello"/>
<bean id="welcome" class="com.durgasoft.beans.Welcome">
<constructor-arg value="Durga"/>
<constructor-arg value="Good Morning!"/>
</bean>
</beans>

Main.java
import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Welcome;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");

Hello hello = (Hello) applicationContext.getBean("hello");


System.out.println(hello.sayHello());

Welcome welcome = (Welcome)


applicationContext.getBean("welcome");
System.out.println(welcome.sayWelcome());

}
}

Bean Instantiation By Using Static Factory Method:


—-----------------------------------------------------------------
If we want to create a Bean object by using static factory method then we have to define
a static method[Static Factory method] in the bean class and it must return the current
bean object reference.

After defining a static factory method in Bean class we have to configure static factory
method in bean definition inside spring configuration file by using “factory-method”
attribute in <bean> tag.

Hello.java
public class Hello{
public Hello(){
—---
}
public static Hello getInstance(){
return new Hello();
}
—------
}

SpringConfig.xml
<beans>
<bean id=”hello” class=”com.durgasoft.beans.Hello”
factory-method=” getInstance”/>
</beans>
Test.java
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext(“SpringConfig.xml”);

Bean Instantiation by using INstance Factory Method:


—----------------------------------------------------------------------
1. Declare a Bean class
2. Declare a Factory class.
3. Declare an instance factory method inside factory class.
4. Declare Factory class as bean in Spring configuration file.
5. Configure Factory class and Factory method in bean definition in spring
configuration file.

EX:
public class Welcome{
}

Public class WelcomeFactory{


public Welcome getWelcomeInstance(){
return new Welcome();
}
}

<beans>
<bean id=”welcome” class=”com.durgasoft.beans.Welcome”
factory-method=”getWelcomeInstance” factory-bean=”welcomeFactory”>
<bean id=”welcomeFactory” class=”com.durgasoft.beans.WelcomeFactory”/>
</beans>

Test.java
—--------
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext(“SpringConfig.xml”);

EX:
—--
Hello.java
package com.durgasoft.beans;
public class Hello {
static Hello getInstance(){
System.out.println("from getInstance() Method, creating Hello
bean object......");
return new Hello();
}
public Hello(){
System.out.println("from 0-ARg constructor....");
}
public String sayHello(){
return "Hello User!";
}
}

Welcome.java
package com.durgasoft.beans;

public class Welcome {


public String sayWelcome(){
return "Hello User, Welcome to Spring!";
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.durgasoft.beans.Hello"
factory-method="getInstance"/>
<bean id="welcome" class="com.durgasoft.beans.Welcome"
factory-method="getWelcomeInstance" factory-bean="welcomeFactory"/>
<bean id="welcomeFactory"
class="com.durgasoft.factory.WelcomeFactory"/>

</beans>

WelcomeFactory.java
package com.durgasoft.factory;

import com.durgasoft.beans.Welcome;
public class WelcomeFactory {
public Welcome getWelcomeInstance(){
System.out.println("From getWelcomeInstance() method creating
Welcome Bean Object....");
return new Welcome();
}
}

Main.java
import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Welcome;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");

Hello hello = (Hello) applicationContext.getBean("hello");


System.out.println(hello.sayHello());

Welcome welcome = (Welcome)


applicationContext.getBean("welcome");
System.out.println(welcome.sayWelcome());

}
}

Bean Initialization And Destruction:


—--------------------------------------------
In Spring applications, After the Bean instantiation, Container must provide initial values
inside the bean object, providing initial values inside the bean object is called “Bean
Initialization”.

In Spring applications, after executing the business logic, Container has to destroy bean
objects , here destroying bean objects is called “Bean Destruction”.

In Spring applications, to destroy bean objects explicitly by the container we have to use
the following instruction.
applicationContext.registerShutdownHook();

Note: To use registerShutdownHook() method we have to use the


AbstractApplicationContext container in place of ApplicationContext.
EX: AbstractApplicationContext applicationContext = new
ClassPathXmlApplicationContext(“SpringConfig.xml”);

In Spring applications there are three ways to perform Bean Initialization and
Destruction .

1. By Using custom initialization and Destruction methods.


2. By Using InitializingBean and DisposableBean callback interfaces.
3. By Using @PostConstruct and @Predestroy annotations

Bean Initialization and Destruction By Using custom initialization and Destruction


methods:
—-------------------------------------------------------------------------------------------
IN this approach, we have to define methods for initializing beans and destroying beans
in the bean class and we have to declare them in the bean configuration in the Spring
Configuration File by using “init-method” and “destroy-method” attributes in <bean> tag..
EX:
—--
public class Hello{
public void init(){
}
public void destroy(){
}
—---
}

SpringConfig.xml
<beans>
<bean id=”hello” class=”com.durgasoft.beans.Hello” init-method=”init”
destroy-method=”destroy”/>
</beans>

In the above context, ApplicationContext will perform the bean lifecycle in the following
order.
1. Bean Loading
2. Bean Instantiation
3. Accessing setter methods
4. init() method execution
5. Business methods execution when we access them
6. As per the registerShutdownHook() method call, destroy() method execution …..

EX:
—--
Hello.java
package com.durgasoft.beans;

public class Hello {


private String name;

public void init(){


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

public void setName(String name) {


this.name = name;
System.out.println("setName().....");
}

public String getName() {


return name;
}

public String sayHello(){


return "Hello "+name;
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.durgasoft.beans.Hello"
init-method="init" destroy-method="destroy">
<property name="name" value="Durga"/>
</bean>
</beans>

Main.java
import com.durgasoft.beans.Hello;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.AbstractApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
AbstractApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Hello hello = (Hello) applicationContext.getBean("hello");
System.out.println(hello.sayHello());
applicationContext.registerShutdownHook();
}
}

In Spring applications, if we have more than one bean class and each and every bean
class contains the same initialization method and the same destruction method then it is
not required configure init-method and destroy-method at each and every bean
definition in spring configuration file, commonly we can configure init method and
destroy method at <beans> tag by using default-init-method and default-destroy-method
once then it will be applicable to all the beans configurations in spring configuration file.

EX:
—--
Welcome.java
package com.durgasoft.beans;

public class Welcome {


private String name;

public void setName(String name) {


this.name = name;
}
public String getName() {
return name;
}

public void init(){


System.out.println("init()-Welcome class.....");
}
public void destroy(){
System.out.println("destroy()-Welcome class.....");
}
public String sayWelcome(){
return "Hello "+name+" , Welcome To Durgasoft";
}
}

Hello.java
package com.durgasoft.beans;

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

public class Hello {


private String name;
public void setName(String name) {
this.name = name;
System.out.println("setName().....");
}
public String getName() {
return name;
}
public void init(){
System.out.println("init()-Hello class.....");
}
public void destroy(){
System.out.println("destroy()-Hello class......");
}
public String sayHello(){
return "Hello "+name;
}

}
Wish.java
package com.durgasoft.beans;

public class Wish {


private String name;

public void setName(String name) {


this.name = name;
}

public String getName() {


return name;
}

public void init(){


System.out.println("init()-Wish class.....");
}
public void destroy(){
System.out.println("destroy()-Wish......");
}
public String sayWish(){
return "Hello "+name+", Good Morning";
}
}

SpringConfig.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd"
default-init-method="init" default-destroy-method="destroy"
>
<context:annotation-config/>
<bean id="hello" class="com.durgasoft.beans.Hello" >
<property name="name" value="Durga"/>
</bean>
<bean id="welcome" class="com.durgasoft.beans.Welcome" >
<property name="name" value="Durga"/>
</bean>
<bean id="wish" class="com.durgasoft.beans.Wish" >
<property name="name" value="Durga"/>
</bean>
</beans>

Main.java
import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Welcome;
import com.durgasoft.beans.Wish;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.AbstractApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
AbstractApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");

Hello hello = (Hello) applicationContext.getBean("hello");


System.out.println(hello.sayHello());
System.out.println();

Welcome welcome = (Welcome)


applicationContext.getBean("welcome");
System.out.println(welcome.sayWelcome());
System.out.println();

Wish wish = (Wish) applicationContext.getBean("wish");


System.out.println(wish.sayWish());

applicationContext.registerShutdownHook();
}
}

Op:
setName().....
init()-Hello class.....
init()-Welcome class.....
init()-Wish class.....
Hello Durga

Hello Durga , Welcome To Durgasoft

Hello Durga, Good Morning


destroy()-Wish......
destroy()-Welcome class.....
destroy()-Hello class......

Q)IN the spring applications, if we provide initialization methods and destruction


methods at both <beans> tag and <bean> tag for a bean with different methods then
which methods will be executed by the applicationContext in bean initialization and in
bean destruction?
—----------------------------------------------------------------------------------------------
Ans:
—---
IN Spring applications, ApplicationContext will check initialization method and
destruction method configuration at <bean> tag first, if they are not available at <bean>
tag then ApplicationContext will search for them in <beans> tag.

EX:
—--
Hello.java
package com.durgasoft.beans;

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

public class Hello {


private String name;
public void setName(String name) {
this.name = name;
System.out.println("setName().....");
}
public String getName() {
return name;
}
public void init1(){
System.out.println("init1()-Hello class.....");
}
public void destroy1(){
System.out.println("destroy1()-Hello class......");
}

public void init2(){


System.out.println("init2()-Hello class.....");
}
public void destroy2(){
System.out.println("destroy2()-Hello class......");
}

public String sayHello(){


return "Hello "+name;
}

SpringConfig.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd"
default-init-method="init1" default-destroy-method="destroy1"
>
<context:annotation-config/>
<bean id="hello" class="com.durgasoft.beans.Hello"
init-method="init2" destroy-method="destroy2">
<property name="name" value="Durga"/>
</bean>

</beans>

Main.java
import com.durgasoft.beans.Hello;
import
org.springframework.context.support.AbstractApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
AbstractApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");

Hello hello = (Hello) applicationContext.getBean("hello");


System.out.println(hello.sayHello());
System.out.println();

applicationContext.registerShutdownHook();
}
}

Op:

setName().....
init2()-Hello class.....
Hello Durga

destroy2()-Hello class....

Bean Initialization and Destruction by using InitializingBean and DisposableBean


callback interfaces:
—-----------------------------------------------------------------------------------
Where InitializingBean callback interface has the following method , it will be executed
by the ApplicationContext container automatically when the container is performing
bean initialization.

public void afterPropertiesSet()

Where DisposableBean callback interface has the following method, it will be executed
by the container automatically when the container performs Bean Destruction.

public void destroy()


If we use the above callback interfaces in the bean class then the ApplicationContext
container is able to perform the bean lifecycle like below.

1. Bean Loading
2. Bean Instantiation
3. setXxx() methods execution
4. afterPropertiesSet()......
5. Business methods execution
6. destroy()..... As per registerShutdownHook() method call.

EX:
Hello.java
package com.durgasoft.beans;

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

public class Hello implements InitializingBean, DisposableBean {


private String name;

public void setName(String name) {


this.name = name;
System.out.println("setName().....");
}

public String getName() {


return name;
}

public String sayHello(){


return "Hello "+name;
}

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("AfterPropertiesSet().......");
}

@Override
public void destroy() throws Exception {
System.out.println("destroy().....");
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.durgasoft.beans.Hello" >
<property name="name" value="Durga"/>
</bean>
</beans>

Main.java
import com.durgasoft.beans.Hello;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.AbstractApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
AbstractApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Hello hello = (Hello) applicationContext.getBean("hello");
System.out.println(hello.sayHello());
applicationContext.registerShutdownHook();
}
}
Bean Initialization And Destruction by using @PostConstruct and @Predestroy
annotations:
—---------------------------------------------------------------------------------------
@PostConstruct and @Predestroy annotations are defined by javax.annotation
package.

In Bean classes, the initialization method declared with @PostConstruct will be


executed immediately after bean instantiation.
In Bean classes, the destruction method declared with @Predestroy will be executed
just before destroying bean object.

EX:
Hello.java
package com.durgasoft.beans;

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

public class Hello {


private String name;

@PostConstruct
public void initialize(){
System.out.println("initialize()......");
}
@PreDestroy
public void destruction(){
System.out.println("destruction().......");
}
public void setName(String name) {
this.name = name;
System.out.println("setName().....");
}

public String getName() {


return name;
}

public String sayHello(){


return "Hello "+name;
}

SpringConfig.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="hello" class="com.durgasoft.beans.Hello" >
<property name="name" value="Durga"/>
</bean>
</beans>

Main.java
import com.durgasoft.beans.Hello;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.AbstractApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
AbstractApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Hello hello = (Hello) applicationContext.getBean("hello");
System.out.println(hello.sayHello());
applicationContext.registerShutdownHook();
}
}

Note: @PostConstruct and @Predestroy annotations are deprecated from JDK1.9


version onwards.

Q)In Spring applications, if we use all the initialization mechanisms and destruction
mechanisms in a single bean then in which order all the initialization methods are
executed and in which order all the destruction methods are executed?
—------------------------------------------------------------------------------------------------
Ans:
—---
Initialization Order:
1. Initialization method with @PostConstruct
2. afterPropertiesSet() from InitializingBean callback interface.
3. Custom init method.

Destruction Order:
1. Destruction method with @Predestroy
2. destroy() method from DisposableBean callback interface.
3. Custom destruction method.

Hello.java
package com.durgasoft.beans;

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

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

public class Hello implements InitializingBean, DisposableBean {


static {
System.out.println("Bean Loading.....");
}
public Hello(){
System.out.println("Bean Instantiation though
Constructor...");
}
private String name;
public void setName(String name) {
this.name = name;
System.out.println("setName().....");
}
public String getName() {
return name;
}
public void init1(){
System.out.println("init1()-Hello class.....");
}
public void destroy1(){
System.out.println("destroy1()-Hello class......");
}
public void afterPropertiesSet(){

System.out.println("afterPropertiesSet()-InitializingBean-Hello Bean
class.....");
}
public void destroy(){
System.out.println("destroy()-DisposableBean - Hello Bean
class......");
}

@PostConstruct
public void initialize(){
System.out.println("initialize() - @PostConstruct - Hello Bean
class......");
}

@PreDestroy
public void destruction(){
System.out.println("destruction() - @Predestroy - Hello Bean
class.......");
}
public String sayHello(){
return "Hello "+name;
}

SpringConfig.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd"

>
<context:annotation-config/>
<bean id="hello" class="com.durgasoft.beans.Hello"
init-method="init1" destroy-method="destroy1">
<property name="name" value="Durga"/>
</bean>

</beans>

Main.java
import com.durgasoft.beans.Hello;
import
org.springframework.context.support.AbstractApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
AbstractApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");

Hello hello = (Hello) applicationContext.getBean("hello");


System.out.println(hello.sayHello());
System.out.println();
applicationContext.registerShutdownHook();
}
}

Output:
Bean Loading.....
Bean Instantiation though Constructor...
setName().....
initialize() - @PostConstruct - Hello Bean class......
afterPropertiesSet()-InitializingBean-Hello Bean class.....
init1()-Hello class.....
Hello Durga

destruction() - @Predestroy - Hello Bean class.......


destroy()-DisposableBean - Hello Bean class......
destroy1()-Hello class......

Bean Inheritance:
—---------------------
In general, in Spring applications we are able to provide more beans as per the
requirement, in this case we must configure all beans in the bean configuration file.
In the above context, there may be a chance to have the common configuration details
in all the beans , here to reduce duplicate beans configuration we are able to inherit one
bean configuration to another bean configuration in order to improve reusability.

IN Spring configuration file, if we want to get a bean configuration details into another
bean configuration then we have to use the “parent” attribute in the child bean definition
with the id value of the parent bean.

<beans>
<bean id=”bean1” ….>
—----
</bean>
<bean id=”bean2” parent=”bean1”>
—---
</bean>
</beans>

After defining parent-child relation between bean definitions, it is possible to override


parent bean configuration details in the child bean definition by using the <property>
tags .

EX:
—--
Wish.java
package com.durgasoft.beans;

public class Wish {


private String name;
private String message;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getMessage() {


return message;
}
public void setMessage(String message) {
this.message = message;
}

public String sayWish(){


return "Mr "+name+", "+message;
}
}

Hello.java
package com.durgasoft.beans;

public class Hello {


private String name;
private String message;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getMessage() {


return message;
}

public void setMessage(String message) {


this.message = message;
}

public String sayHello(){


return "Hello "+name+", "+message;
}
}

Hi.java
package com.durgasoft.beans;
public class Hi {
private String name;
private String message;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getMessage() {


return message;
}
public void setMessage(String message) {
this.message = message;
}
public String sayHi(){
return "Hi "+name+", "+message;
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="wish" class="com.durgasoft.beans.Wish">
<property name="name" value="Durga"/>
<property name="message" value="Good Morning!"/>
</bean>
<bean id="hello" class="com.durgasoft.beans.Hello" parent="wish">
<property name="name" value="Pavan"/>
</bean>
<bean id="hi" class="com.durgasoft.beans.Hi" parent="wish">
<property name="name" value="Vishnu"/>
</bean>

</beans>
Main.java
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Wish;
import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Hi;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");

Wish wish = (Wish)applicationContext.getBean("wish");


System.out.println(wish.sayWish());

Hello hello = (Hello) applicationContext.getBean("hello");


System.out.println(hello.sayHello());

Hi hi = (Hi) applicationContext.getBean("hi");
System.out.println(hi.sayHi());

}
}

Output:
Mr Durga, Good Morning!
Hello Pavan, Good Morning!
Hi Vishnu, Good Morning!

In the above application, in the Spring configuration file we can make parent definition
as an abstract definition that is template definition by using “abstract” attribute in
<bean> tag, its main purpose is to definit some configuration details in order to share
these details to the child definitions in the same spring configuration file, it doesn't
represent any bean class in the application.

Note: If we declare any bean definition as template definition then it is not required to
provide ‘class’ attribute in <bean> tag.

EX:
—--
Hello.java
package com.durgasoft.beans;

public class Hello {


private String name;
private String message;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getMessage() {


return message;
}

public void setMessage(String message) {


this.message = message;
}

public String sayHello(){


return "Hello "+name+", "+message;
}
}

Hi.java
—-------
package com.durgasoft.beans;

public class Hi {
private String name;
private String message;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String sayHi(){
return "Hi "+name+", "+message;
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="wish" abstract="true">
<property name="name" value="Durga"/>
<property name="message" value="Good Morning!"/>
</bean>
<bean id="hello" class="com.durgasoft.beans.Hello" parent="wish">
<property name="name" value="Pavan"/>
</bean>
<bean id="hi" class="com.durgasoft.beans.Hi" parent="wish">
<property name="name" value="Vishnu"/>
</bean>

</beans>

Main.java
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Hi;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Hello hello = (Hello) applicationContext.getBean("hello");
System.out.println(hello.sayHello());

Hi hi = (Hi) applicationContext.getBean("hi");
System.out.println(hi.sayHi());

}
}

Nested Beans:
—------------------
In general, in Spring applications, we may use more bean components as per the
requirement, in this case all the bean classes must be configured in the Spring
Configuration file.

In the above context, some bean components are associated with some other bea
components , that is, one bean class has the reference variable of another bean class,
in this case to configure beans and their relation we have to use Nested Beans.

Declaring one bean definition in another bean definition is called Nested bean.

Syntax:
<beans>
<bean id=”--” class=”--”>
—------
<property name=”--”>
<bean id=”---” class=”---”>
—-----
</bean>
</property>
</bean>
</beans>

EX:
—--
Account.java
package com.durgasoft.beans;

public class Account {


private String accNo;
private String accHolderName;
private String accType;
private int balance;

public String getAccNo() {


return accNo;
}

public void setAccNo(String accNo) {


this.accNo = accNo;
}

public String getAccHolderName() {


return accHolderName;
}

public void setAccHolderName(String accHolderName) {


this.accHolderName = accHolderName;
}

public String getAccType() {


return accType;
}

public void setAccType(String accType) {


this.accType = accType;
}

public int getBalance() {


return balance;
}

public void setBalance(int balance) {


this.balance = balance;
}
}

Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

private Account account;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}

public Account getAccount() {


return account;
}

public void setAccount(Account account) {


this.account = account;
}

public void getEmpDetails(){


System.out.println("Employee Details");
System.out.println("----------------------");
System.out.println("Employee Number : "+eno);
System.out.println("Employee Name : "+ename);
System.out.println("Employee Salary : "+esal);
System.out.println("Employee Address : "+eaddr);
System.out.println();
System.out.println("Account Details");
System.out.println("--------------------------");
System.out.println("Account Number :
"+account.getAccNo());
System.out.println("Account Holder Name :
"+account.getAccHolderName());
System.out.println("Account Type :
"+account.getAccType());
System.out.println("Account Balance :
"+account.getBalance());
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="employee" class="com.durgasoft.beans.Employee">
<property name="eno" value="111"/>
<property name="ename" value="Durga"/>
<property name="esal" value="50000"/>
<property name="eaddr" value="Hyd"/>
<property name="account">
<bean id="account" class="com.durgasoft.beans.Account">
<property name="accNo" value="abc123"/>
<property name="accHolderName" value="Durga N"/>
<property name="accType" value="Savings"/>
<property name="balance" value="60000"/>
</bean>
</property>
</bean>
</beans>

Main.java
import com.durgasoft.beans.Employee;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.ApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Employee employee =
applicationContext.getBean(Employee.class);
employee.getEmpDetails();
}
}

Output:
Employee Details
----------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000.0
Employee Address : Hyd

Account Details
--------------------------
Account Number : abc123
Account Holder Name : Durga N
Account Type : Savings
Account Balance : 60000

Note: The above requirement is possible with Dependency Injection also, nested beans
are not suggestible.

BeanPostProcessor:
—------------------------
The main intention of the BeanPostprocessor is to customize the bean initialization
process in Spring applications.
In the above context, we will customize the bean initialization by executing a set of
instructions before initialization of the bean and after initialization of the bean.

BeanPostProcessor is an interface provided by Spring framework and it has the


following two methods.

public Object postProcessBeforeInitialization(Object bean, String name)


It will be executed before bean initialization mechanisms , where we may use either of
the initialization mechanisms like custom bean initialization or InitializingBean call back
interface or@PostConstructor.

public Object postProcessAfterInitialization(Object bean, String name)


It will be executed after the initialization mechanisms , where we may use either of the
initialization mechanisms like custom bean initialization or InitializingBean call back
interface or@PostConstructor.

To use BeanPostProcessor in spring applications we have to use the following steps.


1. Declare BeanPostProcessor class :

public class BeanPostProcessorImpl implements BeanPostProcessor{


—------
}
2. Configure BeanPostProcessor in the Spring configuration File:

<beans>
—----
<bean class=”com.durgasoft.beans.BeanPostProcessorImpl”/>
—-----
</beans>

EX:
Institute.java
package com.durgasoft.beans;

public class Institute {


private String welcomeMessage;

public void setWelcomeMessage(String welcomeMessage) {


this.welcomeMessage = welcomeMessage;
}
public void init(){
System.out.println("Initialization Process......");
}
public void destroy(){
System.out.println("Destruction Process......");
}
public String sayWelcome(){
return "Hello User, "+welcomeMessage;
}
}

BeanPostProcessorImpl.java
package com.durgasoft.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class BeanPostProcessorImpl implements BeanPostProcessor {


@Override
public Object postProcessBeforeInitialization(Object bean, String
beanName) throws BeansException {

System.out.println("postProcessBeforeIntialization()-BeanPostProcesso
r");
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String
beanName) throws BeansException {

System.out.println("postProcessAfterIntialization()-BeanPostProcessor
");
return bean;
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="instutute" class="com.durgasoft.beans.Institute"
init-method="init" destroy-method="destroy">
<property name="welcomeMessage" value="Welcome To Durgasoft"/>
</bean>
<bean class="com.durgasoft.beans.BeanPostProcessorImpl"/>
</beans>

Main.java
import com.durgasoft.beans.Institute;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import
org.springframework.context.support.AbstractApplicationContext;
public class Main {
public static void main(String[] args) {
AbstractApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Institute institute =
applicationContext.getBean(Institute.class);
System.out.println(institute.sayWelcome());
applicationContext.registerShutdownHook();
}
}

EX:
—-
Account.java
package com.durgasoft.beans;

public class Account {


private String accNo;
private String accHolderName;
private String accType;
private int balance;

public String getAccNo() {


return accNo;
}

public void setAccNo(String accNo) {


this.accNo = accNo;
}

public String getAccHolderName() {


return accHolderName;
}

public void setAccHolderName(String accHolderName) {


this.accHolderName = accHolderName;
}

public String getAccType() {


return accType;
}

public void setAccType(String accType) {


this.accType = accType;
}

public int getBalance() {


return balance;
}

public void setBalance(int balance) {


this.balance = balance;
}

public void displayAccountDetails(){


System.out.println("Account Details");
System.out.println("--------------------------");
System.out.println("Account Number : "+accNo);
System.out.println("Account Holder Name : "+accHolderName);
System.out.println("Account Type : "+accType);
System.out.println("Account Balance : "+balance);
}
}

BeanPostProcessorImpl.java
package com.durgasoft.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class BeanPostProcessorImpl implements BeanPostProcessor {


@Override
public Object postProcessBeforeInitialization(Object bean, String
beanName) throws BeansException {
Account account = (Account) bean;
account.setAccType("Savings");
return account;
}

@Override
public Object postProcessAfterInitialization(Object bean, String
beanName) throws BeansException {
Account account = (Account) bean;
account.setBalance(25000);
return account;
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="account" class="com.durgasoft.beans.Account">
<property name="accNo" value="abc123"/>
<property name="accHolderName" value="Durga"/>
</bean>
<bean class="com.durgasoft.beans.BeanPostProcessorImpl"/>
</beans>

Main.java
import com.durgasoft.beans.Account;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Account account = applicationContext.getBean(Account.class);
account.displayAccountDetails();
}
}

In Spring Applications , BeanPostprocessor is applicable for all bean components which


we have used in our application.
EX:
—-
Hello.java
package com.durgasoft.beans;

public class Hello {


public void init(){
System.out.println("HelloBean-init()......");
}
public void destroy(){
System.out.println("HelloBean-destroy()......");
}
public String sayHello(){
return "Hello User!";
}
}

Welcome.java
package com.durgasoft.beans;

public class Welcome {


public void init(){
System.out.println("WelcomeBean-init()......");
}
public void destroy(){
System.out.println("WelcomeBean-destroy()......");
}
public String sayWelcome(){
return "Welcome To Durga Software Solutions";
}
}

Wish.java
package com.durgasoft.beans;

public class Wish {


public void init(){
System.out.println("WishBean-init()......");
}
public void destroy(){
System.out.println("WishBean-destroy()......");
}
public String sayWish(){
return "Hello User, Good Morning";
}
}

BeanPostProcessorImpl.java
package com.durgasoft.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class BeanPostProcessorImpl implements BeanPostProcessor {


@Override
public Object postProcessBeforeInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization() - for
"+beanName+"Bean");
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessAfterInitialization() - for
"+beanName+"Bean");
return bean;
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.durgasoft.beans.Hello"
init-method="init" destroy-method="destroy"/>
<bean id="welcome" class="com.durgasoft.beans.Welcome"
init-method="init" destroy-method="destroy"/>
<bean id="wish" class="com.durgasoft.beans.Wish"
init-method="init" destroy-method="destroy"/>
<bean class="com.durgasoft.beans.BeanPostProcessorImpl"/>
</beans>

Main.java
import com.durgasoft.beans.Hello;
import com.durgasoft.beans.Welcome;
import com.durgasoft.beans.Wish;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.AbstractApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
AbstractApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Hello hello = applicationContext.getBean(Hello.class);
System.out.println(hello.sayHello());

Welcome welcome = applicationContext.getBean(Welcome.class);


System.out.println(welcome.sayWelcome());

Wish wish = applicationContext.getBean(Wish.class);


System.out.println(wish.sayWish());

applicationContext.registerShutdownHook();

}
}

Output:
postProcessBeforeInitialization() - for helloBean
HelloBean-init()......
postProcessAfterInitialization() - for helloBean
postProcessBeforeInitialization() - for welcomeBean
WelcomeBean-init()......
postProcessAfterInitialization() - for welcomeBean
postProcessBeforeInitialization() - for wishBean
WishBean-init()......
postProcessAfterInitialization() - for wishBean
Hello User!
Welcome To Durga Software Solutions
Hello User, Good Morning
WishBean-destroy()......
WelcomeBean-destroy()......
HelloBean-destroy()......

In Spring applications, it is possible to provide more than one BeanPostProcessor.


EX:
Hello.java
package com.durgasoft.beans;

public class Hello {


public void init(){
System.out.println("init() Method......");
}
public void destroy(){
System.out.println("destroy() Method........");
}
public String sayHello(){
return "Hello User!";
}
}

BeanPostProcessorImpl1.java
package com.durgasoft.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class BeanPostProcessorImpl1 implements BeanPostProcessor {


@Override
public Object postProcessBeforeInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization() -
BeanPostProcessorImpl1");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessAfterInitialization() -
BeanPostProcessorImpl1");
return bean;
}
}

BeanPostProcessorImpl2.java
package com.durgasoft.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class BeanPostProcessorImpl2 implements BeanPostProcessor {


@Override
public Object postProcessBeforeInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization() -
BeanPostProcessorImpl2");
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessAfterInitialization() -
BeanPostProcessorImpl2");
return bean;
}
}

BeanPostProcessorImpl3.java
package com.durgasoft.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class BeanPostProcessorImpl3 implements BeanPostProcessor {


@Override
public Object postProcessBeforeInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization() -
BeanPostProcessorImpl3");
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessAfterInitialization() -
BeanPostProcessorImpl3");
return bean;
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.durgasoft.beans.Hello"
init-method="init" destroy-method="destroy"/>
<bean class="com.durgasoft.beans.BeanPostProcessorImpl1"/>
<bean class="com.durgasoft.beans.BeanPostProcessorImpl2"/>
<bean class="com.durgasoft.beans.BeanPostProcessorImpl3"/>
</beans>

Main.java
import com.durgasoft.beans.Hello;
import
org.springframework.context.support.AbstractApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
AbstractApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Hello hello = applicationContext.getBean(Hello.class);
System.out.println(hello.sayHello());
applicationContext.registerShutdownHook();
}
}

Output:
postProcessBeforeInitialization() - BeanPostProcessorImpl1
postProcessBeforeInitialization() - BeanPostProcessorImpl2
postProcessBeforeInitialization() - BeanPostProcessorImpl3
init() Method......
postProcessAfterInitialization() - BeanPostProcessorImpl1
postProcessAfterInitialization() - BeanPostProcessorImpl2
postProcessAfterInitialization() - BeanPostProcessorImpl3
Hello User!
destroy() Method........

In the above application, we are able to control the BeanPostProcessors execution


order by using the “Ordered” interface provided by Spring Framework.

If we want to use Ordered interface in Spring applications then we have to implement


Ordered interface at each and every BeanPostProcessor implementation class and
implement the following method.

public int getOrder()

EX:
—-
Hello.java
package com.durgasoft.beans;

public class Hello {


public void init(){
System.out.println("init() Method......");
}
public void destroy(){
System.out.println("destroy() Method........");
}
public String sayHello(){
return "Hello User!";
}
}

BeanPostProcessorImpl1.java
package com.durgasoft.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;

public class BeanPostProcessorImpl1 implements BeanPostProcessor,


Ordered {
@Override
public Object postProcessBeforeInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization() -
BeanPostProcessorImpl1");
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessAfterInitialization() -
BeanPostProcessorImpl1");
return bean;
}

@Override
public int getOrder() {
return 3;
}
}

BeanPostProcessorImpl2.java

package com.durgasoft.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;

public class BeanPostProcessorImpl2 implements BeanPostProcessor,


Ordered {
@Override
public Object postProcessBeforeInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization() -
BeanPostProcessorImpl2");
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessAfterInitialization() -
BeanPostProcessorImpl2");
return bean;
}

@Override
public int getOrder() {
return 2;
}
}

BeanPostProcessorImpl3.java
package com.durgasoft.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;

public class BeanPostProcessorImpl3 implements BeanPostProcessor,


Ordered {
@Override
public Object postProcessBeforeInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization() -
BeanPostProcessorImpl3");
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String
beanName) throws BeansException {
System.out.println("postProcessAfterInitialization() -
BeanPostProcessorImpl3");
return bean;
}

@Override
public int getOrder() {
return 1;
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.durgasoft.beans.Hello"
init-method="init" destroy-method="destroy"/>
<bean class="com.durgasoft.beans.BeanPostProcessorImpl1"/>
<bean class="com.durgasoft.beans.BeanPostProcessorImpl2"/>
<bean class="com.durgasoft.beans.BeanPostProcessorImpl3"/>
</beans>

Main.java
import com.durgasoft.beans.Hello;
import
org.springframework.context.support.AbstractApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
AbstractApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Hello hello = applicationContext.getBean(Hello.class);
System.out.println(hello.sayHello());
applicationContext.registerShutdownHook();
}
}

Output:
postProcessBeforeInitialization() - BeanPostProcessorImpl3
postProcessBeforeInitialization() - BeanPostProcessorImpl2
postProcessBeforeInitialization() - BeanPostProcessorImpl1
init() Method......
postProcessAfterInitialization() - BeanPostProcessorImpl3
postProcessAfterInitialization() - BeanPostProcessorImpl2
postProcessAfterInitialization() - BeanPostProcessorImpl1
Hello User!
destroy() Method........

BeanFactoryPostProcessor:
—-----------------------------------
It can be used to change/Override the property values in the spring configuration file.

If we use BeanFactoryPostProcessor in Spring applications then we have to use the


following steps.
1. Prepare an user defined class as an implementation class to
BeanFactoryPostProcessor interface.
2. Implement postProcessBeanFactory() method .
a. Get Bean Definition.
b. Get MutablePropertyValues.
c. Add a property with the new message.
3. COnfigure BeanFactoryPostprocessor in Spring Configuration File.

EX:
—-
Wish.java
package com.durgasoft.beans;

public class Wish {


private String wishMessage;

public void setWishMessage(String wishMessage) {


this.wishMessage = wishMessage;
System.out.println("from setWishMessage()-Wish
Bean...."+wishMessage);
}
public String sayWish(){
return "Hello User, "+wishMessage;
}
}
BeanFactoryPostprocessorImpl.java
package com.durgasoft.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import
org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import
org.springframework.beans.factory.config.ConfigurableListableBeanFact
ory;

import java.time.LocalTime;

public class BeanFactoryPostProcessorImpl implements


BeanFactoryPostProcessor {

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory
configurableListableBeanFactory) throws BeansException {
BeanDefinition beanDefinition =
configurableListableBeanFactory.getBeanDefinition("wish");
MutablePropertyValues mutablePropertyValues =
beanDefinition.getPropertyValues();
String wishMessage = "";
LocalTime localTime = LocalTime.now();
int hour = localTime.getHour();
if(hour < 12){
wishMessage = "Good Morning!";
}else if(hour < 17){
wishMessage = "Good Afternoon!";
}else{
wishMessage = "Good Evening!";
}

mutablePropertyValues.addPropertyValue("wishMessage",wishMessage);
System.out.println("from
postProcessBeanFactory()-BeanFactoryPostProcessorImpl");
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="wish" class="com.durgasoft.beans.Wish">
<property name="wishMessage" value="Good Morning!"/>
</bean>
<bean class="com.durgasoft.beans.BeanFactoryPostProcessorImpl"/>
</beans>
Main.java
import com.durgasoft.beans.Wish;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Wish wish = applicationContext.getBean(Wish.class);
System.out.println(wish.sayWish());
}
}

Output:
from postProcessBeanFactory()-BeanFactoryPostProcessorImpl
from setWishMessage()-Wish Bean....Good Morning!
Hello User, Good Morning!

BeanFactoryPostProcess is able to override the property values at the time of reading


bean configurations from SpringConfiguration file and before executing setXXX()
methods of the bean class.

Note: In Spring Framework, AOP and some other Annotations like @Required,
@Transdactional,.... Are defined on the basis of BeanPostProcessors only.
Inversion Of Control:
------------------------
Inversion Of Control is a Design Pattern , it is able to provide all the application required
services automatically without receiving any request from the application.

There are two forms to provide Inversion of Control.


1. Dependency Lookup
2. Dependency Injection

1. Dependency Lookup:
--------------------------------
In this approach , Service providers will create the required Services and they will
manage the services either in some other registry software or in its own container and
ask the Consumer to lookup the required services.

There are two types of Dependency Lookup.


1. Dependency Pull
2. Contextualized Dependency Lookup

1. Dependency Pull:
--------------------------
In this approach, Service providers will create the services and make available that
service in a registry and ask the consumer to pull the services.

EX: JNDI is a middleware service , it is able to share all the resources throughout the
applications if we define them in the JNDI.
EX: IN RMI, Registry Application will create Remote objects and keep them in the
RMIRegistry, where all the client applications will get the remote object by performing
lookup operation over the RMIRegistry.

Contextualized Dependency Lookup:


-------------------------------------------------
In this approach, Service providers will create the services and services will be provided
in their own container and it will make all the client to use the provided Services.

EX:
----
In general, in web applications, Servlet Container will create ServletContext object at
the time of application deployment and Servlet Container is able to manage
ServletContext object , here Servlet applications has to get ServletContext object by
using getServletContext() method.

Dependency Injection:
-----------------------------
In this approach, Service provider will create the services and service provider will send
the services to the main application directly.

EX:
In Servlet application execution, the container will execute Servlet classes by its
lifecycle, where in Request Processing phase Container will access service() method in
order to process the request, to access service() method container must create and
pass request and response objects, it is called as "Dependency Injection".

public void service(ServletRequest request, ServletResponse response)throws


ServletException, IOException
There are two types of Dependency Injection:
1. Constructor Dependency Injection
2. Setter Method Dependency Injection

1. Constructor Dependency Injection:


--------------------------------------------------
The process of injecting a dependency object through a constructor is called
"Constructor Dependency Injection".

If we want to implement Constructor Dependency Injection in Spring applications we


have to use the following tags in the Spring Configuration file under <bean> tag.
<beans>
<bean id=”--” class=”--”>
<constructor-arg value=”--” name=”--” index=”---”/>
</bean>
</beans>

EX:
Customer.java
package com.durgasoft.beans;

public class Customer {


private String customerId;
private String customerName;
private String customerAddress;
private String customerMobileNo;

public Customer(String customerId, String customerName, String


customerAddress, String customerMobileNo) {
this.customerId = customerId;
this.customerName = customerName;
this.customerAddress = customerAddress;
this.customerMobileNo = customerMobileNo;
}
public void displayCustomerDetails(){
System.out.println("Customer Details");
System.out.println("-----------------------");
System.out.println("Customer Id : "+customerId);
System.out.println("Customer Name : "+customerName);
System.out.println("Customer Address : "+customerAddress);
System.out.println("Customer Mobile No : "+customerMobileNo);
}
}

Item.java
package com.durgasoft.beans;

public class Item {


private String itemId;
private String itemName;
private int itemPrice;

public Item(String itemId, String itemName, int itemPrice) {


this.itemId = itemId;
this.itemName = itemName;
this.itemPrice = itemPrice;
}

public void displayItemDetails(){


System.out.println("Item Details");
System.out.println("--------------------");
System.out.println("Item Id : "+itemId);
System.out.println("Item Name : "+itemName);
System.out.println("Item Proce : "+itemPrice);
}
}

Order.java
package com.durgasoft.beans;

public class Order {


private String orderId;
private String orderName;
private Customer customer;
private Item item;

public Order(String orderId, String orderName, Customer customer,


Item item) {
this.orderId = orderId;
this.orderName = orderName;
this.customer = customer;
this.item = item;
}

public void displayOrderDetails(){


System.out.println("Order Details");
System.out.println("-------------------");
System.out.println("Order Id : "+orderId);
System.out.println("Order Name : "+orderName);
System.out.println();
customer.displayCustomerDetails();
System.out.println();
item.displayItemDetails();
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="customer" class="com.durgasoft.beans.Customer">


<constructor-arg value="C111" name="customerId"/>
<constructor-arg value="Durga" name="customerName"/>
<constructor-arg value="S R nagar, Hyd-38"
name="customerAddress"/>
<constructor-arg value="9988776655" name="customerMobileNo"/>
</bean>
<bean id="item" class="com.durgasoft.beans.Item">
<constructor-arg name="itemId" value="I-111"/>
<constructor-arg name="itemName" value="Mobile"/>
<constructor-arg name="itemPrice" value="25000"/>
</bean>
<bean id="order" class="com.durgasoft.beans.Order">
<constructor-arg name="orderId" value="O-111"/>
<constructor-arg name="orderName" value="Mobile-Order"/>
<constructor-arg name="customer" ref="customer"/>
<constructor-arg name="item" ref="item"/>
</bean>
</beans>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Order;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Order order = applicationContext.getBean(Order.class);
order.displayOrderDetails();
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app06</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-conte
xt -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>

</dependencies>
</project>

2. Setter Method Dependency Injection:


-----------------------------------------------------
The process of injecting a dependency object through its respective setter method is
called "Setter Method Dependency Injection".

EX:
Item.java
package com.durgasoft.beans;

public class Item {


private String itemId;
private String itemName;
private int itemPrice;

public String getItemId() {


return itemId;
}

public void setItemId(String itemId) {


this.itemId = itemId;
}

public String getItemName() {


return itemName;
}

public void setItemName(String itemName) {


this.itemName = itemName;
}

public int getItemPrice() {


return itemPrice;
}

public void setItemPrice(int itemPrice) {


this.itemPrice = itemPrice;
}
}

Cart.java
package com.durgasoft.beans;

public class Cart {


private String cartId;
private String cartName;
private Item item;

public String getCartId() {


return cartId;
}

public void setCartId(String cartId) {


this.cartId = cartId;
}

public String getCartName() {


return cartName;
}
public void setCartName(String cartName) {
this.cartName = cartName;
}

public Item getItem() {


return item;
}

public void setItem(Item item) {


this.item = item;
}

public void displayCartDetails(){


System.out.println("Cart Details");
System.out.println("-------------------");
System.out.println("Cart Id : "+cartId);
System.out.println("Cart Name : "+cartName);
System.out.println();
System.out.println("Item Details");
System.out.println("----------------");
System.out.println("Item Id : "+item.getItemId());
System.out.println("Item Name : "+item.getItemName());
System.out.println("Item Price : "+item.getItemPrice());
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="item" class="com.durgasoft.beans.Item">
<property name="itemId" value="I-111"/>
<property name="itemName" value="MI Mobile"/>
<property name="itemPrice" value="25000"/>
</bean>
<bean id="cart" class="com.durgasoft.beans.Cart">
<property name="cartId" value="C-111"/>
<property name="cartName" value="Mobile-Cart"/>
<property name="item" ref="item"/>
</bean>
</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app07</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Cart;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Cart cart = applicationContext.getBean(Cart.class);
cart.displayCartDetails();
}
}

EX:
Review.java
package com.durgasoft.beans;

public class Review {


private String reviewId;
private String criticsName;
private String description;
private float rating;

public float getRating() {


return rating;
}

public void setRating(float rating) {


this.rating = rating;
}

public String getCriticsName() {


return criticsName;
}

public void setCriticsName(String criticsName) {


this.criticsName = criticsName;
}

public String getReviewId() {


return reviewId;
}
public void setReviewId(String reviewId) {
this.reviewId = reviewId;
}

public String getDescription() {


return description;
}

public void setDescription(String description) {


this.description = description;
}
}

Movie.java
package com.durgasoft.beans;

public class Movie {


private String movieId;
private String movieName;
private Review review;

public String getMovieId() {


return movieId;
}

public void setMovieId(String movieId) {


this.movieId = movieId;
}

public String getMovieName() {


return movieName;
}

public void setMovieName(String movieName) {


this.movieName = movieName;
}

public Review getReview() {


return review;
}

public void setReview(Review review) {


this.review = review;
}

public void getMovieDetails(){


System.out.println("Movie Details");
System.out.println("----------------------");
System.out.println("Movie Id : "+movieId);
System.out.println("Movie Name : "+movieName);
System.out.println("Review Details");
System.out.println("-----------------------");
System.out.println("Review Id : "+review.getReviewId());
System.out.println("Critics Name: "+review.getCriticsName());
System.out.println("Description : "+review.getDescription());
System.out.println("Rating : "+review.getRating());

}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Movie;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Movie movie = (Movie) applicationContext.getBean("movie");
movie.getMovieDetails();
}
}

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="review" class="com.durgasoft.beans.Review">
<property name="reviewId" value="R-111"/>
<property name="criticsName" value="Durga"/>
<property name="description" value="Blockbuster"/>
<property name="rating" value="4.0"/>
</bean>
<bean id="movie" class="com.durgasoft.beans.Movie">
<property name="movieId" value="M-111"/>
<property name="movieName" value="PUSHPA"/>
<property name="review" ref="review"/>
</bean>
</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app08</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
Different Types of Elements Dependency Injection in Beans:
—------------------------------------------------------------------------------
1. Injecting Primitive Values
2. Injecting an Object
3. Injecting a List
4. Injecting a Set
5. Injecting a Map
6. Injecting a Properties

If we want to inject List of values then we have to declare a property with java.util.List
type in bean class and we must configure that List type property in the Spring
configuration file like below.

<property name="qualifications">
<list>
<value>BTECH</value>
<value>MTECH</value>
<value>PHD</value>
</list>
</property>

If we want to inject a set of values in a Bean then we have to declare a property of type
java.util.Set and its setXXX() method and getXXX() method and we must configure that
property in the Spring COnfiguration file like below.

<property name="subjects">
<set>
<value>JAVA</value>
<value>PYTHON</value>
<value>.NET</value>
</set>
</property>

If we want to inject a Map in a Bean then we have to declare a property of type


java.util.Map and we must configure that property in Spring configuration like below.
<property name="degreeAndYerOfPassout">
<map>
<entry key="BTECH" value="2019"/>
<entry key="MTECH" value="2021"/>
<entry key="PHD" value="2026"/>
</map>
</property>
<property name="course" ref="course"/>

If we want to inject Properties of data in a Bean object then we have to declare that
property of type java.util.Properties and we must configure that property in the Spring
Configuration file like below.

<property name="subjectsAndMarks">
<props>
<prop key="JAVA">88</prop>
<prop key="PYTHON">93</prop>
<prop key=".NET">77</prop>
</props>
</property>

EX:
Course.java
package com.durgasoft.beans;

public class Course {


private String cid;
private String cname;
private int cfee;

public String getCid() {


return cid;
}

public void setCid(String cid) {


this.cid = cid;
}

public String getCname() {


return cname;
}
public void setCname(String cname) {
this.cname = cname;
}

public int getCfee() {


return cfee;
}

public void setCfee(int cfee) {


this.cfee = cfee;
}
}

Student.java
package com.durgasoft.beans;

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

public class Student {


private String sid;
private String sname;
private Course course;
private int sage;

public int getSage() {


return sage;
}

public void setSage(int sage) {


this.sage = sage;
}

private List<String> qualifications;


private Map<String, Integer> degreeAndYerOfPassout;
private Properties subjectsAndMarks;

public Properties getSubjectsAndMarks() {


return subjectsAndMarks;
}
public void setSubjectsAndMarks(Properties subjectsAndMarks) {
this.subjectsAndMarks = subjectsAndMarks;
}

public Map<String, Integer> getDegreeAndYerOfPassout() {


return degreeAndYerOfPassout;
}

public void setDegreeAndYerOfPassout(Map<String, Integer>


degreeAndYerOfPassout) {
this.degreeAndYerOfPassout = degreeAndYerOfPassout;
}

private Set<String> subjects;

public Set<String> getSubjects() {


return subjects;
}

public void setSubjects(Set<String> subjects) {


this.subjects = subjects;
}

public List<String> getQualifications() {


return qualifications;
}

public void setQualifications(List<String> qualifications) {


this.qualifications = qualifications;
}

public String getSid() {


return sid;
}

public void setSid(String sid) {


this.sid = sid;
}

public String getSname() {


return sname;
}
public void setSname(String sname) {
this.sname = sname;
}

public Course getCourse() {


return course;
}

public void setCourse(Course course) {


this.course = course;
}

public void getStudentDetails(){


System.out.println("Student Details");
System.out.println("-----------------------");
System.out.println("Student Id : "+sid);
System.out.println("Student Name : "+sname);
System.out.println("Student Age : "+sage);
System.out.println("Qualifications : "+qualifications);
System.out.println("Subjects : "+subjects);
System.out.println("Degree And Year :
"+degreeAndYerOfPassout);
System.out.println("Subjects And Marks :
"+subjectsAndMarks);

System.out.println("Course Details");
System.out.println("-------------------------");
System.out.println("Course Id : "+course.getCid());
System.out.println("Course Name : "+course.getCname());
System.out.println("Course Fee : "+course.getCfee());

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

https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="course" class="com.durgasoft.beans.Course">
<property name="cid" value="C-111"/>
<property name="cname" value="JAVA"/>
<property name="cfee" value="50000"/>
</bean>
<bean id="student" class="com.durgasoft.beans.Student">
<property name="sid" value="S-111"/>
<property name="sname" value="Durga"/>
<property name="sage" value="34"/>
<property name="qualifications">
<list>
<value>BTECH</value>
<value>MTECH</value>
<value>PHD</value>
</list>
</property>
<property name="subjects">
<set>
<value>JAVA</value>
<value>PYTHON</value>
<value>.NET</value>
</set>
</property>
<property name="degreeAndYerOfPassout">
<map>
<entry key="BTECH" value="2019"/>
<entry key="MTECH" value="2021"/>
<entry key="PHD" value="2026"/>
</map>
</property>
<property name="subjectsAndMarks">
<props>
<prop key="JAVA">88</prop>
<prop key="PYTHON">93</prop>
<prop key=".NET">77</prop>
</props>
</property>
<property name="course" ref="course"/>
</bean>
</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app09</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Student;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Student student = applicationContext.getBean(Student.class);
student.getStudentDetails();
}
}

Circular Dependency Injection:


—---------------------------------------
Injecting dependency objects in a circular fashion is called Circular Dependency
injection, it will occur in only Constructor Dependency Injection.

EX:
Student.java
package com.durgasoft.beans;

public class Student {


private String sid;
private String sname;
private Branch branch;

public Student(String sid, String sname, Branch branch) {


this.sid = sid;
this.sname = sname;
this.branch = branch;
}

Branch.java
package com.durgasoft.beans;

public class Branch {


private String branchId;
private String branchName;
private Student student;

public Branch(String branchId, String branchName, Student student) {


this.branchId = branchId;
this.branchName = branchName;
this.student = student;
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.durgasoft.beans.Student">
<constructor-arg name="sid" value="S-111"/>
<constructor-arg name="sname" value="Durga"/>
<constructor-arg name="branch" ref="branch"/>
</bean>
<bean id="branch" class="com.durgasoft.beans.Branch">
<constructor-arg name="branchId" value="B-111"/>
<constructor-arg name="branchName" value="Computers"/>
<constructor-arg name="student" ref="student"/>
</bean>
</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app01</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

Main.java
package com.durgasoft;

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

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
}
}

If we run the above application , ApplicationContext will provide the following exception .
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating
bean with name 'student': Requested bean is currently in creation: Is there an
unresolvable circular reference?

In the above application, when ApplicationContext is creating Student Bean object it


required Branch bean object, but Branch bean object is in creation, while creating
branch bean object Student bean object is required, but Student bean object is in
Creation, it represents Circular dependency injection, it is not supported by Spring
framework.

To avoid the circular Dependency Injection problem we have to use the setter method
dependency Injection.

In case of Setter method dependency injections, Bean objects created with 0-arg
constructor , after this, Container will inject dependency objects through setter methods,
here there is not chance of getting Circular dependency injection.

EX:
Student.java
package com.durgasoft.beans;

public class Student {


private String sid;
private String sname;
private Branch branch;

public String getSid() {


return sid;
}

public void setSid(String sid) {


this.sid = sid;
}

public String getSname() {


return sname;
}

public void setSname(String sname) {


this.sname = sname;
}

public Branch getBranch() {


return branch;
}

public void setBranch(Branch branch) {


this.branch = branch;
}

public void getStudentDetails(){


System.out.println("Student Details");
System.out.println("-----------------------");
System.out.println("Student Id : "+sid);
System.out.println("Student Name : "+sname);
System.out.println("Branch Id : "+branch.getBranchId());
System.out.println("Branch Name : "+branch.getBranchName());

}
}

Branch.java
package com.durgasoft.beans;

public class Branch {


private String branchId;
private String branchName;
private Student student;

public String getBranchId() {


return branchId;
}

public void setBranchId(String branchId) {


this.branchId = branchId;
}

public String getBranchName() {


return branchName;
}

public void setBranchName(String branchName) {


this.branchName = branchName;
}

public Student getStudent() {


return student;
}

public void setStudent(Student student) {


this.student = student;
}

public void getBranchDetails(){


System.out.println("Branch Details");
System.out.println("----------------------");
System.out.println("Branch Id : "+branchId);
System.out.println("Branch Name : "+branchName);
System.out.println("Student Id : "+student.getSid());
System.out.println("Student Name : "+student.getSname());
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.durgasoft.beans.Student">
<property name="sid" value="S-111"/>
<property name="sname" value="Durga"/>
<property name="branch" ref="branch"/>
</bean>
<bean id="branch" class="com.durgasoft.beans.Branch">
<property name="branchId" value="B-111"/>
<property name="branchName" value="Computers"/>
<property name="student" ref="student"/>
</bean>
</beans>

Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app01</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Branch;
import com.durgasoft.beans.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Student student = applicationContext.getBean(Student.class);
student.getStudentDetails();
System.out.println();

Branch branch = applicationContext.getBean(Branch.class);


branch.getBranchDetails();
}
}

Q)In Spring applications, if we provide both setter method dependency injection and
Constructor Dependency injection in a single bean object then what will happen in
Spring application?
—--------------------------------------------------------------------------------------------------------
Ans:
—---
In Spring applications, if we provide both constructor dependency injection and Setter
method dependency injection in a single bean then Constructor dependency injection is
overridden by Setter method dependency injection, finally we are able to get only setter
method dependency injection provided values in bean object.

EX:
—-
Student.java
package com.durgasoft.beans;

public class Student {


private String sid;
private String sname;
private String saddr;

public Student(String sid, String sname, String saddr) {


this.sid = sid;
this.sname = sname;
this.saddr = saddr;
}

public String getSid() {


return sid;
}

public void setSid(String sid) {


this.sid = sid;
}

public String getSname() {


return sname;
}

public void setSname(String sname) {


this.sname = sname;
}

public String getSaddr() {


return saddr;
}

public void setSaddr(String saddr) {


this.saddr = saddr;
}
public void getStudentDetails(){
System.out.println("Student Details");
System.out.println("------------------------");
System.out.println("Student Id : "+sid);
System.out.println("Student Name : "+sname);
System.out.println("Student Address : "+saddr);
}
}

SpringConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.durgasoft.beans.Student">
<constructor-arg name="sid" value="S-111"/>
<constructor-arg name="sname" value="AAA"/>
<constructor-arg name="saddr" value="Hyd"/>
<property name="sid" value="S-222"/>
<property name="sname" value="BBB"/>
<property name="saddr" value="Chennai"/>
</bean>

</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>app02</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

Main.java
package com.durgasoft;
import com.durgasoft.beans.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Student student = applicationContext.getBean(Student.class);
student.getStudentDetails();
}
}

OP
Student Details
------------------------
Student Id : S-222
Student Name : BBB
Student Address : Chennai

Q)What are the differences between constructor Dependency injection and Setter
method dependency injection?
—-----------------------------------------------------------------------------------------------------------
Ans:
—---
1. Injecting dependency objects through a constructor is called Constructor
Dependency Injection.

Injecting Dependency objects through a setter method is called Setter method


dependency injection

2. Constructor Dependency injection will not provide good Readability.

Setter Method Dependency Injection will provide good Readability.

3. Constructor Dependency injection is suggestible when we have less number of


arguments.

Setter method dependency injection is suggestible for any number of


Dependencies.
4. In case of Constructor Dependency injection, all Dependency elements must be
ready before injection, without getting ready the dependency elements there is
no chance for Constructor Dependency injection.

In the case of Setter method dependency injection, no need to make ready all the
Dependency elements, with some dependency elements we can manage setter
method dependency injection.

5. Partial dependency injection is not possible in Constructor Dependency Injection.

Partial Dependency injection is possible in Setter method dependency injection.

6. Constructor Dependency injection will give guarantee for the dependency


injection and its injected values.

Setter Method Dependency injection is not giving guarantee for dependency


injection and its injected values.

7. It is not easy to modify the values in bean objects through Constructor


dependency injection.

It is very simple to modify the values in bean objects through Setter method
dependency injection.

8. If we are trying to modify the values of a bean object through Constructor


dependency injection then Constructor will be executed again and it will create
another new bean object with the new values.

If we are trying to modify the values of a bean object through Setter method
dependency injection then no new bean will be created, in the same bean object
modifications will be performed.

9. Constructor dependency injection will make the bean objects as Immutable


objects.
Setter method dependency injection will make the bean objects as Mutable
Objects.

10. Circular Dependency injection problem will come in Constructor dependency


injection.
Circular Dependency injection problem will be resolved in Setter method
dependency injection.

11. In a single bean if we provide both constructor dependency injection and setter
method dependency injection then Setter method dependency injection provided
values will override the constructor dependency injection provided values.

P-NameSpace and C-Name Space:


—----------------------------------------------
P-Namespace:
If we want to provide values to a bean object through setter method dependency
injection then we have to use the following tags.

<beans>
<bean is=”employee” class=”com.durgasoft.beans.Employee”>
<property name=”eno” value=”111”/>
<property name=”ename” value=”Durga”/>
<property name=”esal” value=”5000”/>
<property name=”eaddr” value=”Hyd”/>
</bean>
</beans>

In the above configurations, we must provide a separate <poroperty> tag for each and
every property of the bean component, here we want to inject values to the bean
properties without using <property> tags, there we must use P-Namespace.

If we want to inject values to the bean properties through setter method dependency
injection by using P-Namespace then we have to use P-namespace xsd in Spring
Configuration file and we have to provide the values in the same <bean> tag along with
the P-namespace variable like below.

<beans
Xmlns p:http://org.springframework/namespaces/p
—----
>
<bean id=”--” class=”--” p:eno=”111” p:ename=”AAA” p:account-ref=”account”/>
—--
</beans>

EX:
Account.java
package com.durgasoft.beans;

public class Account {


private String accNo;
private String accHolderName;
private String accType;
private int balance;

public String getAccNo() {


return accNo;
}

public void setAccNo(String accNo) {


this.accNo = accNo;
}

public String getAccHolderName() {


return accHolderName;
}

public void setAccHolderName(String accHolderName) {


this.accHolderName = accHolderName;
}

public String getAccType() {


return accType;
}

public void setAccType(String accType) {


this.accType = accType;
}

public int getBalance() {


return balance;
}

public void setBalance(int balance) {


this.balance = balance;
}
}

Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;
private Account account;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}
public void setEsal(float esal) {
this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}

public Account getAccount() {


return account;
}

public void setAccount(Account account) {


this.account = account;
}

public void getEmployeeDetails(){


System.out.println("Employee Details");
System.out.println("------------------------");
System.out.println("Employee Number : "+eno);
System.out.println("Employee Name : "+ename);
System.out.println("Employee Salary : "+esal);
System.out.println("Employee Address : "+eaddr);
System.out.println();
System.out.println("Account Details");
System.out.println("-------------------------");
System.out.println("Account Number :
"+account.getAccNo());
System.out.println("Account Holder Name:
"+account.getAccHolderName());
System.out.println("Account Type :
"+account.getAccType());
}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Employee employee =
applicationContext.getBean(Employee.class);
employee.getEmployeeDetails();
}
}

SpringConfig.xml
<beans
xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd">
<bean id="account" class="com.durgasoft.beans.Account"
p:accNo="abc123"
p:accHolderName="Durga"
p:accType="Savings"
p:balance="50000"
/>
<bean id="employee"
class="com.durgasoft.beans.Employee"
p:eno="111"
p:ename="Durga"
p:esal="5000"
p:eaddr="Hyd"
p:account-ref="account"
/>
</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app12</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

Note: In Bean components, if we want to inject List type elements, Set Type
Elements,.... Then P-Namespace is sufficient, there we have to use <property> tags.

C-Namespace:
—-----------------
If we want to provide values to a bean object through Constructor dependency injection
then we have to use the following tags.

<beans>
<bean is=”employee” class=”com.durgasoft.beans.Employee”>
<constructor-arg name=”eno” value=”111”/>
<constructor-arg name=”ename” value=”Durga”/>
<constructor-arg name=”esal” value=”5000”/>
<constructor-arg name=”eaddr” value=”Hyd”/>
</bean>
</beans>

In the above configurations, we must provide a separate <constructor-arg> tag for each
and every argument of the bean class constructor, here we want to inject values to the
bean properties without using <constructor-arg> tags, there we must use
C-Namespace.

If we want to inject values to the bean Object through Constructor dependency injection
by using C-Namespace then we have to use C-namespace xsd in Spring Configuration
file and we have to provide the values in the same <bean> tag along with the
C-namespace variable like below.

<beans
Xmlns=c:http://org.springframework/namespaces/c
—----
>
<bean id=”--” class=”--” c:eno=”111” c:ename=”AAA” c:account-ref=”account”/>
—--
</beans>

EX:
—--
Schedule.java
package com.durgasoft.beans;

public class Schedule {


private String scheduleId;
private String demoDate;
private String demoTime;

public Schedule(String scheduleId, String demoDate,


String demoTime) {
this.scheduleId = scheduleId;
this.demoDate = demoDate;
this.demoTime = demoTime;
}
public void getScheduleDetails(){
System.out.println("Schedule Details");
System.out.println("------------------------");
System.out.println("Schedule Id :
"+scheduleId);
System.out.println("Demo Date : "+demoDate);
System.out.println("Demo Time : "+demoTime);
}
}

Course.java
package com.durgasoft.beans;

public class Course {


private String cid;
private String cname;
private int cfee;
private Schedule schedule;

public Course(String cid, String cname, int cfee,


Schedule schedule) {
this.cid = cid;
this.cname = cname;
this.cfee = cfee;
this.schedule = schedule;
}

public void getCourseDetails(){


System.out.println("Course Details");
System.out.println("---------------------");
System.out.println("Course Id : "+cid);
System.out.println("Course Name : "+cname);
System.out.println("Course Fee : "+cfee);
System.out.println();
schedule.getScheduleDetails();

}
}

SpringConfig.xml
<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"
xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd">
<bean id="schedule"
class="com.durgasoft.beans.Schedule"
c:scheduleId="C-111"
c:demoDate="21-04-2023"
c:demoTime="7AM"
/>
<bean id="course" class="com.durgasoft.beans.Course"
c:cid="C-111"
c:cname="Java"
c:cfee="30000"
c:schedule-ref="schedule"
/>

</beans>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Course;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Course course =
applicationContext.getBean(Course.class);
course.getCourseDetails();
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app13</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>

In the C_Namespace if we want to use argument index values to represent argument


values then we have to use Argument Name along with C-Namespace like below.

<bean id="schedule" class="com.durgasoft.beans.Schedule"


c:_0="C-111"
c:_1="21-04-2023"
c:_2="7AM"
/>

EX:
<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"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd">
<bean id="schedule"
class="com.durgasoft.beans.Schedule"
c:_0="C-111"
c:_1="21-04-2023"
c:_2="7AM"
/>
<bean id="course" class="com.durgasoft.beans.Course"
c:_0="C-111"
c:_1="Java"
c:_2="30000"
c:_3-ref="schedule"
/>
</beans>

Note: In the case of C-Namespace , if we want to inject complex data like List, Set,
Map,.... in a bean object then we have to use the <constructor-arg> tag in the <bean>
tag.

EX:
<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"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd">
<bean id="schedule"
class="com.durgasoft.beans.Schedule"
c:_0="C-111"
c:_1="21-04-2023"
c:_2="7AM"
/>
<bean id="course" class="com.durgasoft.beans.Course"
c:_0="C-111"
c:_1="Java"
c:_2="30000"
c:_3-ref="schedule"
>
<constructor-arg name="pre_requisite">
<list>
<value>C</value>
<value>C++</value>
</list>
</constructor-arg>
</bean>
</beans>

Bean Collaboration or Bean Auto-wiring:


—----------------------------------------------------
In general, in enterprise applications, we are able to use a number of bean components,
where one bean component is depending on another bean component.

In Spring applications, we are able to provide dependency beans to the Dependent


bean objects either through Setter method dependency injection or through constructor
dependency injection.

In Spring applications, to inject any bean object through setter method dependency
injection we have to use <property> tag with ‘ref’ attribute in <bean> tag in Spring
configuration file, to inject bean object through constructor dependency injection we
have to use <constructor-arg> tag with ‘ref’ attribute under <bean> tag in Spring
Configuration File.

If we want to inject bean objects through setter method method dependency injection
without using <property> tag then we have to use “P-namespace”, if we want to injects
objects through Constructor dependency injection without using <constructor-arg> tag
then we have to use “C-Namespace”.

In Spring applications, if we want to inject bean objects automatically on the basis of the
properties names or properties data types either through Setter method dependency
Injection or through Constructor dependency injection without using <property> tag,
<constructor-arg> tag , P-namespace and C-Namespace then we have to use
“Auto-Wiring”.

Auto-Wiring is not applicable for primitive values injection rather it is applicable for
Objects injection.

“Auto-wiring” will make the container inject the dependency objects to the Dependent
objects either by matching the properties names or by matching the properties data
types .

In Spring applications, there are four ways to provide auto-wiring.


1. XML Based Autowiring
2. Annotation Based Autowiring
3. Stereotype Autowiring
4. Java Based Autowiring

XML Based Autowiring:


—-----------------------------
In XML based autowiring, we will use the “autowire” attribute in <bean> tag in spring
configuration file inorder to provide autowiring.

<beans>
<bean autowire=”value”>
—----
</bean>
—----
</beans>

EX:
Address.java
package com.durgasoft.beans;

public class Address {


private String hno;
private String street;
private String city;
private String state;
setXxx() and getXxx()
}

Account.java
package com.durgasoft.beans;
public class Account {
private String accNo;
private String accHolderName;
private String accType;
private int balance;
setXxx() getXxx()
}
Employee.java
public class Employee {
private int eno;
private String ename;
private float esal;
private Address address;
private Account account;
setXxx() and getXxx()
}
Test.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Employee employee = (Employee)
applicationContext.getBean("employee");
employee.getEmployeeDetails();
}
}

Where the autowire attribute will have the following values.


1. no
2. byName
3. byType
4. constructor

Where “no” value represents no autowiring in the bean configuration, we must use
explicit wiring.
EX:
<beans>
<bean id="address" class="com.durgasoft.beans.Address"
p:hno="23"
p:street="MG Road"
p:city="Hyd"
p:state="Telangana"
/>

<bean id="account" class="com.durgasoft.beans.Account"


p:accNo="abc123"
p:accHolderName="Durga"
p:accType="Savings"
p:balance="10000"

/>

<bean id="employee"
class="com.durgasoft.beans.Employee"
p:eno="111"
p:ename="Durga"
p:esal="50000"
autowire="no"
p:account-ref="account"
p:address-ref="address"
/>
</beans>

Where “byName” value is representing autowiring by matching the property names in


the bean classes and the bean id values in the spring configuration file.
EX:
<beans>
<bean id="address" class="com.durgasoft.beans.Address"
p:hno="23"
p:street="MG Road"
p:city="Hyd"
p:state="Telangana"
/>
<bean id="account" class="com.durgasoft.beans.Account"
p:accNo="abc123"
p:accHolderName="Durga"
p:accType="Savings"
p:balance="10000"

/>
<bean id="employee"
class="com.durgasoft.beans.Employee"
p:eno="111"
p:ename="Durga"
p:esal="50000"
autowire="byName"
/>
</beans>
Where “byType” value is representing autowiring by matching the property data type in
the bean classes and the bean’s class attribute value in bean definition in Spring
configuration file.
EX:
<beans>
<bean id="address1"
class="com.durgasoft.beans.Address"
p:hno="23"
p:street="MG Road"
p:city="Hyd"
p:state="Telangana"
/>
<bean id="account1"
class="com.durgasoft.beans.Account"
p:accNo="abc123"
p:accHolderName="Durga"
p:accType="Savings"
p:balance="10000"

/>
<bean id="employee"
class="com.durgasoft.beans.Employee"
p:eno="111"
p:ename="Durga"
p:esal="50000"
autowire="byType"

/>
</beans>

Note: If we have more than one bean definition with the same class attribute
value[Same Type] then Container will raise an exception.
EX:
<beans>
<bean id="address1"
class="com.durgasoft.beans.Address"
p:hno="23"
p:street="MG Road"
p:city="Hyd"
p:state="Telangana"
/>
<bean id="account1"
class="com.durgasoft.beans.Account"
p:accNo="abc123"
p:accHolderName="Durga"
p:accType="Savings"
p:balance="10000"

/>

<bean id="account2"
class="com.durgasoft.beans.Account"
p:accNo="xyz123"
p:accHolderName="Anil"
p:accType="Savings"
p:balance="20000"

/>

<bean id="employee"
class="com.durgasoft.beans.Employee"
p:eno="111"
p:ename="Durga"
p:esal="50000"
autowire="byType"

/>
</beans>

If we run Main.java file then we are able to get the following exception.

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
qualifying bean of type 'com.durgasoft.beans.Account' available: expected single
matching bean but found 2: account1,account2

In the above context, to resolve the ambiguity of injecting which bean object among the
multiple beans of the same type we will use the “autowire-candidate” attribute. It will
take a boolean value, if we provide true value then the bean object will be included in
the dependency injection, if we provide false value to this attribute then the respective
bean object will not be included in the dependency Injection.

EX:
<beans>
<bean id="address1"
class="com.durgasoft.beans.Address"
p:hno="23"
p:street="MG Road"
p:city="Hyd"
p:state="Telangana"
/>
<bean id="account1"
class="com.durgasoft.beans.Account"
p:accNo="abc123"
p:accHolderName="Durga"
p:accType="Savings"
p:balance="10000"

/>

<bean id="account2"
class="com.durgasoft.beans.Account"
p:accNo="xyz123"
p:accHolderName="Anil"
p:accType="Savings"
p:balance="20000"
autowire-candidate=”false”
/>

<bean id="employee"
class="com.durgasoft.beans.Employee"
p:eno="111"
p:ename="Durga"
p:esal="50000"
autowire="byType"

/>
</beans>

Note: In the above byName, byType autowiring, Container will use Setter method
dependency injection internally.

Where the “constructor” value is the same as byType autowiring , but it will use
Constructor Dependency injection internally in place of the Setter method dependency
Injection.

EX:
—----
Address.java
package com.durgasoft.beans;
public class Address {
private String hno;
private String street;
private String city;
private String state;

public Address(String hno, String street, String city,


String state) {
this.hno = hno;
this.street = street;
this.city = city;
this.state = state;
}
public void getAddressDetails(){
System.out.println("Address Details");
System.out.println("----------------------");
System.out.println("House Number : "+hno);
System.out.println("Street : "+street);
System.out.println("City : "+city);
System.out.println("State : "+state);
}
}

Account.java
package com.durgasoft.beans;

public class Account {


private String accNo;
private String accHolderName;
private String accType;
private int balance;

public Account(String accNo, String accHolderName,


String accType, int balance) {
this.accNo = accNo;
this.accHolderName = accHolderName;
this.accType = accType;
this.balance = balance;
}
public void getAccountDetails(){
System.out.println("Account Details");
System.out.println("-----------------------");
System.out.println("Account Number :
"+accNo);
System.out.println("Account Holder Name :
"+accHolderName);
System.out.println("Account Type :
"+accType);
System.out.println("Account Balance :
"+balance);
}
}

Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private Address address;
private Account account;

public Employee(int eno, String ename, float esal,


Address address, Account account) {
this.eno = eno;
this.ename = ename;
this.esal = esal;
this.address = address;
this.account = account;
}

public void getEmployeeDetails() {


System.out.println("Employee Details");
System.out.println("-------------------------");
System.out.println("Employee Number : " + eno);
System.out.println("Employee Name : " +
ename);
System.out.println("Employee Salary : " +
esal);
System.out.println();
account.getAccountDetails();
System.out.println();
address.getAddressDetails();
}
}

SpringConfig.xml
<?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"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd">
<bean id="address1"
class="com.durgasoft.beans.Address"
c:hno="23"
c:street="MG Road"
c:city="Hyd"
c:state="Telangana"
/>

<bean id="account1"
class="com.durgasoft.beans.Account"
c:accNo="abc123"
c:accHolderName="Durga"
c:accType="Savings"
c:balance="10000"

/>

<bean id="account2"
class="com.durgasoft.beans.Account"
c:accNo="xyz123"
c:accHolderName="Anil"
c:accType="Savings"
c:balance="20000"
autowire-candidate="false"
/>

<bean id="employee"
class="com.durgasoft.beans.Employee"
c:eno="111"
c:ename="Durga"
c:esal="50000"
autowire="constructor"

/>

</beans>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Employee employee = (Employee)
applicationContext.getBean("employee");
employee.getEmployeeDetails();
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app14</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

Annotation Based Auto-Wiring:


—----------------------------------------
In XML based Auto-wiring , to perform Dependency Injection we have to use the
“autowire” attribute with the values like “no”, “byName”, “byType” and “constructor”.

In Spring applications if we want to provide auto-wiring without using “autowire” attribute


and “autowire-candidate” attribute in Spring Configuration File then we have to use
“Annotation Based Autowiring”.

In “Annotation Based Autowiring” , to provide Auto-wiring we have to use the following


annotations.

1. @Required
2. @Autowired
3. @Qualifier

@Required:
—------------
It is a method level annotation, it will be used just above of the setXXX() method which
we used for a particular bean injection.

The main intention of @Required annotation is to make a bean object dependency


injection mandatory.

class Account{
—----
}
class Employee{
—----
private Account account;
—----
@Required
public void setAccount(Account account){
This.account = account;
}
—------
}

@Autowired
—---------------
The main purpose of this annotation is to perform Bean auto-wiring.
It will use “byType” auto-wiring internally.

In Spring applications, it will be used for the variables, methods,.....

If we provide @Autowired annotation at a property declaration then it will use setter


method Dependency injection internally.

If we Provide @Autowired annotation to a constructor argument then it will use


Constructor Dependency injection internally.

Note: If we use “required” member or attribute in @Autowired annotation then it not


required to use @Required annotation.

EX:
class Account{
—----
}
class Employee{
—----
private Account account;
—----
@Autowired()
@Required
public void setAccount(Account account){
This.account = account;
}
—------
}

EX:
class Account{
—----
}
class Employee{
—----
@Autowired(required=true)
private Account account;
—----
public void setAccount(Account account){
this.account = account;
}
—------
}

EX:
class Account{
—----
}
class Employee{
—----
private Account account;
—----
public Employee(....,...., @Autowired Account account){
—------
}
}

@Qualifier:
—-------------
In Spring applications, @Autowired annotation is following “byType” auto-wiring
internally, in this context if more than one bean object exists with the same type then we
are able to get an ambiguity situation that which bean object has to be injected.

In the above context, to resolve ambiguity problems we have to use @Qualifier


annotation to specify a particular bean object for injection out of multiple bean objects of
the same type.
class Course{
—-----
}
class Student{
—----
private Course course;
—----
@Autowired(required=true)
@Qualifier(“advjava”)
public void setCourse(Course course){
this.course = course;
}
}

<beans>
<bean id=”corejava” class=”com.dss.beans.Course”>
—---
</bean>
<bean id=”advjava” class=”com.dss.beans.Course”>
—---
</bean>
<bean id=”student” class=”com.dss.beans.Student”>
</bean>
</beans>

EX:
Course.java
package com.durgasoft.beans;

public class Course {


private String cid;
private String cname;
private int cfee;

public String getCid() {


return cid;
}

public void setCid(String cid) {


this.cid = cid;
}

public String getCname() {


return cname;
}

public void setCname(String cname) {


this.cname = cname;
}

public int getCfee() {


return cfee;
}

public void setCfee(int cfee) {


this.cfee = cfee;
}
}

Student.java
package com.durgasoft.beans;

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

public class Student {


private String sid;
private String sname;
private String saddr;
private Course course;
public String getSid() {
return sid;
}

public void setSid(String sid) {


this.sid = sid;
}

public String getSname() {


return sname;
}

public void setSname(String sname) {


this.sname = sname;
}

public String getSaddr() {


return saddr;
}

public void setSaddr(String saddr) {


this.saddr = saddr;
}

public Course getCourse() {


return course;
}
@Autowired
@Qualifier("python")
public void setCourse(Course course) {
this.course = course;
}

public void getStudentDetails(){


System.out.println("Student Details");
System.out.println("------------------------");
System.out.println("Student Id : "+sid);
System.out.println("Student Name : "+sname);
System.out.println("Student Address : "+saddr);
System.out.println();
System.out.println("Course Details");
System.out.println("-------------------------");
System.out.println("Course Id :
"+course.getCid());
System.out.println("Course Name :
"+course.getCname());
System.out.println("Course Cost :
"+course.getCfee());

}
}

SpringConfig.xml
<?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/cont
ext"
xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-con
text.xsd">
<context:annotation-config/>
<bean id="java" class="com.durgasoft.beans.Course"
p:cid="C-111"
p:cname="JAVA"
p:cfee="30000"
/>
<bean id="python" class="com.durgasoft.beans.Course"
p:cid="C-222"
p:cname="PYTHON"
p:cfee="20000"

/>
<bean id="student" class="com.durgasoft.beans.Student"
p:sid="S-111"
p:sname="Durga"
p:saddr="Hyd"

/>
</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app15</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>

EX:
Movie.java
package com.durgasoft.beans;

public class Movie {


private String id;
private String name;
private String rating;

public Movie(String id, String name, String rating) {


this.id = id;
this.name = name;
this.rating = rating;
}
public void getMovieDetails(){
System.out.println("Movie Details");
System.out.println("-----------------------");
System.out.println("Movie Id : "+id);
System.out.println("Movie Name : "+name);
System.out.println("Movie Rating : "+rating);
}
}

Album.java
package com.durgasoft.beans;

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

public class Album {


private String albumId;
private String albumName;
private Movie movie;

public Album(String albumId, String


albumName,@Autowired @Qualifier("bahubali1") Movie movie)
{

this.albumId = albumId;
this.albumName = albumName;
this.movie = movie;
}
public void getAlbumDetails(){
System.out.println("Album Details");
System.out.println("----------------------");
System.out.println("Album Id : "+albumId);
System.out.println("Album Name : "+albumName);
movie.getMovieDetails();
}
}

SpringConfig.xml
<?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/cont
ext"
xmlns:c="http://www.springframework.org/schema/c"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-con
text.xsd">
<context:annotation-config/>
<bean id="bahubali1" class="com.durgasoft.beans.Movie"
c:id="M-111"
c:name="Bahubali-The Begining"
c:rating="4*"
/>
<bean id="bahubali2" class="com.durgasoft.beans.Movie"
c:id="M-111"
c:name="Bahubali-The Conclusion"
c:rating="4.5*"
/>
<bean id="album" class="com.durgasoft.beans.Album"
c:albumId="A-111"
c:albumName="Movies Album"

/>
</beans>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Album;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Album album = (Album)
applicationContext.getBean("album");
album.getAlbumDetails();
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app16</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>

Stereotypes Autowiring:
—-----------------------------
If we want to perform auto-wiring in Spring applications we have to use either
<property> tag or <constructor-arg> tag with ref attribute .

If we want to perform auto-wiring without using <property> tag and <constructor-arg>


tag then we have to use P-namespace and C-namespace.

If we want to perform auto-wiring without <property> tag, <constructor-arg> tag,


P-namespace and C-namespace then we have to use Annotations like @Required,
@Autowired, @Qualifier.

Note: In all the above cases , we must provide beans configuration in the spring
configuration file.

In spring applications, if we want to provide auto-wiring even without providing beans


definitions in the spring configuration file then we have to use “Stereotype” annotations.
If we want to use Stereotype annotations in spring applications then we have to make
the container to scan all the components at the time of container startup, for this we
have to use the following tag in spring configuration file.

<context:component-scan base-package=”com.durgasoft.*”/>

If we provide the above tag in the spring configuration file then Container will perform
the following actions.

1. Container will recognize the <context:component-scan> tag .


2. Container will take the base package name from the “base-package” attribute.
3. Container will goto the base package and scan each and every class which
exists directly under the base package or under the child packages of the base
package.
4. If the container identifies any Stereotype annotations then the container will
create bean objects and provide the dependency injection as per the Stereotype
annotations .

Spring Framework has provided the following Stereotype annotations to implement


dependency injection.

1. @Controller
2. @Service
3. @Repository
4. @Component
If we declare any class with @Component then that class is acting as a component
class and its object will be created by the Container automatically.

If we declare any class with @Repository annotation then that class is acting as a
repository class and its object is created by the container and it will be injected to the
Service component.

If we declare any class with @Service annotation then that class is acting as a service
class and its object is created by the container and it will be injected to the Controller
component.

If we declare any class with @Controller annotation then that class is acting as
controller and its object will be created by the container and it will be injected in the
Front Controller.

In the above cases, to implement Dependency injection we need @Autowired


annotation just before the respective property or just before the respective setXxx()
method.
EX:
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}
public void setEaddr(String eaddr) {
this.eaddr = eaddr;
}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.controller.EmployeeController;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
EmployeeController employeeController =
(EmployeeController)
applicationContext.getBean("empController");
try (
BufferedReader bufferedReader = new
BufferedReader(new InputStreamReader(System.in));
){
System.out.println("Employee Management
System");

System.out.println("================================");
while(true){
System.out.println();
System.out.println("1. ADD Employee");
System.out.println("2. SEARCH Employee");
System.out.println("3. UPDATE Employee");
System.out.println("4. DELETE Employee");
System.out.println("5. EXIT");
System.out.print("Your Option[1,2,3,4 and
5] : ");
int option =
Integer.parseInt(bufferedReader.readLine());
switch (option){
case 1:
System.out.println("======ADD
MODULE=======");
employeeController.addEmployee();
break;
case 2:
System.out.println("======SEARCH
MODULE=======");

employeeController.searchEmployee();
break;
case 3:
System.out.println("======UPDATE
MODULE=======");

employeeController.updateEmployee();
break;
case 4:
System.out.println("======DELETE
MODULE=======");

employeeController.deleteEmployee();
break;
case 5:
System.out.println("Thank You For
Using Employee Management System Application");
System.exit(0);
break;
default:
System.out.println("Please enter
the values from 1 to 5");
break;
}
}
}catch(Exception exception){
exception.printStackTrace();
}

}
}

EmployeeController.java
package com.durgasoft.controller;

import com.durgasoft.beans.Employee;
import com.durgasoft.service.EmployeeService;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Controller("empController")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;

BufferedReader bufferedReader = new BufferedReader(new


InputStreamReader(System.in));
public void addEmployee(){
try{
String status = "";
System.out.print("Employee Number : ");
int eno =
Integer.parseInt(bufferedReader.readLine());

System.out.print("Employee Name :
");
String ename = bufferedReader.readLine();
System.out.print("Employee Salary :
");
float esal =
Float.parseFloat(bufferedReader.readLine());
System.out.print("Employee Address :
");
String eaddr = bufferedReader.readLine();
Employee employee = new Employee();
employee.setEno(eno);
employee.setEname(ename);
employee.setEsal(esal);
employee.setEaddr(eaddr);

status =
employeeService.addEmployee(employee);
if(status.equalsIgnoreCase("success")){
System.out.println("Status :
SUCCESS");
}
if(status.equalsIgnoreCase("failure")){
System.out.println("Status :
FAILURE");
}
if(status.equalsIgnoreCase("existed")){
System.out.println("Status :
EXISTED");
}
}catch(Exception exception){
exception.printStackTrace();
}

}
public void searchEmployee(){
Employee employee = null;
try {
System.out.print("Employee Number : ");
int eno =
Integer.parseInt(bufferedReader.readLine());
employee =
employeeService.searchEmployee(eno);
if(employee == null){
System.out.println("Status : Employee
Not Existed");
}else{
System.out.println("Status : Employee
Existed");
System.out.println("Employee Details");

System.out.println("----------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Salary :
"+employee.getEsal());
System.out.println("Employee Address :
"+employee.getEaddr());
}
} catch (Exception e) {
e.printStackTrace();
}

}
public void updateEmployee(){
try{
System.out.print("Employee Number : ");
int eno =
Integer.parseInt(bufferedReader.readLine());
Employee emp =
employeeService.searchEmployee(eno);
if(emp == null){
System.out.println("Status : Employee
Not Existed");
}else{
System.out.println("Status : Employee
Existed");
System.out.print("Employee Name [Old:
"+emp.getEname()+" ] New : ");
String ename = bufferedReader.readLine();
if(ename == null ||
ename.equalsIgnoreCase("")){
ename = emp.getEname();
}

System.out.print("Employee Salary [Old:


"+emp.getEsal()+" ] New : ");
String sal = bufferedReader.readLine();
float esal = 0.0f;
if(sal == null ||
sal.equalsIgnoreCase("")){
esal = emp.getEsal();
}else{
esal = Float.parseFloat(sal);
}

System.out.print("Employee Address [Old:


"+emp.getEaddr()+" ] New : ");
String eaddr = bufferedReader.readLine();
if(eaddr == null ||
eaddr.equalsIgnoreCase("")){
eaddr = emp.getEaddr();
}

Employee newEmp = new Employee();


newEmp.setEno(eno);
newEmp.setEname(ename);
newEmp.setEsal(esal);
newEmp.setEaddr(eaddr);

String status =
employeeService.updateEmployee(newEmp);
if(status.equalsIgnoreCase("success")){
System.out.println("Status :
Employee Updated Successfully");
}else{
System.out.println("Status :
Employee Updation Failure");
}
}
}catch(Exception exception){
exception.printStackTrace();
}
}
public void deleteEmployee(){
try {
System.out.print("Employee NUmber : ");
int eno =
Integer.parseInt(bufferedReader.readLine());
Employee employee =
employeeService.searchEmployee(eno);
if(employee == null){
System.out.println("Status : Employee
Not Existed");
}else{
String status =
employeeService.deleteEmployee(eno);
if(status.equalsIgnoreCase("success")){
System.out.println("Status :
Employee Deleted Successfully");
}else{
System.out.println("Status :
Employee Deletion Failure");
}
}

}catch (Exception exception){


exception.printStackTrace();
}
}

EmployeeService.java
package com.durgasoft.service;

import com.durgasoft.beans.Employee;
import com.durgasoft.repository.EmployeeRepository;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
public String addEmployee(Employee employee){
String status = employeeRepository.add(employee);
return status;
}
public Employee searchEmployee(int eno){
Employee employee =
employeeRepository.search(eno);
return employee;
}
public String updateEmployee(Employee employee){
String status =
employeeRepository.update(employee);
return status;
}
public String deleteEmployee(int eno){
String status = employeeRepository.delete(eno);
return status;
}
}

EmployeeRepository.java
package com.durgasoft.repository;

import com.durgasoft.beans.Employee;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.jdbc.datasource.DriverManagerDataSour
ce;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Repository
public class EmployeeRepository {
@Autowired
private DriverManagerDataSource
driverManagerDataSource;
public String add(Employee employee){
String status = "";
try {
Employee emp = search(employee.getEno());
if (emp == null) {
Connection connection =
driverManagerDataSource.getConnection();
PreparedStatement preparedStatement =
connection.prepareStatement("insert into emp1
values(?,?,?,?)");
preparedStatement.setInt(1,
employee.getEno());
preparedStatement.setString(2,
employee.getEname());
preparedStatement.setFloat(3,
employee.getEsal());
preparedStatement.setString(4,
employee.getEaddr());
int rowCount =
preparedStatement.executeUpdate();
if (rowCount == 1) {
status = "Success";
} else {
status = "Failure";
}
}else{
status = "existed";
}
}catch(Exception exception){
exception.printStackTrace();
}
return status;
}

public Employee search(int eno){


Employee employee = null;
try {
Connection connection =
driverManagerDataSource.getConnection();
PreparedStatement preparedStatement =
connection.prepareStatement("select * from emp1 where ENO
= ?");
preparedStatement.setInt(1, eno);
ResultSet resultSet =
preparedStatement.executeQuery();
boolean b = resultSet.next();
if(b == true){
employee = new Employee();
employee.setEno(resultSet.getInt("ENO"));

employee.setEname(resultSet.getString("ENAME"));

employee.setEsal(resultSet.getFloat("ESAL"));

employee.setEaddr(resultSet.getString("EADDR"));
}else{
employee = null;
}
}catch (Exception exception){
exception.printStackTrace();
}
return employee;
}
public String update(Employee employee){
String status = "";
try {
Connection connection =
driverManagerDataSource.getConnection();
PreparedStatement preparedStatement =
connection.prepareStatement("update emp1 set ENAME=?,
ESAL=?, EADDR=? where ENO=?");
preparedStatement.setString(1,
employee.getEname());
preparedStatement.setFloat(2,
employee.getEsal());
preparedStatement.setString(3,
employee.getEaddr());
preparedStatement.setInt(4,
employee.getEno());
int rowCount =
preparedStatement.executeUpdate();
if(rowCount == 1){
status = "success";
}else{
status = "failure";
}
}catch(Exception exception){
exception.printStackTrace();
}
return status;
}
public String delete(int eno){
String status = "";
try{
Connection connection =
driverManagerDataSource.getConnection();
PreparedStatement preparedStatement =
connection.prepareStatement("delete from emp1 where ENO =
?");
preparedStatement.setInt(1, eno);
int rowCount =
preparedStatement.executeUpdate();
if(rowCount == 1){
status = "success";
}else{
status = "failure";
}
}catch(Exception exception){
exception.printStackTrace();
}
return status;
}
}

SpringConfig.xml
<?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/cont
ext"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-con
text.xsd">
<context:component-scan
base-package="com.durgasoft.*"/>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerD
ataSource">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>

</bean>
</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app17</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/sp
ring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.25</version>
</dependency>
<!--
https://mvnrepository.com/artifact/mysql/mysql-connector-
java -->
<dependency>
<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>

</dependencies>

</project>

Java Based Autowiring:


—-----------------------------
In the case of Java based Autowiring, we will use a java file or a java program in place
of Spring Configuration.

In the Java program we have to use the annotations like @Configuration and @Bean

EX:
—--
Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.config.AppConfig;
import com.durgasoft.controller.EmployeeController;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigAp
plicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
AnnotationConfigApplicationContext(AppConfig.class);
EmployeeController employeeController =
(EmployeeController)
applicationContext.getBean("employeeController");
try (
BufferedReader bufferedReader = new
BufferedReader(new InputStreamReader(System.in));
){
System.out.println("Employee Management
System");

System.out.println("================================");
while(true){
System.out.println();
System.out.println("1. ADD Employee");
System.out.println("2. SEARCH Employee");
System.out.println("3. UPDATE Employee");
System.out.println("4. DELETE Employee");
System.out.println("5. EXIT");
System.out.print("Your Option[1,2,3,4 and
5] : ");
int option =
Integer.parseInt(bufferedReader.readLine());
switch (option){
case 1:
System.out.println("======ADD
MODULE=======");
employeeController.addEmployee();
break;
case 2:
System.out.println("======SEARCH
MODULE=======");

employeeController.searchEmployee();
break;
case 3:
System.out.println("======UPDATE
MODULE=======");

employeeController.updateEmployee();
break;
case 4:
System.out.println("======DELETE
MODULE=======");

employeeController.deleteEmployee();
break;
case 5:
System.out.println("Thank You For
Using Employee Management System Application");
System.exit(0);
break;
default:
System.out.println("Please enter
the values from 1 to 5");
break;
}
}
}catch(Exception exception){
exception.printStackTrace();
}

}
}

EmployeeController.java
package com.durgasoft.controller;

import com.durgasoft.beans.Employee;
import com.durgasoft.service.EmployeeService;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Controller("empController")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;

BufferedReader bufferedReader = new BufferedReader(new


InputStreamReader(System.in));
public void addEmployee(){
try{
String status = "";
System.out.print("Employee Number : ");
int eno =
Integer.parseInt(bufferedReader.readLine());

System.out.print("Employee Name :
");
String ename = bufferedReader.readLine();
System.out.print("Employee Salary :
");
float esal =
Float.parseFloat(bufferedReader.readLine());
System.out.print("Employee Address :
");
String eaddr = bufferedReader.readLine();
Employee employee = new Employee();
employee.setEno(eno);
employee.setEname(ename);
employee.setEsal(esal);
employee.setEaddr(eaddr);

status =
employeeService.addEmployee(employee);
if(status.equalsIgnoreCase("success")){
System.out.println("Status :
SUCCESS");
}
if(status.equalsIgnoreCase("failure")){
System.out.println("Status :
FAILURE");
}
if(status.equalsIgnoreCase("existed")){
System.out.println("Status :
EXISTED");
}
}catch(Exception exception){
exception.printStackTrace();
}

}
public void searchEmployee(){
Employee employee = null;
try {
System.out.print("Employee Number : ");
int eno =
Integer.parseInt(bufferedReader.readLine());
employee =
employeeService.searchEmployee(eno);
if(employee == null){
System.out.println("Status : Employee
Not Existed");
}else{
System.out.println("Status : Employee
Existed");
System.out.println("Employee Details");

System.out.println("----------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Salary :
"+employee.getEsal());
System.out.println("Employee Address :
"+employee.getEaddr());
}
} catch (Exception e) {
e.printStackTrace();
}

}
public void updateEmployee(){
try{
System.out.print("Employee Number : ");
int eno =
Integer.parseInt(bufferedReader.readLine());
Employee emp =
employeeService.searchEmployee(eno);
if(emp == null){
System.out.println("Status : Employee
Not Existed");
}else{
System.out.println("Status : Employee
Existed");
System.out.print("Employee Name [Old:
"+emp.getEname()+" ] New : ");
String ename = bufferedReader.readLine();
if(ename == null ||
ename.equalsIgnoreCase("")){
ename = emp.getEname();
}

System.out.print("Employee Salary [Old:


"+emp.getEsal()+" ] New : ");
String sal = bufferedReader.readLine();
float esal = 0.0f;
if(sal == null ||
sal.equalsIgnoreCase("")){
esal = emp.getEsal();
}else{
esal = Float.parseFloat(sal);
}

System.out.print("Employee Address [Old:


"+emp.getEaddr()+" ] New : ");
String eaddr = bufferedReader.readLine();
if(eaddr == null ||
eaddr.equalsIgnoreCase("")){
eaddr = emp.getEaddr();
}

Employee newEmp = new Employee();


newEmp.setEno(eno);
newEmp.setEname(ename);
newEmp.setEsal(esal);
newEmp.setEaddr(eaddr);

String status =
employeeService.updateEmployee(newEmp);
if(status.equalsIgnoreCase("success")){
System.out.println("Status :
Employee Updated Successfully");
}else{
System.out.println("Status :
Employee Updation Failure");
}
}
}catch(Exception exception){
exception.printStackTrace();
}
}
public void deleteEmployee(){
try {
System.out.print("Employee NUmber : ");
int eno =
Integer.parseInt(bufferedReader.readLine());
Employee employee =
employeeService.searchEmployee(eno);
if(employee == null){
System.out.println("Status : Employee
Not Existed");
}else{
String status =
employeeService.deleteEmployee(eno);
if(status.equalsIgnoreCase("success")){
System.out.println("Status :
Employee Deleted Successfully");
}else{
System.out.println("Status :
Employee Deletion Failure");
}
}

}catch (Exception exception){


exception.printStackTrace();
}
}

EmployeeService.java
package com.durgasoft.service;

import com.durgasoft.beans.Employee;
import com.durgasoft.repository.EmployeeRepository;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
public String addEmployee(Employee employee){
String status = employeeRepository.add(employee);
return status;
}
public Employee searchEmployee(int eno){
Employee employee =
employeeRepository.search(eno);
return employee;
}
public String updateEmployee(Employee employee){
String status =
employeeRepository.update(employee);
return status;
}
public String deleteEmployee(int eno){
String status = employeeRepository.delete(eno);
return status;
}
}

EmployeeRepository.java
package com.durgasoft.repository;

import com.durgasoft.beans.Employee;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.jdbc.datasource.DriverManagerDataSour
ce;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Repository
public class EmployeeRepository {
@Autowired
private DriverManagerDataSource
driverManagerDataSource;
public String add(Employee employee){
String status = "";
try {
Employee emp = search(employee.getEno());
if (emp == null) {
Connection connection =
driverManagerDataSource.getConnection();
PreparedStatement preparedStatement =
connection.prepareStatement("insert into emp1
values(?,?,?,?)");
preparedStatement.setInt(1,
employee.getEno());
preparedStatement.setString(2,
employee.getEname());
preparedStatement.setFloat(3,
employee.getEsal());
preparedStatement.setString(4,
employee.getEaddr());
int rowCount =
preparedStatement.executeUpdate();
if (rowCount == 1) {
status = "Success";
} else {
status = "Failure";
}
}else{
status = "existed";
}
}catch(Exception exception){
exception.printStackTrace();
}
return status;
}

public Employee search(int eno){


Employee employee = null;
try {
Connection connection =
driverManagerDataSource.getConnection();
PreparedStatement preparedStatement =
connection.prepareStatement("select * from emp1 where ENO
= ?");
preparedStatement.setInt(1, eno);
ResultSet resultSet =
preparedStatement.executeQuery();
boolean b = resultSet.next();
if(b == true){
employee = new Employee();
employee.setEno(resultSet.getInt("ENO"));

employee.setEname(resultSet.getString("ENAME"));

employee.setEsal(resultSet.getFloat("ESAL"));

employee.setEaddr(resultSet.getString("EADDR"));
}else{
employee = null;
}
}catch (Exception exception){
exception.printStackTrace();
}
return employee;
}
public String update(Employee employee){
String status = "";
try {
Connection connection =
driverManagerDataSource.getConnection();
PreparedStatement preparedStatement =
connection.prepareStatement("update emp1 set ENAME=?,
ESAL=?, EADDR=? where ENO=?");
preparedStatement.setString(1,
employee.getEname());
preparedStatement.setFloat(2,
employee.getEsal());
preparedStatement.setString(3,
employee.getEaddr());
preparedStatement.setInt(4,
employee.getEno());
int rowCount =
preparedStatement.executeUpdate();
if(rowCount == 1){
status = "success";
}else{
status = "failure";
}
}catch(Exception exception){
exception.printStackTrace();
}
return status;
}
public String delete(int eno){
String status = "";
try{
Connection connection =
driverManagerDataSource.getConnection();
PreparedStatement preparedStatement =
connection.prepareStatement("delete from emp1 where ENO =
?");
preparedStatement.setInt(1, eno);
int rowCount =
preparedStatement.executeUpdate();
if(rowCount == 1){
status = "success";
}else{
status = "failure";
}
}catch(Exception exception){
exception.printStackTrace();
}
return status;
}
}

Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

AppConfig.java
package com.durgasoft.config;

import com.durgasoft.controller.EmployeeController;
import com.durgasoft.repository.EmployeeRepository;
import com.durgasoft.service.EmployeeService;
import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
import
org.springframework.jdbc.datasource.DriverManagerDataSour
ce;

@Configuration
public class AppConfig {
@Bean
public DriverManagerDataSource dataSource(){
DriverManagerDataSource dataSource = new
DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver")
;

dataSource.setUrl("jdbc:mysql://localhost:3306/durgadb");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
@Bean
public EmployeeController employeeController(){
EmployeeController employeeController = new
EmployeeController();
return employeeController;
}
@Bean
public EmployeeService employeeService(){
EmployeeService employeeService = new
EmployeeService();
return employeeService;
}

@Bean
public EmployeeRepository employeeRepository(){
EmployeeRepository employeeRepository = new
EmployeeRepository();
return employeeRepository;
}
}

Q)If we provide both explicit wiring and autowiring in a single bean object then which
wiring will be available in the respective Bean object?
—----------------------------------------------------------------------------------------------------------------
Ans:
—---
In a single Bean object, for a single property, if we provide both explicit wiring and
autowiring then Container will perform Explicit wiring only, in the case if explicit wiring
does not exist then container will search for autowiring.

EX:
Course.java
package com.durgasoft.beans;

public class Course {


private String cid;
private String cname;
private int cfee;
public String getCid() {
return cid;
}

public void setCid(String cid) {


this.cid = cid;
}

public String getCname() {


return cname;
}

public void setCname(String cname) {


this.cname = cname;
}

public int getCfee() {


return cfee;
}

public void setCfee(int cfee) {


this.cfee = cfee;
}
}

Student.java
package com.durgasoft.beans;

public class Student {


private String sid;
private String sname;
private String saddr;
private Course course2;

public String getSid() {


return sid;
}

public void setSid(String sid) {


this.sid = sid;
}

public String getSname() {


return sname;
}

public void setSname(String sname) {


this.sname = sname;
}

public String getSaddr() {


return saddr;
}

public void setSaddr(String saddr) {


this.saddr = saddr;
}

public Course getCourse2() {


return course2;
}

public void setCourse2(Course course2) {


this.course2 = course2;
}

public void getStudentDetails(){


System.out.println("Student Details");
System.out.println("-----------------------");
System.out.println("Student Id : "+sid);
System.out.println("Student Name : "+sname);
System.out.println("Student Address : "+saddr);
System.out.println("Course Details");
System.out.println("---------------------------");
System.out.println("Course Id :
"+course2.getCid());
System.out.println("Course Name :
"+course2.getCname());
System.out.println("Course Fee :
"+course2.getCfee());

}
}

SpringConfig.xml
<?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/cont
ext"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-con
text.xsd">
<bean id="course1" class="com.durgasoft.beans.Course">
<property name="cid" value="C-111"/>
<property name="cname" value="Java"/>
<property name="cfee" value="50000"/>
</bean>
<bean id="course2" class="com.durgasoft.beans.Course">
<property name="cid" value="C-222"/>
<property name="cname" value="Python"/>
<property name="cfee" value="10000"/>
</bean>
<bean id="student" class="com.durgasoft.beans.Student"
autowire="byName">
<property name="sid" value="S-111"/>
<property name="sname" value="AAA"/>
<property name="saddr" value="Hyd"/>
<property name="course2" ref="course1"/>
</bean>

</beans>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Student;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Student student = (Student)
applicationContext.getBean("student");
student.getStudentDetails();
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app18</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>
Drawbacks with Autowiring:
—----------------------------------
1. Auto-wiring is less exact than Explicit Wiring.
2. Auto-wiring is able to inject only Objects, not possible to inject primitive data, but
in explicit wiring we are able to inject both primitive data and Objects data.
3. Auto-wiring is providing less readability when compared with explicit wiring.
4. When compared with Auto-Wiring, Explicit wiring is giving guarantee for
Dependency Injection.
5. Auto-wiring is following the byType approach, if we have more than one bean
object of the same type then Container will raise an exception, it will not be the
problem in Explicit wiring.
6. Auto-wiring is suggestible when we have less number of dependency objects, but
Explicit wiring is suggestible when we have more number dependency objects.
7. If we provide both Auto-wiring and Explicit wiring in a single bean object then
Explicit Wiring dominates Auto-wiring.

Method Injection:
—--------------------
In Spring applications, if we provide a “singleton” scope to any bean object then
Container will create only one bean object per bean definition in the Spring configuration
file.

If we provide prototype scope to a bean object then the container will create a separate
bean object for each and every request for the bean object, that is , for each and every
getBean() method call.

In Spring applications, in Beans association or in dependency injection , if the container


bean and contained bean are having singleton scope then we will not get any problem.

In spring applications, in beans association or in dependency injection, if the container


bean has Singleton scope and if the contained object has prototype scope then for
every request of the Container bean a single container bean object must be return, not
creating a separate new Container bean object every time, but the contained bean must
be created separately for every request, but a single Contained bean object will be
returned for every request of Container bean object, because Container Bean object
has only one Contained bean object reference.

EX:
—--
Token.java
package com.durgasoft.beans;

public class Token {


private String tokenId;
private String query;

public String getTokenId() {


return tokenId;
}

public void setTokenId(String tokenId) {


this.tokenId = tokenId;
}

public String getQuery() {


return query;
}

public void setQuery(String query) {


this.query = query;
}
}

TokenGenerator.java
package com.durgasoft.beans;

public class TokenGenerator {


private String generatorId;
private String generatorName;

private Token token;

public void setToken(Token token) {


this.token = token;
}

public Token getToken() {


return token;
}

public String getGeneratorId() {


return generatorId;
}

public void setGeneratorId(String generatorId) {


this.generatorId = generatorId;
}

public String getGeneratorName() {


return generatorName;
}

public void setGeneratorName(String generatorName) {


this.generatorName = generatorName;
}
}

SpringConfig.xml
<?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/cont
ext"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-con
text.xsd">
<bean id="token" class="com.durgasoft.beans.Token"
scope="prototype">
<property name="tokenId" value="111"/>
<property name="query" value="For Checking Balance
in Account"/>
</bean>
<bean id="tokenGenerator"
class="com.durgasoft.beans.TokenGenerator"
scope="singleton">
<property name="generatorId" value="G-111"/>
<property name="generatorName" value="XXX"/>
<property name="token" ref="token"/>
</bean>
</beans>

Main.java
package com.durgasoft;

import com.durgasoft.beans.TokenGenerator;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
TokenGenerator tokenGenerator =
applicationContext.getBean(TokenGenerator.class);
System.out.println("Token Generator :
"+tokenGenerator);
System.out.println("Token :
"+tokenGenerator.getToken());
System.out.println();

tokenGenerator =
applicationContext.getBean(TokenGenerator.class);
System.out.println("Token Generator :
"+tokenGenerator);
System.out.println("Token :
"+tokenGenerator.getToken());
System.out.println();

tokenGenerator =
applicationContext.getBean(TokenGenerator.class);
System.out.println("Token Generator :
"+tokenGenerator);
System.out.println("Token :
"+tokenGenerator.getToken());

}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app19</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>

If we run the above application then we are able to get the following output.

Token Generator : com.durgasoft.beans.TokenGenerator@18ce0030


Token : com.durgasoft.beans.Token@4445629

Token Generator : com.durgasoft.beans.TokenGenerator@18ce0030


Token : com.durgasoft.beans.Token@4445629

Token Generator : com.durgasoft.beans.TokenGenerator@18ce0030


Token : com.durgasoft.beans.Token@4445629

As per the application requirement we have to get a different token object for every time
of requesting a TokenGenerator and we have to get the same TokenGenerator Object.

To achieve the above requirement, we have to use Method Injection.

There are two ways to perform Method Injection.

1. Look Method Injection


2. Arbitrary Method Replacement.

Look Method Injection:


—---------------------------
In Lookup method injection, we have to request the Spring Framework for creating
contained bean objects as per the scopes without thinking about the Container scope.

If we want to provide Lookup Method Injection in Spring applications then we have to


use the following steps.
1. Declare Container bean class as an abstract class.
2. Declare getXXX() method as an abstract method which is returning Contained
object.[Factory Method].
3. In Spring COnfiguration File, configure getXXX() method as lookup method in
order to generate Contained objects as per the scope.

Token.java
package com.durgasoft.beans;

public class Token {


private String tokenId;
private String query;

public String getTokenId() {


return tokenId;
}

public void setTokenId(String tokenId) {


this.tokenId = tokenId;
}

public String getQuery() {


return query;
}

public void setQuery(String query) {


this.query = query;
}
}
TokenGenerator.java
package com.durgasoft.beans;

public abstract class TokenGenerator {


private String generatorId;
private String generatorName;

private Token token;

public void setToken(Token token) {


this.token = token;
}

public abstract Token getToken();

public String getGeneratorId() {


return generatorId;
}

public void setGeneratorId(String generatorId) {


this.generatorId = generatorId;
}

public String getGeneratorName() {


return generatorName;
}

public void setGeneratorName(String generatorName) {


this.generatorName = generatorName;
}
}

SpringConfig.xml
<?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/cont
ext"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-con
text.xsd">
<bean id="token" class="com.durgasoft.beans.Token"
scope="prototype">
<property name="tokenId" value="111"/>
<property name="query" value="For Checking Balance
in Account"/>
</bean>
<bean id="tokenGenerator"
class="com.durgasoft.beans.TokenGenerator"
scope="singleton">
<property name="generatorId" value="G-111"/>
<property name="generatorName" value="XXX"/>
<property name="token" ref="token"/>
<lookup-method name="getToken" bean="token" />
</bean>
</beans>

Main.java
package com.durgasoft;

import com.durgasoft.beans.TokenGenerator;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
TokenGenerator tokenGenerator =
applicationContext.getBean(TokenGenerator.class);
System.out.println("Token Generator :
"+tokenGenerator);
System.out.println("Token :
"+tokenGenerator.getToken());
System.out.println();

tokenGenerator =
applicationContext.getBean(TokenGenerator.class);
System.out.println("Token Generator :
"+tokenGenerator);
System.out.println("Token :
"+tokenGenerator.getToken());
System.out.println();

tokenGenerator =
applicationContext.getBean(TokenGenerator.class);
System.out.println("Token Generator :
"+tokenGenerator);
System.out.println("Token :
"+tokenGenerator.getToken());

}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app19</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>

If we run the above program then we are able to get the following output.
Token Generator :
com.durgasoft.beans.TokenGenerator$$EnhancerBySpringCGLIB$$f3903c7a@513995
30
Token : com.durgasoft.beans.Token@2b71e916

Token Generator :
com.durgasoft.beans.TokenGenerator$$EnhancerBySpringCGLIB$$f3903c7a@513995
30
Token : com.durgasoft.beans.Token@36fc695d

Token Generator :
com.durgasoft.beans.TokenGenerator$$EnhancerBySpringCGLIB$$f3903c7a@513995
30
Token : com.durgasoft.beans.Token@28701274

In the above program, by using <lookup-method> tag in bean configuration we are able
to send a request to SpringFramework like to take a sub class for the Container class
and to provide implementation for getToken() method dynamically in order to generate
Token object as per the prototype scope.

As per the above request, Spring Framework is able to take dynamic subclasses to the
container and it is able to provide implementation for the getToken() method dynamically
to generate Token objects as per Prototype scope by using the “CGLIB” library
internally.

Method Replacement:
—---------------------------
It is one type of method injection, where we will give an intimation to the Container
about replacing the existing method implementation with some other method
implementation.

To achieve Method replacement in spring applications, we have to declare an user


defined bean class with a method and implementation which we want to replace and we
have to replace the method by taking a class and by implementing “MethodReplacer”
interface.

In the MethodReplacer interface we have a method “reimplement(---) , it will take the


new implementation to replace an existing method implementation.

In the above context, the implementation class of MethodReplacer interface must be


configured as bean and we must configure the method name which we want to replace
by using the following tag.
<replaced-method name=”methodName” replacer=”newBean”/>

EX:
—-
Course.java
package com.durgasoft.beans;

public class Course {


private String cid;
private String cname;
private int cfee;

public String getCid() {


return cid;
}

public void setCid(String cid) {


this.cid = cid;
}

public String getCname() {


return cname;
}

public void setCname(String cname) {


this.cname = cname;
}

public int getCfee() {


return cfee;
}

public void setCfee(int cfee) {


this.cfee = cfee;
}
public void getCourseDetails(){
System.out.println("Course Details");
System.out.println("------------------------");
System.out.println("Course Id : "+cid);
System.out.println("Course Name : "+cname);
System.out.println("Course Fee : "+cfee);
}
}

NewCourse.java
package com.durgasoft.beans;

import org.springframework.beans.factory.support.MethodReplacer;

import java.lang.reflect.Method;

public class NewCourse implements MethodReplacer {


@Override
public Object reimplement(Object o, Method method, Object[] objects)
throws Throwable {
System.out.println("Course Details");
System.out.println("------------------------");
System.out.println("Course Id : C-222");
System.out.println("Course Name : .NET");
System.out.println("Course Cost : 50000");
return null;
}
}

SpringConfig.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="course" class="com.durgasoft.beans.Course">
<property name="cid" value="C-111"/>
<property name="cname" value="Java"/>
<property name="cfee" value="10000"/>
<replaced-method name="getCourseDetails" replacer="newCourse"/>
</bean>
<bean id="newCourse" class="com.durgasoft.beans.NewCourse"/>
</beans>
Main.java
package com.durgasoft;

import com.durgasoft.beans.Course;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Course course = (Course) applicationContext.getBean("course");
course.getCourseDetails();
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app20</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>

Bean validations in Spring Framework:


—------------------------------------
The process of checking whether the data is valid or not before using data
in application’s business logic is called “Data Validations”.

There are two types of Data Validations.


1. Client Side Data Validations
2. Server side Data Validations

Client Side Data Validations:


—-----------------------------
The process of checking whether the data is valid or invalid at client
browser just before submitting a request from client to Server is called
“Client Side Data Validations”.

To perform Client side data validations we have to use Java Script


functions.

Server side Data Validations:


—-----------------------------
The process of checking whether the data is valid or not after getting
data in bean objects and just before using data in the applications
business logic at server side application is called “Server Side Data
Validations”.

We are able to provide Server side data validations by using java code
only.

Note: The MVC based Frameworks like Struts, JSF and Spring Web MVC are
having predefined sub frameworks in the form of “Validator Frameworks” to
perform Server side data validations.
IN Spring Core Applications , to perform data validations in the bean
objects Spring Framework has provided a predefined library in the form of
“org.springframework.validation.Validator” interface.

To provide data validations in spring core applications we have to use the


following steps.

1. Create a properties file with the validation messages.

errors.properties
—-----------------
error.uname.empty = User Name is required.
error.upwd.empty = User Password Is Required.

2. Prepare Validation Class:


a. Declare an user defined class.
b. Implement Validator interface in the user defined class.
c. In the implementation class declare Resource property and its
setter method.
d. Provide implementation for the Validator interface methods.
public boolean supports(Object Type)
public void validate(Object bean, Errors errors)

Where supports() method will check whether the current bean


object is supporting data validations or not.
EX:
public boolean supports(Object type){
return Employee.class.equals(type);
}

Where validate() method will include the actual data


validation logic.

To provide data validations in the validate() method then we


have to use the following steps.
I. Load all the validation messages from Resource
object into the properties Object.
Properties prop =
PropertiesLoaderUtil.getProperties(resource);
II. Check the individual bean properties data, if the
data is invalid then define validation message
along with the property name in Errors object.

public void rejectValue(


String propName,
String errorKey,
String errorMessage)
EX:
if(user.uname == null || user.uname.equals(“”){
errors.rejectValue(“uname”,
“error.uname.empty”,
prop.getProperty(“error.uname.empty”)
}
3. Prepare Spring Configuration file with the Bean configurations.
a. Provide configuration for normal beans.
b. Provide Configuration for Validator bean with the
resource property.
<beans>
<bean id=”user” class=”com.durgasoft.beans.User”>
<property name=”uname” value=””/>
<property name”upwd” value=””/>
</beans>
<bean id=”userValidator” class=”....UserValidator”>
<property name=”resource” value=”Errors.properties”/>
</bean>
</beans>

4. Create a Test class , get all the validation messages and display
all the validation messages.

a. Create an ApplicationContext object.


b. Get a normal Bean Object.
User user = appCntx.getBean(User.class);
c. Get Validator Object.
UserValidator userValidator =
appCntx.getBean(“userValidator”);
d. Access Validate method.
Map map = new HashMap();
MapBindingResults results = new MapBindingResults(map,
“com.durgasoft.beans.User”);
userValidator.validate(user, results);
List<ObjectError> list = results.getAllErrors();
for(ObjectError eo: list){
sopln(eo.getDefaultMessage());
}

EX:

Employee.java
package com.durgasoft.beans;

public class Employee {


private String eid;
private String ename;
private int eage;
private String eemail;
private String emobile;

public String getEid() {


return eid;
}

public void setEid(String eid) {


this.eid = eid;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public int getEage() {


return eage;
}
public void setEage(int eage) {
this.eage = eage;
}

public String getEemail() {


return eemail;
}

public void setEemail(String eemail) {


this.eemail = eemail;
}

public String getEmobile() {


return emobile;
}

public void setEmobile(String emobile) {


this.emobile = emobile;
}

public void getEmployeeDetails(){


System.out.println("Employee Details");
System.out.println("------------------------");
System.out.println("Employee Id : "+eid);
System.out.println("Employee Name : "+ename);
System.out.println("Employee Age : "+eage);
System.out.println("Employee Email : "+eemail);
System.out.println("Employee Mobile : "+emobile);
}
}

EmployeeValidator.java
package com.durgasoft.validator;

import com.durgasoft.beans.Employee;
import org.springframework.core.io.Resource;
import
org.springframework.core.io.support.PropertiesLoaderUtils
;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.io.IOException;
import java.util.Properties;

public class EmployeeValidator implements Validator {

Resource resource;

public void setResource(Resource resource) {


this.resource = resource;
}

@Override
public boolean supports(Class<?> clazz) {
return Employee.class.equals(clazz);
}

@Override
public void validate(Object target, Errors errors) {

try {
Employee employee = (Employee) target;
Properties properties =
PropertiesLoaderUtils.loadProperties(resource);
if(employee.getEid() == null ||
employee.getEid().equals("")){
errors.rejectValue("eid",
"error.eid.empty",
properties.getProperty("error.eid.empty"));
}else{
if(!employee.getEid().startsWith("DSS-")){
errors.rejectValue("eid",
"error.eid.invalid",
properties.getProperty("error.eid.invalid"));
}
}
if(employee.getEname() == null ||
employee.getEname().equals("")){
errors.rejectValue("ename",
"error.ename.empty",
properties.getProperty("error.ename.empty"));
}

if(employee.getEage() == 0){
errors.rejectValue("eage",
"error.eage.empty",
properties.getProperty("error.eage.empty"));
}else{
if(employee.getEage() < 18 ||
employee.getEage() > 25){
errors.rejectValue("eage",
"error.eage.range",
properties.getProperty("error.eage.range"));
}
}
if(employee.getEemail() == null ||
employee.getEemail().equals("")){
errors.rejectValue("eemail",
"error.eemail.empty",
properties.getProperty("error.eemail.empty"));
}else{

if(!employee.getEemail().endsWith("@durgasoft.com")){
errors.rejectValue("eemail",
"error.eemail.invalid",
properties.getProperty("error.eemail.invalid"));
}
}
if(employee.getEmobile() == null ||
employee.getEmobile().equals("")){
errors.rejectValue("emobile",
"error.emobile.empty",
properties.getProperty("error.emobile.empty"));
}else{

if(!employee.getEmobile().startsWith("91-")){
errors.rejectValue("emobile",
"error.emobile.invalid",
properties.getProperty("error.emobile.invalid"));
}else{
String[] items =
employee.getEmobile().split("-");
if(items[1].length() != 10){
errors.rejectValue("emobile",
"error.emobile.invalid",
properties.getProperty("error.emobile.invalid"));
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

errors.properties
error.eid.empty = Employee Id Is Required.
error.eid.invalid = Employee Id is Invalid, Hint: DSS-DDD

error.ename.empty = Employee Name Is Required.

error.eage.empty = Employee Age Is Required.


error.eage.range = Employee Age must be from 18 years
through 25 Years.
error.eemail.empty = Employee Email Id Is Required.
error.eemail.invalid = Employee Email Id is invalid,
Hint: abc@durgasoft.com

error.emobile.empty = Employee Mobile Is Required.


error.emobile.invalid = Employee Mobile Number is
Invalid, Hint: 91-DDDDDDDDDD

SpringConfig.xml
<?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/cont
ext"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-con
text.xsd">
<bean id="employee"
class="com.durgasoft.beans.Employee">
<property name="eid" value="DSS-111"/>
<property name="ename" value="Durga"/>
<property name="eage" value="22"/>
<property name="eemail"
value="durga@durgasoft.com"/>
<property name="emobile" value="91-9988776655"/>
</bean>
<bean id="employeeValidator"
class="com.durgasoft.validator.EmployeeValidator">
<property name="resource"
value="errors.properties"/>
</bean>
</beans>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.validator.EmployeeValidator;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;
import org.springframework.validation.MapBindingResult;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Employee employee = (Employee)
applicationContext.getBean("employee");
employee.getEmployeeDetails();

EmployeeValidator employeeValidator =
(EmployeeValidator)
applicationContext.getBean("employeeValidator");
Map<String, String> map = new HashMap<>();
MapBindingResult mapBindingResult = new
MapBindingResult(map, "com.durgasoft.beans.Employee");
employeeValidator.validate(employee,
mapBindingResult);
List<ObjectError> errors =
mapBindingResult.getAllErrors();
for(ObjectError objectError: errors){

System.out.println(objectError.getDefaultMessage());
}

}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app21</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

Event Handling In Spring Framework:


—------------------------------------------------
In GUI Applications, when we trigger a GUI component like a button, checkbox, radio
button, List box,...... an event will be raised automatically , where the generated event
will not be handled by the GUI components directly, where the generated events are
handled by the components which are provided by the developers internally they are
“Listeners”.

In web applications, Web Container is able to raise the events when we perform life
cycle activities of the request, context and Session objects like
1. Creating Object
2. Destroying Object
3. Adding an Attribute
4. Removing an Attribute
5. Replacing an Attribute

In the above context, to handle the events which are provided by the Web Container we
have to use “Listeners”.

Similarly, Spring IOC Container is able to raise events when we perform the following
actions in Spring applications.

1. When we start Container


2. When we refresh Container
3. When we stop container
4. When we close the container
5. When we handle the request in web applications
To handle all the above events in Spring applications we have to use “Listeners”.

To provide Event Handling in Spring applications Spring has provided the following
predefined library.

1. To represent events, Spring framework has provided the following event classes.
a. ContextStartedEvent
b. ContextRefreshedEvent
c. ContextStoppedEvent
d. ContextClosedEvent
e. RequestHandledEvent
2. To represent Listeners , Spring Framework has provided a predefined interface in
the form of “ApplicationListener”, it has the following method , it will be executed
when the event is raised.

public void onApplicationEvent(ApplicationEvent ae)

If we want to provide Event handling in Spring applications then we have to use the
following steps.

1. Prepare Listener class:


a. Declare an user defined class.
b. Implement ApplicationListener
c. Provide implementation to the onApplicationEvent() method.
EX:
public class ContextStartedEventListener implements
ApplicationListener<ContextStartedEvent>{
public void onApplicationEvent(ContextStartedEvent ae){
—-----
}
}

EX:
public class ContextStoppedEventListener implements
ApplicationListener<ContextStoppedEvent>{
public void onApplicationEvent(ContextStoppedEvent ae){
—-----
}
}
—----
—-----
EX:
public class ContextClosedEventListener implements
ApplicationListener<ContextClosedEvent>{
public void onApplicationEvent(ContextClosedEvent ae){
—-----
}
}

Note: If we want to provide a Listener class for a particular event then we have to
provide the respective event class as generic type to the ApplicationEvent interface.

2. Configure all the Listener classes in the Spring Configuration FIle:


<beans>
<bean is=”cntxStartedEventListener” class=”...ContextStartedEventListener”/>
<bean is=”cntxStoppedEventListener” class=”...ContextStoppedEventListener”/>
<bean is=”cntxRefreshedEventListener”
class=”...ContextRefreshedEventListener”/>
—-----

</beans>

3. Prepare Test Application and create AbstractApplicationContext in order to access


the event methods like start(), stop(), refresh(), close(),....

public class Main{


public static void main(String[] args){
AbstractApplicationContext appContext = new
ClasspathXmlApplicationContext(“SpringConfig.xml”);
appContext.refresh();
appContext.start();
appContext.stop();
appContext.close();
}
}

EX:
—---
ContextRefreshedEventHandler.java
package com.durgasoft.listeners;
import org.springframework.context.ApplicationListener;
import
org.springframework.context.event.ContextRefreshedEvent;

public class ContextRefreshedEventHandler implements


ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent
event) {
System.out.println("ApplicationContext is
Refreshed.......");
}
}

ContextStartedEventHandler.java
package com.durgasoft.listeners;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import
org.springframework.context.event.ContextStartedEvent;

public class ContextStartedEventHandler implements


ApplicationListener<ContextStartedEvent> {
@Override
public void onApplicationEvent(ContextStartedEvent
event) {
System.out.println("ApplicationContext is
Started.........");
}
}

ContextStoppedEventHandler.java
package com.durgasoft.listeners;

import org.springframework.context.ApplicationListener;
import
org.springframework.context.event.ContextStoppedEvent;

public class ContextStoppedEventHandler implements


ApplicationListener<ContextStoppedEvent> {
@Override
public void onApplicationEvent(ContextStoppedEvent
event) {
System.out.println("ApplicationContext is
Stopped......");
}
}

ContextClosedEventHandler.java
package com.durgasoft.listeners;

import org.springframework.context.ApplicationListener;
import
org.springframework.context.event.ContextClosedEvent;

public class ContextClosedEventHandler implements


ApplicationListener<ContextClosedEvent> {
@Override
public void onApplicationEvent(ContextClosedEvent
event) {
System.out.println("ApplicationContext is
Closed.......");
}
}

SpringConfig.xml
<?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/cont
ext"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-con
text.xsd">
<bean id="contextStartedEventHandler"
class="com.durgasoft.listeners.ContextStartedEventHandler
"/>
<bean id="contextRefreshedEventHandler"
class="com.durgasoft.listeners.ContextRefreshedEventHandl
er"/>
<bean id="contextStoppedEventHandler"
class="com.durgasoft.listeners.ContextStoppedEventHandler
"/>
<bean id="contextClosedEventHandler"
class="com.durgasoft.listeners.ContextClosedEventHandler"
/>
</beans>

Main.java
package com.durgasoft;

import
org.springframework.context.support.AbstractApplicationCo
ntext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;
public class Main {
public static void main(String[] args) {
AbstractApplicationContext applicationContext =
new ClassPathXmlApplicationContext("SpringConfig.xml");
applicationContext.start();
applicationContext.refresh();
applicationContext.stop();
applicationContext.close();
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app22</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

Custom Events in Spring Framework:


—-----------------------------------------------
Along with the predefined events, Spring has provided an environment to define our
own events and to handle our own events in our own way.

Steps to prepare and Handle Custom Events in Spring Applications:


1. Create User defined Event class:
a. Declare an user defined class.
b. Extend user defined class from ApplicationEvent class.
c. Create Object parameterized constructor and access super class
constructor.
d. Define methods in Event class as per the requirement.

EX:
public class AccountEvent extends ApplicationEvent{
private String message;
public AcountEvent(Object obj, String message){
super(obj);
this.message = message;
}

public void generateLog(){


Send a message to the log file.
}
}

2. Create User defined Listener class:


a. Declare an user defined class.
b. Implement ApplicationListener interface.
c. Provide implementation to onApplicationEvent() method.

EX:
public class AccountEventListener implements ApplicationListener<AccountEvent>{
public void onApplicationEvent(AccountEvent ae){
ae.generateLog();
}
}

3. Create Event Publisher class:


a. Declare an user defined class.
b. Implement ApplicationEventPublisherAware interface.
c. Provide implement for setApplicationEventPublisher(ApplicationEventPublisher);
d. Create our own publish() method and publish the event.
EX:
public class AccountEventPublisher implements ApplicationEventPublisherAware{
private ApplicationEventPublisher applicationEventPublisher;
public void setApplicationEventPublisher(ApplicationEventPublisher
applicationEventPublisher){
this.applicationEventPublisher = applicationEventPublisher;
}

public void publishAccountEvent(String message){


AccountEvent ae = new AccountEvent(this, message);
applicationEventPublisher.publishEvent(ae);
}
}

4. Create a User defined class and declare the methods and publish events.
a. Declare a bean class.
b. Prepare business methods
c. Inside the business methods publish events.

EX:
public class Account{
private AccountEventPublisher accountEventPublisher;
setXXX();
public void createAccount(){
Sopln(“Account Created…..”);
accountEventPublisher.publishAccountEvent(“Account Created….”);
}
public void searchAccount(){
Sopln(“Search Account…..”);
accountEventPublisher.publishAccountEvent(“Search Account….”);
}
public void updateAccount(){
Sopln(“update Account…..”);
accountEventPublisher.publishAccountEvent(“Update Account….”);
}
public void deleteAccount(){
Sopln(“Delete Account…..”);
accountEventPublisher.publishAccountEvent(“Delete Account….”);
}
}

EX:
AccountEvent.java
package com.durgasoft.event;
import org.springframework.context.ApplicationEvent;

import java.io.FileOutputStream;
import java.time.LocalDateTime;

public class AccountEvent extends ApplicationEvent{


String message;
static FileOutputStream fileOutputStream = null;
static{
try{
fileOutputStream = new FileOutputStream("E:/abc/account.txt", true);
}catch(Exception e){
e.printStackTrace();
}
}
public AccountEvent(Object source, String message) {
super(source);
this.message = message;
}
public void generateLog(){
try{
String logMessage = LocalDateTime.now().toString()+" : "+message+"\n";
fileOutputStream.write(logMessage.getBytes());
}catch (Exception e){
e.printStackTrace();
}
}
}

AccountEventPublisher.java
package com.durgasoft.publisher;

import com.durgasoft.event.AccountEvent;
import
org.springframework.context.ApplicationEventPublisher;
import
org.springframework.context.ApplicationEventPublisherAwar
e;

public class AccountEventPublisher implements


ApplicationEventPublisherAware {
private ApplicationEventPublisher
applicationEventPublisher;
@Override
public void
setApplicationEventPublisher(ApplicationEventPublisher
applicationEventPublisher) {
this.applicationEventPublisher =
applicationEventPublisher;
}
public void publishAccountEvent(String message){
AccountEvent accountEvent = new AccountEvent(this,
message);

applicationEventPublisher.publishEvent(accountEvent);
}
}

AccountEventListener.java
package com.durgasoft.listener;

import com.durgasoft.event.AccountEvent;
import org.springframework.context.ApplicationListener;

public class AccountEventListener implements


ApplicationListener<AccountEvent> {

@Override
public void onApplicationEvent(AccountEvent event) {
event.generateLog();
}
}

Account.java
package com.durgasoft.beans;

import com.durgasoft.publisher.AccountEventPublisher;

public class Account {


private AccountEventPublisher accountEventPublisher;

public void
setAccountEventPublisher(AccountEventPublisher
accountEventPublisher) {
this.accountEventPublisher =
accountEventPublisher;
}

public void createAccount(){


System.out.println("Account created
Successfully......");
accountEventPublisher.publishAccountEvent("Account
Created Successfully.");
}
public void searchAccount(){
System.out.println("Account Existed with the
account number abc123......");
accountEventPublisher.publishAccountEvent("Account
Search Successfull.");
}
public void updateAccount(){
System.out.println("Account Updated
Successfully......");
accountEventPublisher.publishAccountEvent("Account
Updated Successfully....");
}
public void deleteAccount(){
System.out.println("Account Deleted
Successfully......");
accountEventPublisher.publishAccountEvent("Account
Deleted Successfully.....");
}
}

SpringConfig.xml
<?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/cont
ext"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-con
text.xsd">
<bean id="accountEventPublisher"
class="com.durgasoft.publisher.AccountEventPublisher"/>
<bean id="accountEventListener"
class="com.durgasoft.listener.AccountEventListener"/>
<bean id="account"
class="com.durgasoft.beans.Account">
<property name="accountEventPublisher"
ref="accountEventPublisher"/>
</bean>

</beans>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Account;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Account account = (Account)
applicationContext.getBean("account");
account.createAccount();
account.searchAccount();
account.updateAccount();
account.deleteAccount();
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app23</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
Internationalization In Spring Framework:
—---------------------------------------------------
Designing Java applications w.r.t the Users Locale is called Internationalization, in short
I18N.

IN Java applications, we are able to provide a very good I18N Support due to the
UNICODE representations in Java.

If we want to provide I18N in java applications we need some predefined library


provided by JAVA in the form of java.text package, where we have to use the predefined
classes like
1. java.util.Locale
2. java.text.NumberFormat
3. java.text.DateFormat
4. java.util.ResourceBundle

Where java.text.NumberFormat class is able to represent a particular number with a


particular Locale.

Where java.text.DateFormat class is able to represent a particular date with a particular


locale.

Where java.textResourceBundle is able to represent messages with a particular Locale.

EX:
—---
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;

public class Main {


public static void main(String[] args) {
Locale locale = new Locale("hi","IN");

NumberFormat numberFormat =
NumberFormat.getInstance(locale);
System.out.println(numberFormat.format(123456789.34565768
7));

DateFormat dateFormat =
DateFormat.getDateInstance(3,locale);
System.out.println(dateFormat.format(new Date()));

ResourceBundle resourceBundle =
ResourceBundle.getBundle("abc", locale);

System.out.println(resourceBundle.getString("welcome"));

}
}

abc_en_US.properties
—----------------------------
welcome=Welcome To en US Users.

abc_it_IT.properties
—------------------------
welcome = Welcomeo toe it IT Userso

abc_hi_IN.properties
—------------------------
welcome = App ka swagath hi.

To provide Internationalization in Spring applications, Spring has provided some


predefined libraries in the form of the following classes and interfaces.

1. MessageSource.
2. MessageSourceResourceBundle
3. ReloadableMessageSourceResourceBundle

In Spring applications we are able to provide Internationalization service in the following


two ways.

1. By Using Properties file


2. By Using XML file

In Spring Applications, if we want to provide internationalization then we have to use the


following steps.

1. Provide properties files with the messages.


abc_en_US.properties
—---------------------------
welcome = Welcome To en US Users.

abc_it_IT.properties
—-------------------------
welcome = Welcome to it IT Users.

2. Declare a Bean class with MessageSource property and its setter method.
public class I18NBean{
private MessageSource messageSource;
setMessageSource(---);
—---
public void getMessage(){
sopln(messageSource.getMessage(“welcome”, null, Locale.US);
}
}

3. Configure Bean components inside the Spring Configuration file and provide
MessageSourceResourceBundle object configuration.

<beans>
<bean id=”resourceBundleMessageSource”
class=”ResourceBundleMessageSource
”>
<property name=”basename” value=”abc”/>
</bean>
<bean id=”i18n” class=”I18NBean” >
<property name=”messageSource”
ref=”resourceBundleMessageSource
”/>
</bean>
</beans>
4. Prepare Test application and access Business method by getting i18N Bean
object.

ApplicationContext applContext =- new ClassPathXmlApplicationContext(-----);


I18NBean i18N = appContext.getBean(“i18n”);
i18n.getMessage();

Note: If we want to provide messages through XMl files in Internationalization then we


have to use XMl files in place of properties file and we have to use
“ReloadableResourceBundleMessageSource” in place of
ResourceBundleMessageSource.

EX:
—---
abc_en_US.properties
welcome = Welcome to en US Users.

abc_it.properties
welcome = Welcome to it IT Users.

abc_en_US.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM
"http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="welcome">Welcome To en US Users from XML
Configurations</entry>
</properties>

abc_it.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM
"http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="welcome">Welcome To it IT Users from XML
Configurations</entry>
</properties>
I18NBean.java
package com.durgasoft.beans;

import org.springframework.context.MessageSource;

import java.util.Locale;

public class I18NBean {


private MessageSource messageSource;

public void setMessageSource(MessageSource


messageSource) {
this.messageSource = messageSource;
}

public void getMessage(){


System.out.println("Message :
"+messageSource.getMessage("welcome", null, Locale.US));
System.out.println("Message :
"+messageSource.getMessage("welcome", null,
Locale.ITALIAN));
}
}

SpringConfig.xml
<?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/cont
ext"

xsi:schemaLocation="http://www.springframework.org/schema
/beans
https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-con
text.xsd">
<bean id="reloadableResourceBundleMessageSource"
class="org.springframework.context.support.ReloadableReso
urceBundleMessageSource">
<property name="basename" value="abc"/>
</bean>

<bean id="i18n" class="com.durgasoft.beans.I18NBean">


<property name="messageSource"
ref="reloadableResourceBundleMessageSource"/>
</bean>
</beans>

pom.xml
—--------
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app25</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>

Note: ResourceBundleMessageSource is able to work for properties files only, it


is not working for XML files, but ReloadableResourceBundleMessageSource is
working for both properties files and XML files, it will give first priority for
properties files.

If we want to provide dynamic values in the messages we have to use place holders in
the messages inside the properties files.

abc_en_US.properties
—---------------------------
welcome = Welcome to {0} {1} Users.

To provide values to the placeholder we have to use the following method from
MessageSource.

public String getMessage(“welcome”, new Object[]{“en”, “US”}, Locale.US);

EX:
—--
abc_en_US.properties
—---------------------------
welcome = Welcome to {0} {1} Users.

abc_it.properties
—---------------------
welcome = Welcome to {0} {1} Users.

I18NBean.java
package com.durgasoft.beans;

import org.springframework.context.MessageSource;

import java.util.Locale;

public class I18NBean {


private MessageSource messageSource;

public void setMessageSource(MessageSource


messageSource) {
this.messageSource = messageSource;
}

public void getMessage(){


System.out.println("Message :
"+messageSource.getMessage("welcome", new
Object[]{"english","USA"}, Locale.US));
System.out.println("Message :
"+messageSource.getMessage("welcome", new
Object[]{"italian", "ITALY"}, Locale.ITALIAN));
}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.I18NBean;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;
import
org.springframework.context.support.MessageSourceResource
Bundle;
import
org.springframework.context.support.ResourceBundleMessage
Source;

public class Main {


public static void main(String[] args) {

ApplicationContext applicationContext = new


ClassPathXmlApplicationContext("SpringConfig.xml");
I18NBean i18NBean = (I18NBean)
applicationContext.getBean("i18n");
i18NBean.getMessage();
}
}

SpringConfig.xml
<?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/cont
ext"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-con
text.xsd">
<bean id="reloadableResourceBundleMessageSource"
class="org.springframework.context.support.ReloadableReso
urceBundleMessageSource">
<property name="basename" value="abc"/>
</bean>

<bean id="i18n" class="com.durgasoft.beans.I18NBean">


<property name="messageSource"
ref="reloadableResourceBundleMessageSource"/>
</bean>
</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app25</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>

abc_it.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM
"http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="welcome">Welcome To {0} {1} Users from XML
Configurations</entry>
</properties>

abc_en_US.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM
"http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="welcome">Welcome To {0} {1} Users from XML
Configurations</entry>
</properties>

Bean Manipulations And Bean Wrappers:


—-----------------------------------------------------
The process of getting details of a particular bean is called “Introspection”.

In introspection we are able to get details of the bean like properties information and
methods information,......
To get details of a particular bean in introspection we have to use the “BeanInfo”
interface from the java.beans package.

To get a BeanInfo object with the description of a particular bean we have to use the
following method from java.beans.Introspector.

public BeanInfo getBeanInfo(Class cls)


EX: BeanInfo beanInfo =
Introspector.getBeanInfo(com.durgasoft.beans.Employee.class);

If we want to get all the properties details then we have to use the following method

public PropertyDescriptor[] getPropertyDescriptors();

If we want to get all the methods[setXXX(), getXXX()] information we have to use the
following method.

public MethodDescriptor[] getMethodDescriptors()

EX:
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;

import java.beans.*;

public class Main {


public static void main(String[] args) throws
Exception {
BeanInfo beanInfo =
Introspector.getBeanInfo(Employee.class);
PropertyDescriptor[] propertyDescriptors =
beanInfo.getPropertyDescriptors();
for(PropertyDescriptor propertyDescriptor:
propertyDescriptors){
System.out.println(propertyDescriptor);
}
System.out.println();

MethodDescriptor[] methodDescriptors =
beanInfo.getMethodDescriptors();
for(MethodDescriptor methodDescriptor:
methodDescriptors){
System.out.println(methodDescriptor);
}

}
}

To get Bean information Spring Framework has provided some predefined libraries in
the form of the following classes and interfaces.

org.springframework.beans.BeanInfoFactory
org.springframework.beans.ExtendedBeanInfoFactory

EX:

BeanInfoFactory bif = new ExtendedBeanInfoFactory();


BeanInfo beanInfo = bif.getBeanInfo(Employee.class);

Note: The above BeanInfo object is able to read all the details of a particular bean. It
must be a non standard Java bean component, that is , at least one of the setXXX()
methods must violate the rules and regulations of the Java beans.

EX:

Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public int setEno(int eno) {


this.eno = eno;
return 10;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}
public void setEaddr(String eaddr) {
this.eaddr = eaddr;
}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import org.springframework.beans.*;
import java.beans.*;

public class Main {


public static void main(String[] args) throws
Exception {
BeanInfoFactory beanInfoFactory = new
ExtendedBeanInfoFactory();
BeanInfo beanInfo =
beanInfoFactory.getBeanInfo(Employee.class);

PropertyDescriptor[] propertyDescriptors =
beanInfo.getPropertyDescriptors();
for(PropertyDescriptor propertyDescriptor:
propertyDescriptors){
System.out.println(propertyDescriptor);
}
System.out.println();

MethodDescriptor[] methodDescriptors =
beanInfo.getMethodDescriptors();
for(MethodDescriptor methodDescriptor:
methodDescriptors){
System.out.println(methodDescriptor);
}
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app26</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>

Bean Wrappers:
—------------------
The main purpose of Bean Wrappers is
1. To get details from Bean objects.
2. To create Bean objects explicitly.
3. To set values to the Bean objects.
4. To get Values from the Bean objects
5. To copy data from one Bean object to another bean object.
—-----
—----
To represent BeanWrapper objects Spring Framework has provided a predefined
interface in the form of org.springframework.beans.BeanWrapper.

To get a BeanWrapper object we have to use a predefined class like


org.springframework.beans.BeanWrapperImpl.

EX:
BeanWrapper beanWrapper = new BeanWrapperImpl(Employee.class);

To set values to the bean object explicitly then we have to use the following method.

public void setpropertyValue(String propName, Object value)

To set all properties values to the Bean object we have to use the following method.

public void setPropertyValues(Map map)

BeanWrapper beanWrapper = new


BeanWrapperImpl(Employee.class);
Map<String, Object> map = new HashMap<>();
map.put("eno",111);
map.put("ename","Ramesh");
map.put("esal",60000);
map.put("eaddr","Chennai");
beanWrapper.setPropertyValues(map);
To get Property values from BeanWrapper we will use the foll;owing method.

Public Object getPropertyValue(String propName)

To copy the data from One bean to another bean we have to use the following method
from org.springframework.beans.BeanUtils class.

public static void copyProperties(Object oldBean, Object newBean)

EX:
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}
public void setEsal(float esal) {
this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}

public void getEmployeeDetails(){


System.out.println("Employee Details");
System.out.println("------------------------");
System.out.println("Employee Number : "+eno);
System.out.println("Employee Name :
"+ename);
System.out.println("Employee Salary : "+esal);
System.out.println("Employee Address :
"+eaddr);
}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import org.springframework.beans.*;
import java.beans.*;

public class Main {


public static void main(String[] args) throws
Exception {
BeanWrapper beanWrapper = new
BeanWrapperImpl(Employee.class);
beanWrapper.setPropertyValue("eno", 111);
beanWrapper.setPropertyValue("ename", "Durga");
beanWrapper.setPropertyValue("esal", 50000);
beanWrapper.setPropertyValue("eaddr", "Hyd");
Employee employee = (Employee)
beanWrapper.getWrappedInstance();
employee.getEmployeeDetails();
System.out.println(employee);

Employee employee1 = new Employee();


BeanUtils.copyProperties(employee, employee1);
employee1.getEmployeeDetails();
System.out.println(employee1);

}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app26</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

Property Editors:
—----------------------
In Spring applications, we are able to write bean classes as per the requirement and we
must configure bean classes in the Spring configuration file along with the properties
values or constructor argument values.

If we provide bean configurations in Spring configuration file , ApplicationContext


container is able to recognize all the bean configurations , it is able to recognize all the
properties values or constructor argument values then Container is able to create bean
objects with the specified data.

In the above context, we are able to provide properties data in Spring configuration file
[XML file] as a text data , after creating bean objects Container will convert text data
into the respective bean properties types and Container will store the converted data
into the respective variables in bean objects by executing the respective setter methods

In the above context, to convert data from text representation to the respective bean
properties types like int, float, String,....... The ApplicationContext container will use
“Property Editors” internally.

Spring Framework has a number of property Editors internally to convert the data from
text format to the respective bean properties types.
EX:
ByteArrayPropertyEditor
InputStreamPropertyEditor
CustomNumberEditor
CustomBooleanEditor
CustomCollectionEditor
CustomURLEditor
—---
—---

Spring is able to allow us to provide our own Property Editors as per the requirement.

To provide our own custom property editors we have to use the following steps.

1. Prepare a Bean class as per the requirement.


EX:
public class Address{
private String hno;
private String street;
private String city;
private String state;
private String country;
setXXX() and getXXX()
}
public class Employee{
private int eno;
private String ename;
private float esal;
private Address eaddr;
setXxx(), getXxx()
}

2. Prepare User defined Property Editor:


a. Declare an user defined class.
b. extends “PropertyEditorSupport” class
c. Implement the following method of PropertyEditorSupport class.
public void setAsText(---,----)
EX:
public class EmployeeAddressEditor extends PropertyEditorSupport{
public void setAsText(Object bean, String value){
—-----
}
}
3. Prepare Configuration file .
In the Spring configuration file we have to provide the following configurations.
a. Provide Beans configuration
b. Provide CustomEditorConfigurer as a bean
c. In CustomEditorConfigurer declare “customEditors” property of type map, where
defined an entry with the Key Bean and with the Property Editor value.

<beans>
<bean id=”emp” class=”com.durgasoft.beans.Employee”>
—----
<property name=”eaddr” value=”H-123, MG Road, Hyd, Telangana, India”/>
</bean>
<bean name=”customEditorConfigurer” class=”...CustomEditorConfigurer”>
<property name=”customEditors”>
<map>
<entry key=”Address” value=”EmployeeAddressEditor”/>
</map>
</property>
</bean>
</beans>

4. Prepare Test application and execute Test application.

EX:
Address.java
package com.durgasoft.beans;

public class Address {


private String hno;
private String street;
private String city;
private String state;
private String country;

public String getHno() {


return hno;
}

public void setHno(String hno) {


this.hno = hno;
}

public String getStreet() {


return street;
}

public void setStreet(String street) {


this.street = street;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

public String getState() {


return state;
}

public void setState(String state) {


this.state = state;
}

public String getCountry() {


return country;
}

public void setCountry(String country) {


this.country = country;
}
}

Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private Address eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public Address getEaddr() {


return eaddr;
}

public void setEaddr(Address eaddr) {


this.eaddr = eaddr;
}
public void getEmployeeDetails(){
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number : "+eno);
System.out.println("Employee Name :
"+ename);
System.out.println("Employee Salary : "+esal);
System.out.println();

System.out.println("Employee Address Details");

System.out.println("-----------------------------");
System.out.println("House Number :
"+eaddr.getHno());
System.out.println("Street :
"+eaddr.getStreet());
System.out.println("City :
"+eaddr.getCity());
System.out.println("State :
"+eaddr.getState());
System.out.println("Country :
"+eaddr.getCountry());
}
}
EmployeeAddressEditor.java
package com.durgasoft.editors;

import com.durgasoft.beans.Address;

import java.beans.PropertyEditorSupport;

public class EmployeeAddressEditor extends


PropertyEditorSupport {
@Override
public void setAsText(String text) throws
IllegalArgumentException {
try{
String[] items = text.split(",");
Address address = new Address();
address.setHno(items[0]);
address.setStreet(items[1]);
address.setCity(items[2]);
address.setState(items[3]);
address.setCountry(items[4]);
super.setValue(address);
}catch(Exception e){
e.printStackTrace();
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;

public class Main {


public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
Employee employee = (Employee)
applicationContext.getBean("employee");
employee.getEmployeeDetails();
}
}

SpringConfig.xml
<?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/cont
ext"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd
http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-con
text.xsd">
<bean id="employee"
class="com.durgasoft.beans.Employee">
<property name="eno" value="111"/>
<property name="ename" value="Durga"/>
<property name="esal" value="50000"/>
<property name="eaddr" value="H-121, MGRoad, Hyd,
Telangana, India"/>
</bean>
<bean id="customEditorConfigurer"
class="org.springframework.beans.factory.config.CustomEdi
torConfigurer">
<property name="customEditors">
<map>
<entry key="com.durgasoft.beans.Address"
value="com.durgasoft.editors.EmployeeAddressEditor"/>
</map>
</property>
</bean>
</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app27</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

Profiles:
—--------
In general, every software application will have the following lifecycle stages
1. Development
2. Testing
3. Production

At each and every software application lifecycle phase we have to use different
components, configurations,.....

It is not suggestible to provide all the configuration details in our application at each and
every lifecycle phase, where we need an automated approach to provide configurations
to the project depending on the lifecycle phase, for this we have to use “Profiles”.

To provide profiles in our applications, Spring Core module has provided the following
approach.
1. Create a separate configuration file for each and every profile[Lifecycle phase]:
Here the configuration file name must be provided in the following format.
fileName-profileName.xml

At each and every configuration file we must provide a profile name in <beans>
Tag.
<beans ……… profile=”profileName”>
—---
</beans>

SpringConfig-Development.xml
<beans —-- profile=”Development”>
—---Development configurations—----
</beans>

SpringConfig-Testing.xml
<beans —-- profile=”Testing”>
—---Testing configurations—----
</beans>

SpringConfig-Production.xml
<beans —-- profile=”Production”>
—---Production configurations—----
</beans>

2. Prepare Bean components as per the requirement.


3. Provide profile name as an input.
System.setProperty(“spring.profiles.active”, “Development”);

4. Use GenericXmlApplicationContext and load all the configuration files.

appContext.load(“SpringConfig-Development.xml, SpringConfig-Testing.xml,
SpringConfig-Production.xml”);

EX:
—---
Employee.java
package com.durgasoft.beans;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Employee {
public Employee(){
System.out.println("Employee Objecty is
created......");
}
private String driverClassName;
private String driverURL;
private String dbUserName;
private String dbPassword;

public String getDriverClassName() {


return driverClassName;
}

public void setDriverClassName(String driverClassName)


{
this.driverClassName = driverClassName;
}

public String getDriverURL() {


return driverURL;
}

public void setDriverURL(String driverURL) {


this.driverURL = driverURL;
}

public String getDbUserName() {


return dbUserName;
}

public void setDbUserName(String dbUserName) {


this.dbUserName = dbUserName;
}
public String getDbPassword() {
return dbPassword;
}

public void setDbPassword(String dbPassword) {


this.dbPassword = dbPassword;
}

public void getEmployeeDetails(){


try{
Class.forName(driverClassName);
Connection connection =
DriverManager.getConnection(driverURL,dbUserName,
dbPassword);
Statement statement =
connection.createStatement();
ResultSet resultSet =
statement.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");

System.out.println("--------------------------------");
while(resultSet.next()){

System.out.print(resultSet.getInt("ENO")+"\t");

System.out.print(resultSet.getString("ENAME")+"\t\t");

System.out.print(resultSet.getFloat("ESAL")+"\t");

System.out.print(resultSet.getString("EADDR")+"\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
SpringConfig-Development.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd" profile="Development">
<bean name="employee"
class="com.durgasoft.beans.Employee">
<property name="driverClassName"
value="oracle.jdbc.OracleDriver"/>
<property name="driverURL"
value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="dbUserName" value="system"/>
<property name="dbPassword" value="durga"/>
</bean>
</beans>

SpringConfig-Production.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd" profile="Production">
<bean name="employee"
class="com.durgasoft.beans.Employee">
<property name="driverClassName"
value="com.mysql.cj.jdbc.Driver"/>
<property name="driverURL"
value="jdbc:mysql://localhost:3306/durgadb"/>
<property name="dbUserName" value="root"/>
<property name="dbPassword" value="root"/>
</bean>
</beans>

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import
org.springframework.context.support.GenericXmlApplication
Context;

public class Main {


public static void main(String[] args) {
System.setProperty("spring.profiles.active",
"Production");
GenericXmlApplicationContext applicationContext =
new GenericXmlApplicationContext();

applicationContext.load("SpringConfig-Development.xml");

applicationContext.load("SpringConfig-Production.xml");
applicationContext.refresh();

Employee employee =
applicationContext.getBean(Employee.class);
employee.getEmployeeDetails();
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app28</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>oracle</groupId>
<artifactId>oracle-ojdbc</artifactId>
<version>21-xe</version>
</dependency>
<!--
https://mvnrepository.com/artifact/mysql/mysql-connector-
java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>

</dependencies>

</project>

Spring Expression Language[SpEL]:


—----------------------------------------------
An Expression language is like a Scripting language or a programming language, it is
able to provide simple syntaxes to perform operations.

JSP EL: It will be used in JSP pages to perform some jsp operations.
Struts2.x OGNL: It is able to perform operations as per the struts applications.
SpEL: It is able to provide simple syntaxes to perform operations in spring applications.

In Spring applications SpEL is able to perform the operations with the bean objects and
their properties.

To perform operations with SpEl in spring applications, Spring Framework has provided
some predefined library in the form of org.springframework.expression.

To perform Operations with SpEL we have to use the following steps.

1. Create ExpressionParser object:


ExpressionParser is an object, it is able to represent an expression and it is able to
evaluate that expression.

To represent ExpressionParser Spring Framework has provided a predefined interface


in the form of “ExpressionParser” and its implementation class is provided in the form of
“SpelExpressionParser”.

ExpressionParser parser = new SpelExpressionParser();


2. Create Expression Object:
To represent and evaluate an expression and to hold the result of that expression we
will use an Expression object.

To create an Expression object we have to use the following method from


ExpressionParser.

public Expression parseExpression(String expression)


EX:
Expression expr = parser.parseExpression(“10+20”);

3. Get the result from Expression object:


To get the result from the Expression object we have to use the following method.

public xxx getValue()


EX:
int result = expr.getValue();

EX:
—---
Main.java
—---------
package com.durgasoft;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import
org.springframework.expression.spel.standard.SpelExpressi
onParser;

public class Main {


public static void main(String[] args) {
ExpressionParser expressionParser = new
SpelExpressionParser();
Expression expression1 =
expressionParser.parseExpression("10+20");

System.out.println(expression1.getExpressionString()+" :
"+expression1.getValue());
Expression expression2 =
expressionParser.parseExpression("20-10");

System.out.println(expression2.getExpressionString()+" :
"+expression2.getValue());

Expression expression3 =
expressionParser.parseExpression("10*20");

System.out.println(expression3.getExpressionString()+" :
"+expression3.getValue());

}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app29</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

In Spring Expression Language, all the expressions are evaluated by the


ExpressionParser with the help of StandardEvaluationContext.

StandardEvaluationContext is a context object in Spel, it is able to manage all the


variables of the expression, beans of the expression and their values.....

To represent StandardEvaluationContext, Spring Framework has provided a predefined


class in the form of “StandardEvaluationContext”.

If we want to use StandardEvaluationContext in Spring applications we have to use the


following steps.

1. Create Bean Object as per the requirement.


public class MyBean{
private int num1;
private int num2;
setXxx() and getXxx()
public int add(){
return num1+num2;
}
}
MyBean mb = new MyBean();

2. Create StandardEvaluationContext object by passing bean object.


StandardEvaluationContext context = new StandardEvaluationContext(mb);

3. Set values to the properties which are managed by the StandardEvaluationContext


through the expressions.

ExpressionParser parser = new SpelExpressionParser();

Expression expr1 = parser.parseExpression(“num1”);


expr1.setValue(context, 10);

Expression expr2 = parser.parseExpression(“num2”);


expr2.setValue(context, 50);

4. Perform the operations with the bean methods.

mb.add();

EX:
Calculator.java
package com.durgasoft.beans;

public class Calculator {


private int num1;
private int num2;

public int getNum1() {


return num1;
}

public void setNum1(int num1) {


this.num1 = num1;
}
public int getNum2() {
return num2;
}

public void setNum2(int num2) {


this.num2 = num2;
}

public int add(){


return num1+num2;
}
public int sub(){
return num1 - num2;
}
public int mul(){
return num1 * num2;
}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Calculator;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import
org.springframework.expression.spel.standard.SpelExpressi
onParser;
import
org.springframework.expression.spel.support.StandardEvalu
ationContext;

public class Main {


public static void main(String[] args) {
Calculator calculator = new Calculator();
StandardEvaluationContext context = new
StandardEvaluationContext(calculator);
ExpressionParser expressionParser = new
SpelExpressionParser();
Expression expression1 =
expressionParser.parseExpression("num1");
Expression expression2 =
expressionParser.parseExpression("num2");

expression1.setValue(context, 10);
expression2.setValue(context, 5);

System.out.println("ADD : "+calculator.add());
System.out.println("SUB : "+calculator.sub());
System.out.println("MUL : "+calculator.mul());

}
}

Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app29</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.source
Encoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

In SpEL, to prepare expressions we have to use the following elements.

1. Expressions
2. Operators
3. Variables
4. Methods
5. Collections

1. Expressions:
Expression is a collection of characters, operators, digits,...... to perform a particular
operation.

There are two types of Expressions in SpEL.


1. Literal Expressions
2. Regular Expressions

1. Literal Expressions:
These expressions include only literals.
2. Regular Expressions:
These expressions are able to allow regular expressions to check whether the string is
as per the regular expression or not.

If the String is matched with the regular expression then it will return true value.
If the String is not matched with the regular expression then it will return a false value.

To compare a string with the regular expression we will use ‘matches’ operator, it is a
boolean operator, it will check whether the provided String matches the regular
expression or not.

Syntax:

StringData matches RegularExpression

EX:
Main.java
package com.durgasoft;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

public class Main {


public static void main(String[] args) {
ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression1 = expressionParser.parseExpression("10+10");
System.out.println(expression1.getValue());

Expression expression2 =
expressionParser.parseExpression("'Durga'+'soft'");
System.out.println(expression2.getValue());

Expression expression3 = expressionParser.parseExpression("'Spring'


matches 'Sp.*'");
System.out.println(expression3.getValue());

Expression expression4 =
expressionParser.parseExpression("'durga@durgasoft.com' matches
'[a-z]*@durgasoft.com'");
System.out.println(expression4.getValue());
}
}
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app30</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

2. Operators:
—----------------
Operator is a symbol, it is able to perform a particular operation over the provided
operands.

To prepare Expressions, Spring Framework has provided the following operators.


1. Arithmetic Operators:
+,-,*,/,%,.....

2. Logical Operators:
and or &&
or or ||
not or !
3. Comparison Operators:
eq or ==
ne or !=
lt or <
le or <=
gt or >
ge or >=
—--
—---

4. Ternary Operator:
Expr1?Expr2:Expr3;

5. Type Operator:
It is able to represent a particular class type or interface type in Expressions.

Syntax: T(ClassName)

6. Safe Navigation Operator:


In general, in java applications, if we access any instance variable or instance
method on a reference variable containing null value then JVM will raise an
exception like java.lang.NullPointerException.

In SpEL, to avoid null pointer exceptions we have to use “Safe Navigation”


operator.

EX:
Main.java
package com.durgasoft;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Date;
class User{
private String uname;

public void setUname(String uname) {


this.uname = uname;
}
public String getUname() {
return uname;
}
}
public class Main {
public static void main(String[] args) {
ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression1 = expressionParser.parseExpression("10+20*2/4");
System.out.println(expression1.getValue());

Expression expression2 = expressionParser.parseExpression("true && false


|| true and false or true");
System.out.println(expression2.getValue());

Expression expression3 = expressionParser.parseExpression("10 ne 20");


System.out.println(expression3.getValue());

Expression expression4 = expressionParser.parseExpression("20 lt 10");


System.out.println(expression4.getValue());

Expression expression5 = expressionParser.parseExpression("10 eq


10?'Condition is true':'Condition is False'");
System.out.println(expression5.getValue());

Expression expression6 =
expressionParser.parseExpression("T(Thread).MIN_PRIORITY");
System.out.println(expression6.getValue());

User user = new User();


StandardEvaluationContext context = new StandardEvaluationContext(user);
Expression expression7 =
expressionParser.parseExpression("uname?.toUppercase()");
System.out.println(expression7.getValue(context));
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app30</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

3. Variables:
—---------------
In SpEL, if we want to access the variables which are already available in the
StandardEvaluationContext then we have to use the following syntax.

#varName

If we want to set a variable to the StandardEvaluationContext then we have to use the


following method.

public void setVariable(String varName, Object value)

EX:
—--
Main.java
package com.durgasoft;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

class Calculator{
private int num1;
private int num2;
public int getNum1() {
return num1;
}

public void setNum1(int num1) {


this.num1 = num1;
}

public int getNum2() {


return num2;
}

public void setNum2(int num2) {


this.num2 = num2;
}
public int add(){
return num1 + num2;
}
public int sub(){
return num1 -num2;
}
public int mul(){
return num1 * num2;
}

}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
StandardEvaluationContext context = new
StandardEvaluationContext(calculator);
context.setVariable("number1", 10);
context.setVariable("number2", 5);
ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression1 = expressionParser.parseExpression("num1 =
#number1");
Expression expression2 = expressionParser.parseExpression("num2 =
#number2");
expression1.getValue(context);
expression2.getValue(context);
System.out.println(calculator.add());
System.out.println(calculator.sub());
System.out.println(calculator.mul());

}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app30</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

4. Method Invocations:
—--------------------------
Method is a set of instructions representing a particular action.

In SpEL, to represent the method and to access the method we have to use the
following steps.

1. Create StandardEvaluationContext
2. Register Method with the name.
public void registerFunction(String methodName, Method m)
3. Prepare an Expression with method call and access the method

EX:
package com.durgasoft;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;

class MyString{
public static void reverseString(String str){
StringBuffer stringBuffer = new StringBuffer(str);
System.out.println(stringBuffer.reverse());
}
}
public class Main {
public static void main(String[] args)throws Exception {
StandardEvaluationContext context = new StandardEvaluationContext();
Class cls = Class.forName("com.durgasoft.MyString");
Method method = cls.getDeclaredMethod("reverseString", String.class);
context.registerFunction("reverse", method);
context.setVariable("str", "Durga Software Solutions");

ExpressionParser expressionParser = new SpelExpressionParser();


Expression expression =
expressionParser.parseExpression("#reverse(#str)");
expression.getValue(context);

expression = expressionParser.parseExpression("'Durga Software


Solutions'".toUpperCase());
System.out.println(expression.getValue());

}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app30</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

4. Collections:
—------------------------
Collection is a group of objects.

In SpEL, we are able to define Collections and we are able to access the content of the
Collection.

Syntax:
Collection_Ref.?Condition_Expression

EX:
Main.java
package com.durgasoft;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;
import java.util.ArrayList;

class CityState{
private String city;
private String state;

public CityState(String city, String state) {


this.city = city;
this.state = state;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

public String getState() {


return state;
}

public void setState(String state) {


this.state = state;
}

public String toString(){


return city+"==>"+state;
}
}

class CityStateCollection{
private ArrayList<CityState> cityStates = new ArrayList<>();
public ArrayList<CityState> getCityState(){
cityStates.add(new CityState("Hyd", "Telangana"));
cityStates.add(new CityState("Vizayawada", "Andhra"));
cityStates.add(new CityState("Warangal", "Telangana"));
cityStates.add(new CityState("Tirupati", "Andhra"));
cityStates.add(new CityState("Karim Nagar", "Telangana"));
cityStates.add(new CityState("Vizag", "Andhra"));
cityStates.add(new CityState("Mahaboob Nagar", "Telangana"));
return cityStates;
}
}
public class Main {
public static void main(String[] args)throws Exception {
CityStateCollection cityStateCollection = new CityStateCollection();
StandardEvaluationContext context = new
StandardEvaluationContext(cityStateCollection);
ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression1 =
expressionParser.parseExpression("cityState.?[state == 'Andhra']");
ArrayList<CityState> al1 = (ArrayList<CityState>)
expression1.getValue(context);
System.out.println(al1);
Expression expression2 =
expressionParser.parseExpression("cityState.?[state == 'Telangana']");
ArrayList<CityState> al2 = (ArrayList<CityState>)
expression2.getValue(context);
System.out.println(al2);
}
}

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>app30</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

</project>

=======================================================================
Spring Config file Dependencies:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

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

P-Namespace XSD
<beans
xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="http://www.springframework.org/schema
/beans

https://www.springframework.org/schema/beans/spring-beans
.xsd">

C-Namespace XSD
<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"

xsi:schemaLocation="http://www.springframework.org/schema
/beans
https://www.springframework.org/schema/beans/spring-beans
.xsd">
</beans>

Context XSD
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

Class notes Link: https://tinyurl.com/spring830amnotes

www.durgasoftonlinetraining@gmail.com
8885252627
9246212143
7386095600

You might also like