Spring 830
Spring 830
Spring 830
com/register/2348474801872643416
SPRING
—-----------
Java Frameworks
1. Hibernate
2. Spring
3. Spring Boot
4. Microservices
5. Web Services
MAVEN, LOG4J
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.
2. To prepare the Data Storage and Access layer we will use a separate logic called
“Persistence Logic”.
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.
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.
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”.
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.
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 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].
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.
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
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.
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
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.
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.
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”;
}
}
To provide beans configuration in the Spring configuration file we have to use the
following tags.
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]
EX:
SpringConfig.xml
—---------------------
Creating a Container:
—--------------------------
The Main purpose of Container is to create bean objects and to manage bean objects
along with their identities.
When we create a Container object like above, Container will perform the following
actions.
4. After creating bean objects, Container will manage all the bean objects along
with their identity values [id attribute values].
package com.durgasoft.beans;
SpringConfig.xml
<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;
}
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.
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;
return name;
this.name = name;
return message;
this.message = message;
}
public String sayWelcome() {
SpringConfig.xml
<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>
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationC
ontext;
import com.durgasoft.beans.Welcome;
System.out.println(welcome.sayWelcome());
Ex3:
Employee.java
package com.durgasoft.beans;
return eno;
this.eno = eno;
return ename;
this.ename = ename;
return esal;
}
public void setEsal(float esal) {
this.esal = esal;
return eaddr;
this.eaddr = eaddr;
System.out.println("Employee Details");
System.out.println("----------------------");
}
}
SpringConfig.xml
<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">
</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;
Employee employee =
(Employee)applicationContext.getBean("employee");
employee.displayEmployeeDetails();
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");
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.
Resource is an object, it is able to represent all the configuration details of the Spring
Configuration file.
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;
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.
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.
EX:
ApplicationContext context = new ClassPathXmlApplicationContext(“SpringConfig.xml”);
EX:
Customer.java
package com.durgasoft.beans;
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.
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.
5. BeanFactory is not supporting the spring modules like Spring ORM, Spring
Tx,....
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.
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.
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.
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.
<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>
EX3:
<beans>
<bean id=”hello1,hello2,hello3” class=”com.durgasoft.beans.Hello”/>
</beans>
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>
EX6:
<beans>
<bean name=”hello1,hello2,hello3” class=”com.durgasoft.beans.Hello”/>
</beans>
EX7:
<beans>
<bean name=”hello1;hello2;hello3” class=”com.durgasoft.beans.Hello”/>
</beans>
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>
In the Spring configuration file, we are able to provide alias names to the beans
explicitly by using <alias> tag.
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>
EX:
Wish.java
package com.durgasoft.beans;
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;
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>
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>
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.
@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();
EX:
—---
Hello.java
package com.durgasoft.beans;
import java.util.HashMap;
import java.util.Map;
ThreadScope.java
package com.durgasoft.scope;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import java.util.Map;
@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;
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.
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.
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);
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;
Welcome.java
package com.durgasoft.beans;
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;
}
}
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.
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;
Welcome.java
package com.durgasoft.beans;
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(){
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;
If we want to define user defined scopes to the bean components in Java Based
configurations then we have to use the following steps.
EX:
—--
Wish.java
package com.durgasoft.beans;
Welcome.java
package com.durgasoft.beans;
Hello.java
package com.durgasoft.beans;
MyThreadLocale.java
package com.durgasoft.scope;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import java.util.Map;
@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;
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.
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”);
EX:
Welcome.java
public class Welcome{
private String name;
Private String 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;
Welcome.java
package com.durgasoft.beans;
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");
}
}
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”);
EX:
public class 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;
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;
}
}
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();
In Spring applications there are three ways to perform Bean Initialization and
Destruction .
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;
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;
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;
Hello.java
package com.durgasoft.beans;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
}
Wish.java
package com.durgasoft.beans;
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;
applicationContext.registerShutdownHook();
}
}
Op:
setName().....
init()-Hello class.....
init()-Welcome class.....
init()-Wish class.....
Hello Durga
EX:
—--
Hello.java
package com.durgasoft.beans;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
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;
applicationContext.registerShutdownHook();
}
}
Op:
setName().....
init2()-Hello class.....
Hello Durga
destroy2()-Hello class....
Where DisposableBean callback interface has the following method, it will be executed
by the container automatically when the container performs Bean Destruction.
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;
@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;
EX:
Hello.java
package com.durgasoft.beans;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@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().....");
}
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;
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;
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;
Output:
Bean Loading.....
Bean Instantiation though Constructor...
setName().....
initialize() - @PostConstruct - Hello Bean class......
afterPropertiesSet()-InitializingBean-Hello Bean class.....
init1()-Hello class.....
Hello Durga
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>
EX:
—--
Wish.java
package com.durgasoft.beans;
Hello.java
package com.durgasoft.beans;
Hi.java
package com.durgasoft.beans;
public class Hi {
private String name;
private String 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");
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;
Hi.java
—-------
package com.durgasoft.beans;
public class Hi {
private String name;
private String 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;
Employee.java
package com.durgasoft.beans;
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.
<beans>
—----
<bean class=”com.durgasoft.beans.BeanPostProcessorImpl”/>
—-----
</beans>
EX:
Institute.java
package com.durgasoft.beans;
BeanPostProcessorImpl.java
package com.durgasoft.beans;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
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;
BeanPostProcessorImpl.java
package com.durgasoft.beans;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
@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;
Welcome.java
package com.durgasoft.beans;
Wish.java
package com.durgasoft.beans;
BeanPostProcessorImpl.java
package com.durgasoft.beans;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
@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;
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()......
BeanPostProcessorImpl1.java
package com.durgasoft.beans;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
BeanPostProcessorImpl2.java
package com.durgasoft.beans;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
@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;
@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;
Output:
postProcessBeforeInitialization() - BeanPostProcessorImpl1
postProcessBeforeInitialization() - BeanPostProcessorImpl2
postProcessBeforeInitialization() - BeanPostProcessorImpl3
init() Method......
postProcessAfterInitialization() - BeanPostProcessorImpl1
postProcessAfterInitialization() - BeanPostProcessorImpl2
postProcessAfterInitialization() - BeanPostProcessorImpl3
Hello User!
destroy() Method........
EX:
—-
Hello.java
package com.durgasoft.beans;
BeanPostProcessorImpl1.java
package com.durgasoft.beans;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;
@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;
@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;
@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;
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.
EX:
—-
Wish.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;
@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;
Output:
from postProcessBeanFactory()-BeanFactoryPostProcessorImpl
from setWishMessage()-Wish Bean....Good Morning!
Hello User, Good Morning!
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.
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.
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.
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".
EX:
Customer.java
package com.durgasoft.beans;
Item.java
package com.durgasoft.beans;
Order.java
package com.durgasoft.beans;
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">
Main.java
package com.durgasoft;
import com.durgasoft.beans.Order;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
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>
EX:
Item.java
package com.durgasoft.beans;
Cart.java
package com.durgasoft.beans;
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;
Movie.java
package com.durgasoft.beans;
}
}
Main.java
package com.durgasoft;
import com.durgasoft.beans.Movie;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
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 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;
Student.java
package com.durgasoft.beans;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
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;
EX:
Student.java
package com.durgasoft.beans;
Branch.java
package com.durgasoft.beans;
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;
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?
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;
}
}
Branch.java
package com.durgasoft.beans;
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;
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;
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;
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.
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.
It is very simple to modify the values in bean objects through Setter method
dependency injection.
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.
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.
<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;
Employee.java
package com.durgasoft.beans;
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;
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;
Course.java
package com.durgasoft.beans;
}
}
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;
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>
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>
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 .
<beans>
<bean autowire=”value”>
—----
</bean>
—----
</beans>
EX:
Address.java
package com.durgasoft.beans;
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;
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="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>
/>
<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;
Account.java
package com.durgasoft.beans;
Employee.java
package com.durgasoft.beans;
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>
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.
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.
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.
<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;
Student.java
package com.durgasoft.beans;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.beans.factory.annotation.Qualifier;
}
}
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;
Album.java
package com.durgasoft.beans;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.beans.factory.annotation.Qualifier;
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;
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 .
Note: In all the above cases , we must provide beans configuration in the 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. @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.
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;
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;
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();
}
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");
}
}
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;
}
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>
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;
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;
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();
}
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");
}
}
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;
}
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;
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;
Student.java
package com.durgasoft.beans;
}
}
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;
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.
EX:
—--
Token.java
package com.durgasoft.beans;
TokenGenerator.java
package com.durgasoft.beans;
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;
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.
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.
Token.java
package com.durgasoft.beans;
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;
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.
EX:
—-
Course.java
package com.durgasoft.beans;
NewCourse.java
package com.durgasoft.beans;
import org.springframework.beans.factory.support.MethodReplacer;
import java.lang.reflect.Method;
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;
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>
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.
errors.properties
—-----------------
error.uname.empty = User Name is required.
error.upwd.empty = User Password Is Required.
4. Create a Test class , get all the validation messages and display
all the validation messages.
EX:
Employee.java
package com.durgasoft.beans;
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;
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
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="[email protected]"/>
<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;
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>
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.
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.
If we want to provide Event handling in Spring applications then we have to use the
following steps.
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.
</beans>
EX:
—---
ContextRefreshedEventHandler.java
package com.durgasoft.listeners;
import org.springframework.context.ApplicationListener;
import
org.springframework.context.event.ContextRefreshedEvent;
ContextStartedEventHandler.java
package com.durgasoft.listeners;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import
org.springframework.context.event.ContextStartedEvent;
ContextStoppedEventHandler.java
package com.durgasoft.listeners;
import org.springframework.context.ApplicationListener;
import
org.springframework.context.event.ContextStoppedEvent;
ContextClosedEventHandler.java
package com.durgasoft.listeners;
import org.springframework.context.ApplicationListener;
import
org.springframework.context.event.ContextClosedEvent;
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>
EX:
public class AccountEvent extends ApplicationEvent{
private String message;
public AcountEvent(Object obj, String message){
super(obj);
this.message = message;
}
EX:
public class AccountEventListener implements ApplicationListener<AccountEvent>{
public void onApplicationEvent(AccountEvent ae){
ae.generateLog();
}
}
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;
AccountEventPublisher.java
package com.durgasoft.publisher;
import com.durgasoft.event.AccountEvent;
import
org.springframework.context.ApplicationEventPublisher;
import
org.springframework.context.ApplicationEventPublisherAwar
e;
applicationEventPublisher.publishEvent(accountEvent);
}
}
AccountEventListener.java
package com.durgasoft.listener;
import com.durgasoft.event.AccountEvent;
import org.springframework.context.ApplicationListener;
@Override
public void onApplicationEvent(AccountEvent event) {
event.generateLog();
}
}
Account.java
package com.durgasoft.beans;
import com.durgasoft.publisher.AccountEventPublisher;
public void
setAccountEventPublisher(AccountEventPublisher
accountEventPublisher) {
this.accountEventPublisher =
accountEventPublisher;
}
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;
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.
EX:
—---
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
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.
1. MessageSource.
2. MessageSourceResourceBundle
3. ReloadableMessageSourceResourceBundle
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.
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;
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>
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>
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.
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;
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;
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>
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>
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.
If we want to get all the properties details then we have to use the following method
If we want to get all the methods[setXXX(), getXXX()] information we have to use the
following method.
EX:
Employee.java
package com.durgasoft.beans;
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import java.beans.*;
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:
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;
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.springframework.beans.*;
import java.beans.*;
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.
EX:
BeanWrapper beanWrapper = new BeanWrapperImpl(Employee.class);
To set values to the bean object explicitly then we have to use the following method.
To set all properties values to the Bean object we have to use the following method.
To copy the data from One bean to another bean we have to use the following method
from org.springframework.beans.BeanUtils class.
EX:
Employee.java
package com.durgasoft.beans;
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.springframework.beans.*;
import java.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>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.
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.
<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>
EX:
Address.java
package com.durgasoft.beans;
Employee.java
package com.durgasoft.beans;
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;
Main.java
package com.durgasoft;
import com.durgasoft.beans.Employee;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicati
onContext;
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>
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;
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;
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>
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.
EX:
—---
Main.java
—---------
package com.durgasoft;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import
org.springframework.expression.spel.standard.SpelExpressi
onParser;
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>
mb.add();
EX:
Calculator.java
package com.durgasoft.beans;
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;
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>
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.
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:
EX:
Main.java
package com.durgasoft;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
Expression expression2 =
expressionParser.parseExpression("'Durga'+'soft'");
System.out.println(expression2.getValue());
Expression expression4 =
expressionParser.parseExpression("'[email protected]' 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.
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)
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;
Expression expression6 =
expressionParser.parseExpression("T(Thread).MIN_PRIORITY");
System.out.println(expression6.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>
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
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 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");
}
}
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;
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">
[email protected]
8885252627
9246212143
7386095600