Spring Class Notes by Raghu Sir
Spring Class Notes by Raghu Sir
Spring
Framework
By : Raghu
1
RaghuSir Sathya Technologies
SPRING FRAMEWORK
Spring Practice -First Program:
1) Spring container takes two inputs like Spring Bean and Configuration File. After
Reading them, Spring container instantiates and assigns the values.
2) By default it creates singleton Objects in Container.
3) To read the Object use getBean(String beanName):Object method.
Step 1) Create New Java Project and Add build path (Spring JARS and +Commons-logging
JAR)
https://repo.spring.io/release/org/springframework/spring/3.2.5.RELEASE/spring-
framework-3.2.5.RELEASE-dist.zip
Commons-Logging JAR:
http://central.maven.org/maven2/commons-logging/commons-
logging/1.1.1/commons-logging-1.1.1.jar
>> Provide Any Sample Name (ex: SpringCore) click on Finish Button
>> Right Click on Project -> Choose Build Path -> Configure buildPath-> Libraries Tab-
>Add External JARS (Select above downloaded JARS). Even add Commons-logging jar.
Step 2) Right Click on src folder -> New Class-> Enter package and Class name:
Ex:
package com.app;
2
RaghuSir Sathya Technologies
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public double getEmpSal() {
return empSal;
}
public void setEmpSal(double empSal) {
this.empSal = empSal;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName
+ ", empSal=" + empSal + "]";
}
}
Step 3) Create A Spring configuration file to configure the Spring Bean Class.
Right Click on src->new->other->type XML-> select XML File-> Next-> Enter any name.xml
(ex: config.xml)->Finish
<property name="empSal">
<value>732.36</value>
</property>
</bean>
</beans>
package com.app;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.app.module.Employee;
Here
4
RaghuSir Sathya Technologies
Spring Bean Primitive type setter injection code can be written in 3 ways. They are
i)Value as Tag(<value></value>)
ex:
Spring Bean:
packagecom.app.module;
publicclass Employee {
privateintempId;
private String empName;
privatedoubleempSal;
public Employee() {
super();
}
publicintgetEmpId() {
returnempId;
5
RaghuSir Sathya Technologies
}
publicvoidsetEmpId(intempId) {
this.empId = empId;
}
public String getEmpName() {
returnempName;
}
publicvoidsetEmpName(String empName) {
this.empName = empName;
}
publicdoublegetEmpSal() {
returnempSal;
}
publicvoidsetEmpSal(doubleempSal) {
this.empSal = empSal;
}
@Override
public String toString() {
return"Employee [empId=" + empId + ", empName=" + empName
+ ", empSal=" + empSal + "]";
}
}
For the Above Spring bean Configuration code can be written as:
i)Value as tag: (Spring Configuration XML Code)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<beanclass="com.app.module.Employee"name="emp">
<propertyname="empId">
<value>10</value>
</property>
<propertyname="empName">
<value>ABCD</value>
</property>
<propertyname="empSal">
<value>732.36</value>
</property>
</bean>
</beans>
6
RaghuSir Sathya Technologies
ii)Value as attribute:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<beanclass="com.app.module.Employee"name="emp">
<propertyname="empId"value="10"/>
<propertyname="empName"value="abcd"/>
<propertyname="empSal"value="23.36"/>
</bean>
</beans>
iii)p-Name Space(p-Schema):
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<beanclass="com.app.module.Employee"name="emp"p:empId="101"p:empName="
ABCD"p:empSal="20.36"/>
</beans>
(Observe the red colour line. That is need to be added while using p-schema)
Note: a) For a dependency , we cannot configure a property more than one time
Ex:
<beanclass="com.app.module.Employee"name="emp"p:empId="101">
<propertyname="empId">
<value>101</value>
</property>
</bean>
Main Class:
System.out.println(emp);
Output:
Exception:
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration
problem: Multiple 'property' definitions for property 'empId'
Note: b) By default <value> tag takes input as String type and later it will be parsed to
specific type. If Data can’t be parsed (or any mismatch) then conversion problem will
occur, and appropriate exception will be thrown.
<beanclass="com.app.module.Employee"name="emp">
<propertyname="empId">
<value>ABCD</value>
</property>
</bean>
8
RaghuSir Sathya Technologies
Ex:
Spring Collections:
1) List
2) Set
3) Map
4) Properties
Here <map> contains internally entries (<entry>). Every entry contains <key> and <value> ,
these even can be represents as attributes.
Ex:
9
RaghuSir Sathya Technologies
Properties also stores data in the key value pair only. But by default key and values are type
String in Properties. It contains child tag <prop key=””></prop>. It doesn’t contain any
<value> tag to represent the value; we can directly specify the value in between the <prop>
tag.
Ex:
Employee.java
packagecom.app.module;
importjava.util.List;
importjava.util.Map;
importjava.util.Properties;
importjava.util.Set;
publicclass Employee {
private List<String>empList;
private Set<String>empSet;
private Map<String,String>empMap;
private Properties empProperties;
public List<String>getEmpList() {
returnempList;
}
publicvoidsetEmpList(List<String>empList) {
this.empList = empList;
}
public Set<String>getEmpSet() {
returnempSet;
}
publicvoidsetEmpSet(Set<String>empSet) {
this.empSet = empSet;
}
public Map<String, String>getEmpMap() {
returnempMap;
10
RaghuSir Sathya Technologies
}
publicvoidsetEmpMap(Map<String, String>empMap) {
this.empMap = empMap;
}
public Properties getEmpProperties() {
returnempProperties;
}
publicvoidsetEmpProperties(Properties empProperties) {
this.empProperties = empProperties;
}
@Override
public String toString() {
return"Employee [empList=" + empList + ", empSet=" + empSet
+ ", empMap=" + empMap + ", empProperties=" +
empProperties
+ "]";
}
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<beanclass="com.app.module.Employee"name="emp">
<propertyname="empList"><!-- it will maintain duplicates -->
<list>
<value>A</value>
<value>A</value>
<value>A</value>
<value>B</value>
<value>C</value>
<value>D</value>
</list>
</property>
<propertyname="empSet"><!-- it will not maintain duplicates -->
<set>
<value>A</value>
<value>A</value>
11
RaghuSir Sathya Technologies
<value>A</value>
<value>B</value>
<value>C</value>
<value>D</value>
</set>
</property>
<propertyname="empMap">
<map>
<entry>
<key>
<value>K1</value>
</key>
<value>V1</value>
</entry>
<entrykey="K2"value="V2"/>
<entrykey="K3">
<value>V3</value>
</entry>
<entryvalue="V4">
<key>
<value>K4</value>
</key>
</entry>
</map>
</property>
<propertyname="empProperties">
<props>
<propkey="key1">val1</prop>
<propkey="key1">val3</prop>
<propkey="key2">val2</prop>
</props>
</property>
</bean>
</beans>
Main Program:
publicclass Main {
publicstaticvoid main(String[] args) throws Exception, Exception {
ApplicationContext
context=newClassPathXmlApplicationContext("config.xml");
Employee emp=(Employee)context.getBean("emp");
System.out.println(emp);
12
RaghuSir Sathya Technologies
Output:
Note 1):
Empty Object Reference and Null Reference:-
If any Object created with no data and referred with a reference is known as empty Object.
For ex: List l1=new ArrayList(); Creating empty Array List.
If a reference not even contains empty object. Or reference, that doesn’t point to Object is
known as null Reference.
Ex:
packagecom.app.module;
importjava.util.List;
publicclass Employee {
private List<String>empList;
public List<String>getEmpList() {
returnempList;
}
publicvoidsetEmpList(List<String>empList) {
this.empList = empList;
}
@Override
public String toString() {
return"Employee [empList=" + empList + "]";
}
}
For the above class, configuration code is given as:
Case 1)
<beanclass="com.app.module.Employee"name="emp">
</bean>
Case2)
13
RaghuSir Sathya Technologies
<beanclass="com.app.module.Employee"name="emp">
<propertyname="empList">
<list></list>
</property>
</bean>
Employee Object created with empList with zero size (Or empty List)
Case 3)
<beanclass="com.app.module.Employee"name="emp">
<propertyname="empList"></property>
</bean>
In case of any property tag is defined without any value tag, then Spring Container throws
Exception:
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration
problem: <property> element for property 'empList' must specify a ref or value
A Class can have relation with another class (HAS-A) dependency. To configure that in Spring
Configuration File (config.xml) <ref/> tag is used.
Syntax:
In this case we must configure always independent class first, then configure dependent
class
ex:
14
RaghuSir Sathya Technologies
package com.app;
}
========
package com.app;
15
RaghuSir Sathya Technologies
return addrId;
}
public void setAddrId(int addrId) {
this.addrId = addrId;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return "Address [addrId=" + addrId + ", loc=" + loc + "]";
}
}
=====
===========
package com.app;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
16
RaghuSir Sathya Technologies
Output:
Note: If a class is having interface dependency , then class must be configured with
implemented class.
ex:
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
ex:
18
RaghuSir Sathya Technologies
Java Code:
Address.java
package com.app;
}
=========================
Employee.java
package com.app;
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>
Test.java
package com.app;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
1) ref as tag:
2) ref as attribute:
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
4) Inner Bean:
<property name="addrId">
<value>1010</value>
</property>
<property name="loc" value="ABCD" />
</bean>
</property>
</bean>
==================
equals() Method:
it compares two objects memory location. It returns true if two references refers same
object, but not similar Objects. Two make equals comparing data (as similar Objects), just
override that method and write logic of Objects comparison.
For ex:
At the time of adding References Objects to Set data, which stores Objects of a class that
doesn't override the equals method, then if we add similar objects, even it treats as
different object.
(Always remember equals method by default check either same or not, that means Two
Object must refer same Object. To make equals comparing similar or not, override the
method )
Address.java
package com.app;
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return "Address [addrId=" + addrId + ", loc=" + loc + "]";
}
}
Test.java
package com.app;
import java.util.HashSet;
import java.util.Set;
System.out.println(addrSet);
}
}
output: [Address [addrId=101, loc=ABCD], Address [addrId=101, loc=ABCD], Address
[addrId=101, loc=ABCD]]
23
RaghuSir Sathya Technologies
Note : To generate equals and hashCode method use shortcut in eclipse (alt+shift+s and
h)
package com.app;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + addrId;
result = prime * result + ((loc == null) ? 0 : loc.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
24
RaghuSir Sathya Technologies
return false;
Address other = (Address) obj;
if (addrId != other.addrId)
return false;
if (loc == null) {
if (other.loc != null)
return false;
} else if (!loc.equals(other.loc))
return false;
return true;
}
}
Test.java:
package com.app;
import java.util.HashSet;
import java.util.Set;
System.out.println(addrSet);
}
}
output:[Address [addrId=101, loc=ABCD]]
25
RaghuSir Sathya Technologies
ex:
Java Code:
Address.java:
package com.app;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + addrId;
result = prime * result + ((loc == null) ? 0 : loc.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Address other = (Address) obj;
if (addrId != other.addrId)
return false;
if (loc == null) {
if (other.loc != null)
return false;
} else if (!loc.equals(other.loc))
return false;
return true;
}
}
Employee.java
package com.app;
import java.util.List;
27
RaghuSir Sathya Technologies
}
Configuration code:
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
28
RaghuSir Sathya Technologies
<bean class="com.app.Address">
<property name="addrId" value="30"/>
<property name="loc" value="HYD1"/>
</bean>
</list>
</property>
</bean>
</beans>
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>
29
RaghuSir Sathya Technologies
3) Util Schema:
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
</beans>
Test.java:
package com.app;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
30
RaghuSir Sathya Technologies
Ex:
Map can have key value pair in 4 combinations, and every combination can be
configured in 4 ways.
31
RaghuSir Sathya Technologies
Ex: a) Map Key as Primitive and value as Primitive : Example Configuration code is given
below,
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<beanclass="com.app.Employee"name="empObj">
<propertyname="empMap">
<map>
<entry>
<key>
<value>Key1</value>
</key>
<value>Val1</value>
</entry>
<entrykey="Key2">
<value>Val2</value>
</entry>
<entryvalue="Val3">
<key>
<value>Key3</value>
</key>
</entry>
<entrykey="Key4"value="Val4"/>
</map>
</property>
</bean>
32
RaghuSir Sathya Technologies
</beans>
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<beanclass="com.app.Address"name="addr1">
<propertyname="addrId"value="110"/>
<propertyname="loc"value="HYD1"/>
</bean>
<beanclass="com.app.Address"name="addr2">
<propertyname="addrId"value="120"/>
<propertyname="loc"value="HYD2"/>
</bean>
<beanclass="com.app.Address"name="addr3">
<propertyname="addrId"value="130"/>
<propertyname="loc"value="HYD3"/>
</bean>
<beanclass="com.app.Address"name="addr4">
<propertyname="addrId"value="140"/>
<propertyname="loc"value="HYD4"/>
</bean>
<beanclass="com.app.Employee"name="empObj">
<propertyname="empMap">
<map>
<entry>
33
RaghuSir Sathya Technologies
<key>
<value>Key1</value>
</key>
<ref bean="addr1"/>
</entry>
<entrykey="Key2">
<ref bean="addr2"/>
</entry>
<entryvalue-ref="addr3">
<key>
<value>Key3</value>
</key>
</entry>
<entrykey="Key4"value-ref="addr4"/>
</map>
</property>
</bean>
</beans>
Note: If key is reference type (class) , that class must override hashCode and equals
methods(alt+shift+s h)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<beanclass="com.app.Address"name="addr1">
<propertyname="addrId"value="110"/>
<propertyname="loc"value="HYD1"/>
</bean>
34
RaghuSir Sathya Technologies
<beanclass="com.app.Address"name="addr2">
<propertyname="addrId"value="120"/>
<propertyname="loc"value="HYD2"/>
</bean>
<beanclass="com.app.Address"name="addr3">
<propertyname="addrId"value="130"/>
<propertyname="loc"value="HYD3"/>
</bean>
<beanclass="com.app.Address"name="addr4">
<propertyname="addrId"value="140"/>
<propertyname="loc"value="HYD4"/>
</bean>
<beanclass="com.app.Employee"name="empObj">
<propertyname="empMap">
<map>
<entry>
<key>
<ref bean="addr1"/>
</key>
<value>Val1</value>
</entry>
<entrykey-ref="addr2">
<value>val2</value>
</entry>
<entryvalue="val3">
<key>
<refbean="addr3"/>
</key>
</entry>
<entry key-ref="addr4"value="val4"/>
</map>
</property>
</bean>
</beans>
d) Map Key as Reference and value as Reference:
Example Configuration Code:
35
RaghuSir Sathya Technologies
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<beanclass="com.app.Project"name="proj1">
<propertyname="projId"value="210"/>
<propertyname="projMode"value="A1"/>
</bean>
<beanclass="com.app.Project"name="proj2">
<propertyname="projId"value="220"/>
<propertyname="projMode"value="A2"/>
</bean>
<beanclass="com.app.Project"name="proj3">
<propertyname="projId"value="230"/>
<propertyname="projMode"value="A3"/>
</bean>
<beanclass="com.app.Project"name="proj4">
<propertyname="projId"value="240"/>
<propertyname="projMode"value="A4"/>
</bean>
<beanclass="com.app.Address"name="addr1">
<propertyname="addrId"value="110"/>
<propertyname="loc"value="HYD1"/>
</bean>
<beanclass="com.app.Address"name="addr2">
<propertyname="addrId"value="120"/>
<propertyname="loc"value="HYD2"/>
</bean>
<beanclass="com.app.Address"name="addr3">
<propertyname="addrId"value="130"/>
36
RaghuSir Sathya Technologies
<propertyname="loc"value="HYD3"/>
</bean>
<beanclass="com.app.Address"name="addr4">
<propertyname="addrId"value="140"/>
<propertyname="loc"value="HYD4"/>
</bean>
<beanclass="com.app.Employee"name="empObj">
<propertyname="empMap">
<map>
<entry>
<key>
<refbean="addr1"/>
</key>
<refbean="proj1"/>
</entry>
<entrykey-ref="addr2">
<refbean="proj2"/>
</entry>
<entryvalue-ref="proj3">
<key>
<refbean="addr3"/>
</key>
</entry>
<entrykey-ref="addr4"value-ref="proj4"/>
</map>
</property>
</bean>
</beans>
2) Inner Bean:
Instead of referring the bean from key tag or ref tag, we can even declare the bean
inside the key or entry.
Ex:
<beanclass="com.app.Employee"name="empObj">
<propertyname="empMap">
<map>
<entry>
<key>
<beanclass="com.app.Project"name="proj1">
<propertyname="projId"value="210"/>
<propertyname="projMode"value="A1"/>
</bean>
</key>
<beanclass="com.app.Address"name="addr1">
37
RaghuSir Sathya Technologies
<propertyname="addrId"value="110"/>
<propertyname="loc"value="HYD1"/>
</bean>
</entry>
</map>
</property>
</bean>
Here bean declared inside the key represents Key bean and bean declared outside key and
inside the entry represent value bean.
3) Standalone collections
We can declare a specific collection type using util schema and can be referred from the
property tag as a bean.
Ex:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"xmlns:util="http://www.sprin
gframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<beanclass="com.app.Project"name="proj3">
<propertyname="projId"value="230"/>
<propertyname="projMode"value="A3"/>
</bean>
<beanclass="com.app.Address"name="addr3">
<propertyname="addrId"value="190"/>
<propertyname="loc"value="HYD5"/>
</bean>
<util:mapid="sampleMap"map-class="java.util.TreeMap">
<entry>
<key>
<beanclass="com.app.Project"name="proj1">
<propertyname="projId"value="210"/>
<propertyname="projMode"value="A1"/>
</bean>
</key>
38
RaghuSir Sathya Technologies
<beanclass="com.app.Project"name="proj2">
<propertyname="projId"value="220"/>
<propertyname="projMode"value="A2"/>
</bean>
</entry>
<entrykey-ref="proj3">
<refbean="addr3"/>
</entry>
</util:map>
<beanclass="com.app.Employee"name="empObj">
<propertyname="empMap">
<refbean="sampleMap"/>
</property>
</bean>
</beans>
By default <bean> tag calls default constructor, to specify a parameterized constructor use
<constructor-arg> in <bean> tag. One <constructor-arg> indicates one attribute. For
example if we want to call 3 parameterized constructor then we have to write <constructor-
arg> 3 times. To use feature, Bean class must have parameterized constructors.
Ex:
packagecom.app.module;
publicclass Employee {
privateintempId;
private String empName;
privatedoubleempSal;
public Employee() {
super();
}
public Employee(intempId, doubleempSal) {
super();
this.empId = empId;
this.empSal = empSal;
}
public Employee(intempId, String empName) {
super();
this.empId = empId;
this.empName = empName;
39
RaghuSir Sathya Technologies
}
public Employee(String empName, doubleempSal) {
super();
this.empName = empName;
this.empSal = empSal;
}
@Override
public String toString() {
return"Employee [empId=" + empId + ", empName=" + empName
+ ", empSal=" + empSal + "]";
}
<beanclass="com.app.module.Employee"name="empObj">
<!-- calls two parameterized constructor -->
<constructor-arg>
<value>10</value>
</constructor-arg>
<constructor-arg>
<value>10.32</value>
</constructor-arg>
</bean>
</beans>
Test.java:
ApplicationContext
context=newClassPathXmlApplicationContext("config.xml");
40
RaghuSir Sathya Technologies
Employee emp=(Employee)context.getBean("empObj");
System.out.println(emp);
Output:
Note: By default <value> tag in constructor tag represents String type. If not found the
String type then it choose the nearest one from given constructors in the given order.
For ex:
<constructor-arg>
<value>10</value>
</constructor-arg>
<constructor-arg>
<value>10.32</value>
</constructor-arg>
It will search for String,String . If not then Compare with First constructor of Class, if not
matched then second like go on to next constructor.
Note: To specify the particular constructor use the attributes like’
1) type (constructor argument data type)
<constructor-argtype="int">
<value>10</value>
</constructor-arg>
<constructor-argtype="double">
<value>10.32</value>
</constructor-arg>
2) index (starts from zero)
<constructor-argindex="0">
<value>10</value>
</constructor-arg>
<constructor-argindex="1">
<value>10.32</value>
</constructor-arg>
3) name (constructor argument name)
<constructor-argname="empId">
<value>10</value>
</constructor-arg>
<constructor-argname="empSal">
41
RaghuSir Sathya Technologies
<value>10.32</value>
</constructor-arg>
Note: <constructor-arg> tag also supports writing of code formats which are supported by
<property> tag. Like inner bean, ref tag and attribute, Stand-alone collection reference
etc..
Ex:
<constructor-arg>
<value>10</value>
</constructor-arg>
<constructor-argvalue="ABCD"/>
<constructor-arg>
<map>
<entrykey="abcd"value="empObj1"/>
</map>
</constructor-arg>
<constructor-arg><!--Innder Bean -->
<beanclass="com.app.Address">
<propertyname="addrId"value="10101"/>
</bean>
</constructor-arg>
<constructor-arg>
<refbean="addrObj"/>
</constructor-arg>
<constructor-arg>
<props>
<propkey="K1">V1</prop>
<propkey="K2">V2</prop>
</props>
</constructor-arg>
While Executing the Constructor, If matching’s not found for Data type then it follows 3
Rules
1) Primitive Type Conversion(Priority 1)
2) Auto Boxing And up-casting (Priority 2)
3) Var-args (In up casted Order)(Priority 3)
package com.app.module;
import java.io.Serializable;
publicclass Employee {
public Employee(byte x,byte y) {
System.out.println("Order-1(never)");
42
RaghuSir Sathya Technologies
}
public Employee(short x,short y) {
System.out.println("Order-2(never)");
}
public Employee(int x,int y) {
System.out.println("Order1");
}
public Employee(long x,long y) {
System.out.println("Order2");
}
public Employee(float x,float y) {
System.out.println("Order3");
}
public Employee(double x,double y) {
System.out.println("Order4");
}
public Employee(Integer x,Integer y) {
System.out.println("Order5");
}
public Employee(Double x,Double y) {
System.out.println("Order5(never)");
}
public Employee(Number x,Number y) {
System.out.println("Order6");
}
public Employee(Serializable x,Serializable y) {
System.out.println("Order7");
}
public Employee(Object x,Object y) {
System.out.println("Order8");
}
public Employee(Integer... integers) {
System.out.println("Order9");
}
public Employee(Number... integers ) {
System.out.println("Order10");
}
public Employee(Serializable... serializables) {
System.out.println("Order11");
}
public Employee(Object... integers) {
System.out.println("Order12");
}
publicstaticvoid main(String[] args) {
//write the above constructor in any order. They are called in Specified
//number formats only.
43
RaghuSir Sathya Technologies
Process 1:
Process 2:
Process 3:
Invalid Process:
44
RaghuSir Sathya Technologies
**** Note: at a time type conversion and auto-boxing can never be done.
Spring Bean is having two life cycle methods, which are called automatically by spring
container.
1) init-method
2) destroy method
Note: init-method will be executed after creating bean (After CI and SI done). And Destroy
method will be called once before the Container shutdown or bean is removed from
container.
1) Using Interfaces
2) XML Configuration
3) Annotation Based
Ex:
packagecom.app.module;
45
RaghuSir Sathya Technologies
importorg.springframework.beans.factory.DisposableBean;
importorg.springframework.beans.factory.InitializingBean;
public Employee() {
super();
System.out.println("In default constructor");
}
publicintgetEmpId() {
returnempId;
}
publicvoidsetEmpId(intempId) {
this.empId = empId;
System.out.println("In empId setter method");
}
@Override
public String toString() {
return"Employee [empId=" + empId + "]";
}
@Override
publicvoidafterPropertiesSet() throws Exception {
System.out.println("Init -method");
}
@Override
publicvoid destroy() throws Exception {
System.out.println("Destory Method");
}
}
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
46
RaghuSir Sathya Technologies
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<beanclass="com.app.module.Employee"name="empObj">
<propertyname="empId"value="200"/>
</bean>
</beans>
Test.java
publicclassTest{
AbstractApplicationContextcontext=newClassPathXmlApplicationContext("config.xm
l");
Employee emp=(Employee)context.getBean("empObj");
System.out.println(emp);
context.registerShutdownHook();
2) XML Configuration:- By using <bean> tag specify two attributes, init-method and
destroy-method and provide method names for these.
Ex:
packagecom.app.module;
publicclass Employee {
privateintempId;
public Employee() {
super();
System.out.println("In default constructor");
}
publicintgetEmpId() {
returnempId;
}
47
RaghuSir Sathya Technologies
publicvoidsetEmpId(intempId) {
this.empId = empId;
System.out.println("In empId setter method");
}
@Override
public String toString() {
return"Employee [empId=" + empId + "]";
}
publicvoidabcd(){
System.out.println("In init-method");
}
publicvoidmnop(){
System.out.println("In destroy-method");
}
}
XMl Code:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<beanclass="com.app.module.Employee"name="empObj"init-
method="abcd"destroy-method="mnop">
<propertyname="empId"value="200"/>
</bean>
</beans>
3) Annotation Based:- Here two Annotations are used to they are: @PostConstruct
(init) and @PreDestroy(destroy)
By Default all Annotations are in spring is disabled mode. We have to enable the
annotation before using them, either specific or all annotations.
org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
48
RaghuSir Sathya Technologies
Ex:
packagecom.app.module;
importjavax.annotation.PostConstruct;
importjavax.annotation.PreDestroy;
publicclass Employee {
privateintempId;
public Employee() {
super();
System.out.println("In default constructor");
}
publicintgetEmpId() {
returnempId;
}
publicvoidsetEmpId(intempId) {
this.empId = empId;
System.out.println("In empId setter method");
}
@Override
public String toString() {
return"Employee [empId=" + empId + "]";
}
@PostConstruct
publicvoidabcd(){
System.out.println("In init-method");
}
@PreDestroy
publicvoidmnop(){
System.out.println("In destroy-method");
}
}
XML Code:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
49
RaghuSir Sathya Technologies
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<beanclass="org.springframework.context.annotation.CommonAnnotationBeanPost
Processor"/>
<beanclass="com.app.module.Employee" name="empObj">
<propertyname="empId"value="200"/>
</bean>
</beans>
Note: If we configure 3 ways , then container creates Object and calls 3 init and destroy
methods in below order
i) Annotated Methods
ii) Interface Methods
iii) XML Configured Methods
All Spring Beans will have dependencies of type Primitive, Collection and References. At the
time of creating object injecting values are optional. To make the values injections
mandatory enable dependency check. This can be enabled group level (simple, object,all) or
individual level (@Required).
1) XML Based : here at bean tag level, we have one attribute dependency-check which
is having 5 possible values
a. simple(Primitive type)
b. objects(Collection and Reference Types)
c. all
d. none
e. default (Will be decided by default-dependency-check tag)
50
RaghuSir Sathya Technologies
If we do not specify any value for the bean it considers as default is the value. But this
default value can be one of remaining 4 values and that will be decided by default-
dependency-check attribute from beans tag level.
Ex:
packagecom.app.module;
importjava.util.List;
publicclass Address {
privateintaddrId;
private List<String>data;
publicintgetAddrId() {
returnaddrId;
}
publicvoidsetAddrId(intaddrId) {
this.addrId = addrId;
}
public List<String>getData() {
returndata;
}
publicvoidsetData(List<String> data) {
this.data = data;
}
@Override
public String toString() {
return"Address [addrId=" + addrId + ", data=" + data + "]";
}
}
packagecom.app.module;
importjava.util.List;
publicclass Employee {
privateintempId;
private String empName;
private Address addr;
private List<String>empList;
publicintgetEmpId() {
returnempId;
}
51
RaghuSir Sathya Technologies
publicvoidsetEmpId(intempId) {
this.empId = empId;
}
public String getEmpName() {
returnempName;
}
publicvoidsetEmpName(String empName) {
this.empName = empName;
}
public Address getAddr() {
returnaddr;
}
publicvoidsetAddr(Address addr) {
this.addr = addr;
}
public List<String>getEmpList() {
returnempList;
}
publicvoidsetEmpList(List<String>empList) {
this.empList = empList;
}
@Override
public String toString() {
return"Employee [empId=" + empId + ", empName=" + empName + ", addr="
+ addr + ", empList=" + empList + "]";
}
}
Configuration file:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"xmlns:xsi="http://www.w3.or
g/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<beanclass="com.app.module.Employee"name="empObj"dependency-
check="simple">
</bean>
</beans>
Main Class:
public classMain{
52
RaghuSir Sathya Technologies
ApplicationContextcontext=newClassPathXmlApplicationContext("config.xml");
Employee emp=(Employee)context.getBean("empObj");
System.out.println(emp);
Output:
Note:
a) Here to check all dependencies use all value
<beanclass="…"name="…"dependency-check="all">
</bean>
b) If we have multiple beans and for all we want to enable by default as simple type
then specify the default-dependency-check as simple at bean tag level. Even you can
override at specific bean level.
Ex:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:c="ttp://www.springframework.org/schema/c"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
default-dependency-check="simple"
>
<beanclass="com.app.module.Employee"name="empObj">
<!-- here it takes default dependency check value simple as default value -->
</bean>
<beanclass="com.app.module.Address"name="addrObj"dependency-check="default">
<!-- it is going to check default value. here default is simple-->
</bean>
<beanclass="com.app.module.Project"name="projObj"dependency-check="simple">
<!-- it overrides the default value to simple only for this Project Bean -->
53
RaghuSir Sathya Technologies
</bean>
</beans>
By default all annotations are in disabled mode in spring, to activate this in spring configure
the class RequiredAnnotationBeanPostProcessor. Or use Context schema,
<context:annotation-config/>
Ex:
packagecom.app.module;
importjava.util.List;
importorg.springframework.beans.factory.annotation.Required;
publicclass Employee {
privateintempId;
private String empName;
private Address addr;
private List<String>empList;
publicintgetEmpId() {
returnempId;
}
@Required
publicvoidsetEmpId(intempId) {
this.empId = empId;
}
public String getEmpName() {
returnempName;
}
publicvoidsetEmpName(String empName) {
this.empName = empName;
}
public Address getAddr() {
returnaddr;
}
publicvoidsetAddr(Address addr) {
this.addr = addr;
}
public List<String>getEmpList() {
54
RaghuSir Sathya Technologies
returnempList;
}
publicvoidsetEmpList(List<String>empList) {
this.empList = empList;
}
@Override
public String toString() {
return"Employee [empId=" + empId + ", empName=" + empName + ", addr="
+ addr + ", empList=" + empList + "]";
}
Format 1)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<beanclass="org.springframework.beans.factory.annotation.RequiredAnnotationBea
nPostProcessor">
</bean>
<beanclass="com.app.module.Employee"name="empObj">
</bean>
</beans>
Format 2)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
55
RaghuSir Sathya Technologies
</beans>
Test Class
ApplicationContextcontext=newClassPathXmlApplicationContext("config.xml");
Employee emp=(Employee)context.getBean("empObj");
System.out.println(emp);
Output:
Spring supports in-built factory design pattern in 2 ways instance factory and static
factory.
56
RaghuSir Sathya Technologies
Here factory method returns object type. It will take dynamic input based on that, it will
create the object. In this case we need to configure only Factory class in spring
configuration file.
Ex:
Code:
packagecom.app.module;
publicclass Employee {
privateintempId;
private String empName;
public Employee() {
super();
}
public Employee(intempId, String empName) {
super();
this.empId = empId;
this.empName = empName;
}
publicintgetEmpId() {
returnempId;
}
publicvoidsetEmpId(intempId) {
this.empId = empId;
}
public String getEmpName() {
returnempName;
}
publicvoidsetEmpName(String empName) {
this.empName = empName;
57
RaghuSir Sathya Technologies
}
@Override
public String toString() {
return"Employee [empId=" + empId + ", empName=" + empName + "]";
}
}
packagecom.app.module;
importjava.util.List;
publicclass Address {
privateintaddrId;
private String loc;
public Address() {
super();
}
public Address(intaddrId, String loc) {
super();
this.addrId = addrId;
this.loc = loc;
}
publicintgetAddrId() {
returnaddrId;
}
publicvoidsetAddrId(intaddrId) {
this.addrId = addrId;
}
public String getLoc() {
returnloc;
}
publicvoidsetLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return"Address [addrId=" + addrId + ", loc=" + loc + "]";
}
}
packagecom.app.module;
publicclassSimpleFactory {
58
RaghuSir Sathya Technologies
</beans>
Test.java
ApplicationContextcontext=newClassPathXmlApplicationContext("config.xml");
Object ob=context.getBean("sf");
if(obinstanceof Employee){
Employee emp=(Employee)ob;
System.out.println(emp);
}elseif(obinstanceof Address){
Address add=(Address)ob;
System.out.println(add);
}
System.out.println("done");
}
59
RaghuSir Sathya Technologies
Output:
Factory class:
packagecom.app.module;
publicclassSimpleFactory {
XML Code:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
Java code :
SimpleFactorysf=new SimpleFactory();
-->
<beanclass="com.app.module.SimpleFactory" name="sf1">
</bean>
<!-- Object sf=sf1.createObject("emp"); -->
<beanname="sf"factory-bean="sf1"factory-method="createObject">
<constructor-arg>
<value>emp</value>
</constructor-arg>
</bean>
</beans>
60
RaghuSir Sathya Technologies
Output:
Ex: for Inheritance : to specify the reading of parent bean data ,use parent attribute at bean
tag level.
java Code:
package com.app;
}
public void setEmpName(String empName) {
this.empName = empName;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + "]";
}
}
=======
package com.app;
62
RaghuSir Sathya Technologies
=======
Config.xml
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
=====
Test.java
package com.app;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
}
}
======
output:
63
RaghuSir Sathya Technologies
Note 1): Even we can use a common bean as template for both the classes common data
representation.
Format 1)
format 2)
Note 2): If value given by parent is not satisfied by child bean, then child bean can
override the value by performing dependency injection again.
64
RaghuSir Sathya Technologies
Autowiring is a concept of injecting a spring bean automatically without writing <ref/> tag
by programmer. Programmer does not required to write explicitly Dependency Injection.
1) XML based
2) Annotation Based
a) byName : compares the spring bean (java code) filed name (variable name) and
configuration code (XML file) bean name (bean tag name) , if they are matched then
automatically those objects will b bonded with each other using setter injection.
b) byType: It compares bean class variable Data type and spring bean class type. If both are
matched then it will do setter injection.
c) constructor: It check for parameterized constructor for creating object with reference
type as parameter. If not found then uses default constructor at last. Always checks More
number of parameters first, if not matched then next level less no of parameters
constructor will be compared, and then goes on up to default constructor.
f) autodetect (works only in older versions like 2.X) : It works like byType if default
constructor is available in spring bean, if not works like constructor if parameterized
constructor is available.
ex: consider the below example for above concept. Employee class has a Address class
Dependency.
65
RaghuSir Sathya Technologies
Java code:
package com.app;
}
=====
66
RaghuSir Sathya Technologies
package com.app;
@Override
public String toString() {
return "Employee [addr=" + addr + "]";
}
======
code byType:
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
</bean>
</beans>
=========
code byName:
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
</bean>
</beans>
68
RaghuSir Sathya Technologies
========
constructor:
to use this option class must have at least one parameterized constructor.
Always constructor with more parameters will be compared first , if not matched then it
goes to next level more parameters constructor (like 4 parameters, 3 parameters ..) until
zero/default constructor. Even If default constructor not found then spring container throws
an exception saying that no constructor found.
Java Code:
package com.app;
public Employee() {
super();
System.out.println("In default");
}
@Override
public String toString() {
return "Employee [addr=" + addr + "]";
}
}
====
package com.app;
package com.app;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
ApplicationContext context=new
ClassPathXmlApplicationContext("config.xml");
70
RaghuSir Sathya Technologies
Address address=context.getBean("addrObj",Address.class);
System.out.println(address);
Employee employee=context.getBean("empObj",Employee.class);
System.out.println(employee);
System.out.println("done");
}
}
====
XML Code:
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
</bean>
</beans>
===========
package com.app;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
71
RaghuSir Sathya Technologies
}
}
======
Note: 1) If more than one matchi9ng found while doing constructor , then it compares
names to inject the bean: for ex:
</bean>
</beans>
in the above code addr,addr2 are two objects then it compares the names to inject. So addr
will be select to inject. If no name matched then no object will be injected.
=========
72
RaghuSir Sathya Technologies
autodetect:
Java code:
package com.app;
}
============
package com.app;
public Employee() {
super();
System.out.println("In default");
}
System.out.println("in Param");
}
@Override
public String toString() {
return "Employee [addr=" + addr + "]";
}
}
===
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
</bean>
</beans>
74
RaghuSir Sathya Technologies
package com.app;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
}
}
Note: if you execute the above code it will check for default constructor and if found it
performs byType Autowiring. If you comment default constructor then it uses
parameterized constructor.
output:
In default
in setter
Employee [addr=Address [addrId=9, loc=HYD9]]
/*public Employee() {
super();
System.out.println("In default");
}*/
output:
in Param
Employee [addr=Address [addrId=9, loc=HYD9]]
1) singleton : This scope specifies , for every spring bean and for one configuration spring
container creates one object. This is the default scope of all spring beans.
75
RaghuSir Sathya Technologies
2) prototype: This scope indicates, creating a spring bean object on every read in spring
container.
4) session: it is also related to web applications. On every session, creates new object in
container.
5)global session:- it is related to portlets concept. It creates a spring bean for the global
session of portlet.
To specify the spring bean scope use bean tag scope attribute.
ex:
package com.app;
</bean>
package com.app;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
}
}
retusn output of same hash code for all above objects.
========
============
If a independent class is prototype scope and dependent class is single tone scope then
always spring container returns first time banded object with sinleton class , even though it
creates new object for prototype.
To change this functionality use, look up method injection, for this we need to add CGLIB
Jar.
http://central.maven.org/maven2/cglib/cglib/3.1/cglib-3.1.jar
77
RaghuSir Sathya Technologies
Specify the abstract method that should return the Prototype class and call that method
somewhere in the java code. make class as even abstract, that class will be implemented as
proxy by CGLIB jar with same name.
ex:
java code:
package com.app;
=====
package com.app;
@Override
public String toString() {
return "Employee [addr=" + addr + "]";
}
}
====
config.xml
">
<bean class="com.app.Address" name="addrObj" scope="prototype">
<property name="addrId" value="152"/>
<property name="loc" value="HYD"/>
</bean>
<bean class="com.app.Employee" name="empObj" scope="singleton">
<lookup-method bean="addrObj" name="createObject"/>
</bean>
=======
Test.java
package com.app;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
}
}
79
RaghuSir Sathya Technologies
output:
emp:5122060,addr:13177628
emp:5122060,addr:17152415
emp:5122060,addr:13508999
emp:5122060,addr:16471729
These are the annotations used to create a bean (object ) in spring container, without any
XML configuration. @Component is the Stereo type Annotation. And even @Controller,
@Repository, @Service are also layer level Stereo type annotations.
To activate this annotation we need to specify the annotation activation and base-package
for component scan in Spring Configuration file.
Ex:
packagecom.app.module;
importorg.springframework.stereotype.Component;
@Component("addrObj")
publicclass Address {
}
Equal XML Code is <bean class=”com.app.module.Address” name=”addrObj”/>
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scanbase-package="com.app"/>
</beans>
packagecom.app;
80
RaghuSir Sathya Technologies
importorg.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
importcom.app.module.Address;
publicclass Test {
ApplicationContextcontext=newClassPathXmlApplicationContext("config.xml");
Address cons =context.getBean("addrObj", Address.class);
System.out.println(cons);
}
}
Output:
com.app.module.Address@4c4975
@Component if not having any parameter value then it takes class name as bean name by
converting first letter of class name as lower case.
Ex:
@Component
publicclass Address {
@Value can be specified as direct value, Expression value and dynamic value.
Ex:
packagecom.app.module;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.stereotype.Component;
@Component("addrObj")
publicclass Address {
81
RaghuSir Sathya Technologies
@Value("350")
privateintempId;
@Value("#{(new java.util.Random()).nextDouble()}")
privatedoubleempSal;
@Value("#{32>99?true:false}")
privatebooleanstatus;
@Override
public String toString() {
return"Address [empId=" + empId + ", empSal=" + empSal + ", status="
+ status + "]";
}
}
XML Code:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scanbase-package="com.app"/>
</beans>
Test.java
packagecom.app;
importorg.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
importcom.app.module.Address;
publicclass Test {
ApplicationContextcontext=newClassPathXmlApplicationContext("config.xml");
Address cons =context.getBean("addrObj", Address.class);
System.out.println(cons);
82
RaghuSir Sathya Technologies
}
}
Bean Externalization : Loading value from .properties file and assigning values to a particular
bean, in known as bean externalization.
To Create a properties file: right click on src-> new -> other -> file-> next-> provider any
name (like jdbc.properties)
It maintains data in the form of key value pair. Both key and value should be in string
format. Key is case sensitive (num ,Num are different). If a key is used to more than one
time in properties file then last value will be considered to the key. To read a key value use
below syntax :
${key-name}.
Ex:
packagecom.app.module;
publicclass Employee {
privateintempId;
privatedoubleempSal;
privatebooleanstatus;
publicintgetEmpId() {
returnempId;
}
publicvoidsetEmpId(intempId) {
this.empId = empId;
}
publicdoublegetEmpSal() {
returnempSal;
}
publicvoidsetEmpSal(doubleempSal) {
this.empSal = empSal;
}
publicbooleanisStatus() {
returnstatus;
}
publicvoidsetStatus(boolean status) {
this.status = status;
}
@Override
public String toString() {
return"Employee [empId=" + empId + ", empSal=" + empSal + ", status="
+ status + "]";
83
RaghuSir Sathya Technologies
}
abcd.properties:
#This is a comment line in Properties file
idValue=250
sal=96369.36
stat=true
XML File:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="abcd.properties"/>
<beanclass="com.app.module.Employee" name="empObj">
<propertyname="empId">
<value>${idValue}</value>
</property>
<propertyname="empSal">
<value>${sal}</value>
</property>
<propertyname="status">
<value>${stat}</value>
</property>
</bean>
</beans>
Test.java
packagecom.app;
importorg.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
importcom.app.module.Employee;
84
RaghuSir Sathya Technologies
publicclass Test {
ApplicationContextcontext=newClassPathXmlApplicationContext("config.xml");
Employee cons =context.getBean("empObj", Employee.class);
System.out.println(cons);
}
}
Output:
Note: if Key name does not exist then spring container throws
Exceptionorg.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean
definition: Could not resolve placeholder 'idValue1' in string value "${idValue1}"
If two classes are dependent on each other, then creating object will be very difficult. In this
case spring provides best solution.
Example:
Consider Employee and Address are the two classes which are having dependency on each
other.
85
RaghuSir Sathya Technologies
packagecom.app;
publicclass Employee {
private Address addr;
public Employee() {
super();
System.out.println("In Employee Default Constructor");
}
publicvoidsetAddr(Address addr) {
this.addr = addr;
System.out.println("In Employee class , Address setter");
}
packagecom.app;
publicclass Address {
private Employee emp;
public Address() {
super();
System.out.println("In Address Default Constructor");
}
returnemp;
}
publicvoidsetEmp(Employee emp) {
this.emp = emp;
System.out.println("In Address class , Employee setter");
}
}
Config.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<beanclass="com.app.Employee"name="empObj">
<propertyname="addr">
<refbean="addrObj"/>
</property>
</bean>
<beanclass="com.app.Address"name="addrObj">
<propertyname="emp">
<refbean="empObj"/>
</property>
</bean>
</beans>
packagecom.app;
importorg.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
importcom.app.Employee;
publicclass Test {
ApplicationContextcontext=newClassPathXmlApplicationContext("config.xml");
Employee cons =context.getBean("empObj", Employee.class);
System.out.println(cons);
}
}
Output: In Employee Default Constructor
Spring-JDBC:
Config.xml:
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
name="dataSource">
<property name="driverClassName" value=""/>
<property name="url" value=""/>
<property name="username" value=""/>
</bean>
<bean class="org.springframework.jdbc.core.JdbcTemplate"
name="jdbcTemplateObj">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
<bean class="com.app.EmployeeDaoImpl" name="empDao">
<property name="template">
<ref bean="jdbcTemplateObj"/>
</property>
</bean>
</beans>
Employee.java
package com.app;
public Employee() {
89
RaghuSir Sathya Technologies
super();
}
package com.app;
90
RaghuSir Sathya Technologies
}
package com.app;
import org.springframework.jdbc.core.JdbcTemplate;
@Override
public void createEmployee(Employee emp) {
String sql="insert into employee values(?,?,?)";
template.update(sql,emp.getEmpId(),emp.getEmpName(),emp.getEmpSal());
}
Main.java
package com.app;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
ApplicationContext context=new
ClassPathXmlApplicationContext("config.xml");
IEmployeeDao dao=(IEmployeeDao)context.getBean("empDao");
Employee emp=new Employee();
emp.setEmpId(101);
emp.setEmpName("abcd");
emp.setEmpSal(200.36);
dao.createEmployee(emp);
91
RaghuSir Sathya Technologies
Java Code:
package com.app;
this.addrId = addrId;
}
public String getLoc() {
returnloc;
}
Public void setLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return"Address [addrId=" + addrId + ", loc=" + loc + "]";
}
@Override
Public int hashCode() {
Final int prime = 31;
int result = 1;
result = prime * result + addrId;
result = prime * result + ((loc == null) ? 0 : loc.hashCode());
return result;
}
@Override
publicboolean equals(Object obj) {
if (this == obj)
returntrue;
if (obj == null)
returnfalse;
if (getClass() != obj.getClass())
returnfalse;
Address other = (Address) obj;
if (addrId != other.addrId)
returnfalse;
if (loc == null) {
if (other.loc != null)
returnfalse;
} elseif (!loc.equals(other.loc))
returnfalse;
returntrue;
}}
package com.app;
publicclass Employee {
privateintempId;
private String empName;
privatedoubleempSal;
private Address addr;
publicint getEmpId() {
93
RaghuSir Sathya Technologies
returnempId;
}
publicvoid setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
returnempName;
}
publicvoid setEmpName(String empName) {
this.empName = empName;
}
publicdouble getEmpSal() {
returnempSal;
}
publicvoid setEmpSal(double empSal) {
this.empSal = empSal;
}
public Address getAddr() {
returnaddr;
}
publicvoid setAddr(Address addr) {
this.addr = addr;
}
@Override
public String toString() {
return"Employee [empId=" + empId + ", empName=" + empName
+ ", empSal=" + empSal + ", addr=" + addr + "]";
}
@Override
publicint hashCode() {
finalint prime = 31;
int result = 1;
result = prime * result + ((addr == null) ? 0 : addr.hashCode());
result = prime * result + empId;
result = prime * result + ((empName == null) ? 0 : empName.hashCode());
long temp;
temp = Double.doubleToLongBits(empSal);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
Public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
94
RaghuSir Sathya Technologies
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (addr == null) {
if (other.addr != null)
return false;
} elseif (!addr.equals(other.addr))
returnfalse;
if (empId != other.empId)
returnfalse;
if (empName == null) {
if (other.empName != null)
returnfalse;
} elseif (!empName.equals(other.empName))
Return false;
if (Double.doubleToLongBits(empSal) != Double
.doubleToLongBits(other.empSal))
returnfalse;
returntrue;
}
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scanbase-package="com.app"/>
<beanclass="org.springframework.jdbc.datasource.DriverManagerDataSource"
name="dsObj">
<propertyname="driverClassName"value="oracle.jdbc.driver.OracleDriver"/>
<propertyname="url"value="jdbc:oracle:thin:@localhost:1521:xe"/>
<propertyname="username"value="system"/>
<propertyname="password"value="system"/>
</bean>
<beanclass="org.springframework.jdbc.core.JdbcTemplate"name="tempObj">
<propertyname="dataSource">
<refbean="dsObj"/>
</property>
95
RaghuSir Sathya Technologies
</bean>
</beans>
package com.app;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
@Component("empDao")
publicclass EmployeeDaoImpl {
@Autowired
private JdbcTemplate template;
i1=template.update(sql2,addr.getAddrId(),addr.getLoc(),employee.getEmpId());
}
if(i1==1 && i==1){
System.out.println("Data inserted successfully");
}
}
public Address getAddressDetailsBasedOnEmpId(int empId){
String sql="select a1.aid,a1.loc from emp e1 left outer join addr a1 on
e1.eid=a1.eid where e1.eid=?";
Address addr=template.queryForObject(sql,new RowMapper<Address>(){
@Override
96
RaghuSir Sathya Technologies
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.app.Address;
importcom.app.Employee;
import com.app.EmployeeDaoImpl;
publicclass Test {
}
}
97
RaghuSir Sathya Technologies
packagecom.app.model;
publicclass Employee {
privateintempId;
private String empName;
privatedoubleempSal;
public Employee() {
super();
}
public Employee(intempId, String empName, doubleempSal) {
super();
this.empId = empId;
this.empName = empName;
this.empSal = empSal;
}
publicintgetEmpId() {
returnempId;
}
publicvoidsetEmpId(intempId) {
this.empId = empId;
}
public String getEmpName() {
returnempName;
}
publicvoidsetEmpName(String empName) {
this.empName = empName;
}
publicdoublegetEmpSal() {
returnempSal;
}
publicvoidsetEmpSal(doubleempSal) {
this.empSal = empSal;
}
@Override
public String toString() {
return"Employee [empId=" + empId + ", empName=" + empName
+ ", empSal=" + empSal + "]";
}
98
RaghuSir Sathya Technologies
@Override
publicinthashCode() {
finalint prime = 31;
int result = 1;
result = prime * result + empId;
result = prime * result + ((empName == null) ? 0 : empName.hashCode());
long temp;
temp = Double.doubleToLongBits(empSal);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
publicboolean equals(Object obj) {
if (this == obj)
returntrue;
if (obj == null)
returnfalse;
if (getClass() != obj.getClass())
returnfalse;
Employee other = (Employee) obj;
if (empId != other.empId)
returnfalse;
if (empName == null) {
if (other.empName != null)
returnfalse;
} elseif (!empName.equals(other.empName))
returnfalse;
if (Double.doubleToLongBits(empSal) != Double
.doubleToLongBits(other.empSal))
returnfalse;
returntrue;
}
}
packagecom.app.dao;
importjava.util.List;
importcom.app.model.Employee;
publicinterfaceIEmployeeDao {
publicintinsertEmployeeToDB(Employee employee);
publicintupdateEmployeeById(Employee emp);
publicintdeleteEmployeeById(intempId);
public Employee getEmployeeObjectById(intempId);
99
RaghuSir Sathya Technologies
public List<Employee>getAllEmployessAsList();
}
packagecom.app.dao.impl;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.util.List;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.jdbc.core.JdbcTemplate;
importorg.springframework.jdbc.core.RowMapper;
importorg.springframework.stereotype.Component;
importcom.app.dao.IEmployeeDao;
importcom.app.model.Employee;
@Component("empSpringJdbcDao")
publicclassEmployeeSpringJdbcDaoImplimplementsIEmployeeDao{
@Autowired
privateJdbcTemplatetemplate;
@Override
publicintinsertEmployeeToDB(Employee employee) {
String sql="insert into empvalues(?,?,?)";
returntemplate.update(sql,
employee.getEmpId(),employee.getEmpName(),employee.getEmpSal());
}
@Override
publicintupdateEmployeeById(Employee emp) {
String sql="update emp set ename=?,esal=? whereeid=?";
returntemplate.update(sql,
emp.getEmpName(),emp.getEmpSal(),emp.getEmpId());
}
@Override
publicintdeleteEmployeeById(intempId) {
String sql="delete from emp where eid=?";
returntemplate.update(sql, empId);
}
@Override
public Employee getEmployeeObjectById(intempId) {
String sql="select * from emp where eid=?";
Employee emp=template.queryForObject(sql, newRowMapper<Employee>(){
@Override
public Employee mapRow(ResultSetrs, introwNum)
throwsSQLException {
Employee emp=newEmployee();
100
RaghuSir Sathya Technologies
emp.setEmpId(rs.getInt(1));
emp.setEmpName(rs.getString(2));
emp.setEmpSal(rs.getDouble(3));
returnemp;
}
}, empId);
returnemp;
}
@Override
public List<Employee>getAllEmployessAsList() {
String sql="select * from emp";
List<Employee>empList=template.query(sql, newRowMapper<Employee>(){
@Override
public Employee mapRow(ResultSetrs, introwNum)
throwsSQLException {
Employee emp=newEmployee();
emp.setEmpId(rs.getInt(1));
emp.setEmpName(rs.getString(2));
emp.setEmpSal(rs.getDouble(3));
returnemp;
}
});
returnempList;
}
}
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scanbase-package="com.app"/>
<context:property-placeholderlocation="jdbc.properties"/>
<beanclass="org.springframework.jdbc.datasource.DriverManagerDataSource"name
="dsObj">
<propertyname="driverClassName"value="${driver}"/>
<propertyname="url"value="${url}"/>
<propertyname="username"value="system"/>
<propertyname="password"value="system"/>
</bean>
<beanclass="org.springframework.jdbc.core.JdbcTemplate"name="tempObj">
<propertyname="dataSource">
<refbean="dsObj"/>
101
RaghuSir Sathya Technologies
</property>
</bean>
</beans>
#JDBC Properties File
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
user=system
password=system
packagecom.app;
importjava.util.List;
importorg.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
importcom.app.dao.IEmployeeDao;
importcom.app.model.Employee;
publicclass Test {
ApplicationContextcontext=newClassPathXmlApplicationContext("config.xml");
IEmployeeDaoob=(IEmployeeDao)context.getBean("empSpringJdbcDao");
List<Employee>empList=ob.getAllEmployessAsList();
System.out.println(empList);
}
}
102
RaghuSir Sathya Technologies
config.xml:
<context:annotation-config/>
<context:component-scan base-package="com.app"/>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
name="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
name="sessionFactory">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
103
RaghuSir Sathya Technologies
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.app.Employee</value>
</list>
</property>
</bean>
<bean class="org.springframework.orm.hibernate3.HibernateTemplate"
name="template">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</property>
</bean>
</beans>
Employee.java
package com.app;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="emp")
public class Employee {
@Id
@Column(name="eid")
private Integer empId;
104
RaghuSir Sathya Technologies
@Column(name="ename")
private String empName;
@Column(name="esal")
private Double empSal;
public Employee() {
super();
}
import java.util.List;
105
RaghuSir Sathya Technologies
package com.app;
import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
@Override
public Integer createEmployee(Employee emp) {
Integer id=(Integer)template.save(emp);
return id;
}
@Override
public Integer updateEmployee(Employee emp) {
template.update(emp);
return emp.getEmpId();
}
@Override
public Integer deleteEmployee(Integer empId) {
Employee emp=template.get(Employee.class, empId);
if (emp!=null) {
template.delete(emp);
}
return emp.getEmpId();
}
106
RaghuSir Sathya Technologies
@Override
public Employee loadEmployee(Integer empId) {
@Override
public List<Employee> getAllEmployees() {
return template.loadAll(Employee.class);
}
}
Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.app.Employee;
import com.app.IEmployeeDao;
/**
* @param args
* @author Raghu
*/
public static void main(String[] args) {
ApplicationContext context=new
ClassPathXmlApplicationContext("config.xml");
IEmployeeDao empDao=(IEmployeeDao)context.getBean("empDao");
Employee emp=new Employee(103,"ka", 16.5);
System.out.println(empDao.getAllEmployees());
}
107
RaghuSir Sathya Technologies
108
RaghuSir Sathya Technologies
Step 4: Controller
>Create a Java class.
>Use an annotation @Controller (Sterio type annot. )
>Enable annotations in config file
(use context schema for base pakage and annotation config)
Web.xml
109
RaghuSir Sathya Technologies
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>/abcd/*</url-pattern>
</servlet-mapping>
</web-app>
Sample-servlet.xml
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsps/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
110
RaghuSir Sathya Technologies
HomeController.java
package com.app.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HomeController {
@RequestMapping("/home")
public ModelAndView showView(){
@RequestMapping(value="/home",method=RequestMethod.POST)
public ModelAndView showView1(){
return null;
}
}
home.jsp
<h1>Welcome to Spring</h1>
URL:- http://localhost:8080/SampleSpringMVC/abcd/home
111
RaghuSir Sathya Technologies
Ex:
packagecom.app;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.ResponseBody;
importorg.springframework.web.servlet.ModelAndView;
@Controller
publicclassHomeController {
@RequestMapping("/welcome")
publicModelAndView welcome(){
ModelAndViewmav=newModelAndView("welcome");
mav.addObject("empId", 100);
mav.addObject("empName", "AJ");
mav.addObject("empSal", 250.36);
112
RaghuSir Sathya Technologies
returnmav;
}
Welcome.jsp
<h1>Data is :</h1>
<b>${empId},${empName},${empSal}</b>
<%=req.getAttribute(“empId”)%>
packagecom.app;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.ResponseBody;
importorg.springframework.web.servlet.ModelAndView;
@Controller
publicclassHomeController {
@RequestMapping("/welcome")
publicModelAndView welcome(){
ModelAndViewmav=newModelAndView("welcome");
Employeeemp=newEmployee();
emp.setEmpId(10);
emp.setEmpName("AJ");
emp.setEmpSal(12.35);
mav.addObject("empObj", emp);
returnmav;
}
<b> ${empObj.empId},${empObj.empName},${empObj.empSal}</b>
Or
113
RaghuSir Sathya Technologies
Out.print(emp.getEmpId());
%>
packagecom.app;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.ResponseBody;
importorg.springframework.web.servlet.ModelAndView;
@Controller
publicclassHomeController {
@RequestMapping("/welcome")
publicModelAndView welcome(){
ModelAndViewmav=newModelAndView("welcome");
Employeeemp=newEmployee();
emp.setEmpId(10);
emp.setEmpName("AJ");
emp.setEmpSal(12.35);
Employee emp2=newEmployee();
emp2.setEmpId(10);
emp2.setEmpName("AJ");
emp2.setEmpSal(12.35);
Employee emp3=newEmployee();
emp3.setEmpId(10);
emp3.setEmpName("AJ");
emp3.setEmpSal(12.35);
List<Employee>empListObj=newArrayList<Employee>();
empListObj.add(emp);
empListObj.add(emp2);
empListObj.add(emp3);
mav.addObject("empListObj", empListObj);
returnmav;
}
114
RaghuSir Sathya Technologies
<c:forEachitems="${empListObj}"var="emp">
<c:outvalue="${emp.empId}"/>,<c:outvalue="${emp.empName}"/>,<c:outvalue="${emp.em
pSal}"/><br/>
</c:forEach>
or
<%
ListempList=request.getAttribute("empListObj");
Iterator iterator= empList.iterator();
while(iterator.hasNext()){
Employeeemp=(Employee)iterator.next();
out.println(emp);
}
%>
Location :http://central.maven.org/maven2/javax/servlet/jstl/1.2/jstl-1.2.jar
115
RaghuSir Sathya Technologies
Web.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/
ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID"version="2.5">
<display-name>sample</display-name>
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>/app/*</url-pattern>
116
RaghuSir Sathya Technologies
</servlet-mapping>
</web-app>
Sample-servlet.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
">
<context:annotation-config/>
<context:component-scanbase-package="com.app"/>
<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="prefix"value="/WEB-INF/jsp/"/>
<propertyname="suffix"value=".jsp"/>
</bean>
<beanclass="org.springframework.jdbc.datasource.DriverManagerDataSource"name
="datasource">
<propertyname="driverClassName"value="com.mysql.jdbc.Driver"/>
<propertyname="url"value="jdbc:mysql://localhost:3306/test"/>
<propertyname="username"value="root"/>
<propertyname="password"value="root"/>
</bean>
<beanclass="org.springframework.orm.hibernate3.annotation.AnnotationSessionFac
toryBean"name="sessionFactory">
<propertyname="dataSource">
<refbean="datasource"/>
</property>
<propertyname="annotatedClasses">
<list>
<value>com.app.model.Employee</value>
</list>
</property>
<propertyname="hibernateProperties">
<props>
117
RaghuSir Sathya Technologies
<propkey="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<propkey="hibernate.show_sql">true</prop>
<propkey="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
</beans>
EmployeeController.java
package com.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.app.model.Employee;
import com.app.service.IEmployeeService;
@Controller
publicclass EmployeeController {
@Autowired
private IEmployeeService empService;
@RequestMapping("/home")
public ModelAndView homePage(){
returnnew ModelAndView("Home");
}
@RequestMapping("/insert")
public String insert(@ModelAttribute("employee")Employee emp){
empService.createEmployee(emp);
System.out.println("hello");
return"redirect:/app/show";
118
RaghuSir Sathya Technologies
@RequestMapping("/show")
public ModelAndView show(@ModelAttribute("employee")Employee emp){
List<Employee> employeeList=empService.showEmployeeDetails();
returnnew ModelAndView("Home","employeeList",employeeList);
}
@RequestMapping("/delete/{empId}")
public String delete(@PathVariable("empId")int empId){
empService.deleteEmployeeById(empId);
return"redirect:/app/show";
}
@RequestMapping("/edit/{empId}")
public ModelAndView edit(@PathVariable("empId")int empId){
Employee emp=empService.loadEmployeeById(empId);
returnnew ModelAndView("Edit","emp",emp);
}
}
IEmployeeService.java
package com.app.service;
import java.util.List;
importcom.app.model.Employee;
publicinterface IEmployeeService {
package com.app.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.app.dao.IEmployeeDao;
119
RaghuSir Sathya Technologies
import com.app.model.Employee;
import com.app.service.IEmployeeService;
@Service("empService")
publicclass EmployeeServiceImpl implements IEmployeeService {
@Autowired
private IEmployeeDao empDao;
@Override
publicvoid createEmployee(Employee employee) {
try {
empDao.createEmployee(employee);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public List<Employee> showEmployeeDetails() {
List<Employee> employeeList=null;
try {
employeeList=empDao.showEmployeeDetails();
} catch (Exception e) {
// TODO: handle exception
}
return employeeList;
}
@Override
publicvoid deleteEmployeeById(int empId) {
try {
empDao.deleteEmployeeById(empId);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Employee loadEmployeeById(int empId) {
Employee emp=null;
try {
emp=empDao.loadEmployeeById(empId);
} catch (Exception e) {
e.printStackTrace();
}
return emp;
}
120
RaghuSir Sathya Technologies
IEmployeeDao.java
package com.app.dao;
import java.util.List;
importcom.app.model.Employee;
publicinterface IEmployeeDao {
EmployeeDaoImpl.java
package com.app.dao.impl;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.app.dao.IEmployeeDao;
import com.app.model.Employee;
@Repository("empDao")
publicclass EmployeeDaoImpl implements IEmployeeDao{
@Autowired
private SessionFactory sessionFactory;
@Override
publicvoid createEmployee(Employee employee) {
Session session=null;
121
RaghuSir Sathya Technologies
Transaction tx=null;
try {
session=sessionFactory.openSession();
tx=session.beginTransaction();
tx.begin();
session.saveOrUpdate(employee);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}finally{
session.flush();
session.close();
}
}
@Override
public List<Employee> showEmployeeDetails() {
Session session=null;
Transaction tx=null;
Criteria criteria=null;
List<Employee> employeeList=null;
try {
session=sessionFactory.openSession();
tx=session.beginTransaction();
tx.begin();
criteria=session.createCriteria(Employee.class);
employeeList=criteria.list();
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}finally{
session.flush();
session.close();
}
return employeeList;
}
@Override
122
RaghuSir Sathya Technologies
session=sessionFactory.openSession();
tx=session.beginTransaction();
tx.begin();
emp=(Employee)session.get(Employee.class, empId);
session.delete(emp);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}finally{
session.flush();
session.close();
}
}
@Override
public Employee loadEmployeeById(int empId) {
Session session=null;
Employee emp=null;
try {
session=sessionFactory.openSession();
emp=(Employee)session.get(Employee.class, empId);
} catch (Exception e) {
e.printStackTrace();
}finally{
session.flush();
session.close();
}
return emp;
}
}
Home.jsp
<%@pagelanguage="java"contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
123
RaghuSir Sathya Technologies
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<styletype="text/css">
tabletrth{
color: white;
background-color: black;
}
</style>
</head>
<body>
<h1>Wel come page</h1>
<formaction="insert"method="POST">
<pre>
user Id:
<inputtype="number"name="empId"value="${emp.empId}"required="required"min="10"m
ax="200">
user name:
<inputtype="text"name="empName"value="${emp.empName}"required="required">
user sal : <inputtype="text"name="empSal"value="${emp.empSal}"required="required">
<inputtype="submit"value="Insert">
</pre>
</form>
<c:iftest="${!empty employeeList}">
<tableborder="1">
<tr>
<th>EMP ID</th><th>EMP NAME</th><th>EMP SAL</th>
</tr>
<c:forEachitems="${employeeList}"var="employee">
<tr>
<td><ahref="edit/${employee.empId}"><c:outvalue="${employee.empId}"/></td>
<td><c:outvalue="${employee.empName}"/></td>
<td><c:outvalue="${employee.empSal}"/></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
124
RaghuSir Sathya Technologies
Edit.jsp
<%@pagelanguage="java"contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<formaction="../insert"method="POST">
<pre>
user Id:
<inputtype="number"name="empId"value="${emp.empId}"required="required"min="10"m
ax="200">
user name:
<inputtype="text"name="empName"value="${emp.empName}"required="required">
user sal : <inputtype="text"name="empSal"value="${emp.empSal}"required="required">
<inputtype="submit"value="Insert">
</pre>
</form>
</body>
</html>
});
125
RaghuSir Sathya Technologies
</script>
package com.app;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HomeController {
@RequestMapping("/welcome")
public ModelAndView showPage(){
@RequestMapping("/ajaxCall")
public @ResponseBody String provideResponse(@RequestParam("input")String
input){
}
<?xml version="1.0" encoding="UTF-8"?>
126
RaghuSir Sathya Technologies
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.app"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
package com.app;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
127
RaghuSir Sathya Technologies
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HomeController {
@Autowired
@Qualifier("empService")
private IEmpService empService;
@RequestMapping(value="/register")
public ModelAndView insertRecord(){
return new ModelAndView("Register");
}
@RequestMapping(value="/home/{empId}",method=RequestMethod.GET)
public ModelAndView sayHello(@PathVariable("empId")String empid){
System.out.println("Entered vales is"+empid);
return new ModelAndView("Page1");
}
@RequestMapping(value="/insert")
public ModelAndView insertRecord(@ModelAttribute("employee")Employee emp){
empService.insertEmployee(emp);
List<Employee> empList=empService.getAllEmployee();
@RequestMapping("/delete/{empId}")
public ModelAndView deleteRecord(@PathVariable("empId")Integer empId){
empService.deleteEmployee(empId);
List<Employee> empList=empService.getAllEmployee();
128
RaghuSir Sathya Technologies
package com.app;
import java.util.List;
----------]
package com.app;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service("empService")
public class EmpServiceImpl implements IEmpService {
@Autowired
@Qualifier("empDao")
private IEmpDao empDao;
@Override
public Integer insertEmployee(Employee emp) {
return empDao.insertEmployee(emp);
}
@Override
public List<Employee> getAllEmployee() {
return empDao.getAllEmployee();
}
@Override
public void deleteEmployee(Integer empId) {
empDao.deleteEmployee(empId);
129
RaghuSir Sathya Technologies
}
package com.app;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service("empService")
public class EmpServiceImpl implements IEmpService {
@Autowired
@Qualifier("empDao")
private IEmpDao empDao;
@Override
public Integer insertEmployee(Employee emp) {
return empDao.insertEmployee(emp);
}
@Override
public List<Employee> getAllEmployee() {
return empDao.getAllEmployee();
}
@Override
public void deleteEmployee(Integer empId) {
empDao.deleteEmployee(empId);
package com.app;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="emp")
public class Employee {
130
RaghuSir Sathya Technologies
@Id
@Column(name="eid")
private Integer empId;
@Column(name="ename")
private String empName;
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="insert">
<pre>
User Id :<input type="text" name="empId" id="empId">
User Name: <input type="text" name="empName" id="empName">
<input type="submit" value="Register">
</pre>
</form>
<br/>
</c:forEach>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.app"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean name="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.app.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
132
RaghuSir Sathya Technologies
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.hibernate3.HibernateTemplate"
name="template">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
133
RaghuSir Sathya Technologies
Aspect Oriented Programming :- Without changing business logic, a new service can be
added to existed layer, using Aspect and advices we can construct services.
Aspect:
package com.app;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class SampleAspectEx {
@Before("execution(* com.one.*.*.get*(..))")
public void showMessage(){
package com.one.two;
134
RaghuSir Sathya Technologies
Shape:
package com.one.three;
135
RaghuSir Sathya Technologies
Student:
package com.app.module;
136
RaghuSir Sathya Technologies
}
Rectangle:
package com.one;
Employee:
package com.app;
138
RaghuSir Sathya Technologies
Design:
package com.one.two;
139
RaghuSir Sathya Technologies
}
Config.xml:
<aop:aspectj-autoproxy/>
140
RaghuSir Sathya Technologies
</bean>
<bean class="com.one.two.Circle" name="c1">
<property name="name">
<value>circle</value>
</property>
<property name="type">
<value>20</value>
</property>
</bean>
<bean class="com.one.Rectangle" name="r1">
<property name="name">
<value>rectangle</value>
</property>
<property name="type">
<value>30</value>
</property>
</bean>
</bean>
</bean>
<value>60</value>
</property>
</bean>
<bean class="com.app.SampleAspectEx"></bean>
</beans>
Test class:
package com.app;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.app.module.Student;
import com.one.Rectangle;
import com.one.three.Shape;
import com.one.two.Circle;
import com.one.two.Design;
ApplicationContext context=new
ClassPathXmlApplicationContext("config.xml");
Employee e=context.getBean("emp",Employee.class);
Student std=context.getBean("std",Student.class);
Shape s1=context.getBean("s1",Shape.class);
Circle c1=context.getBean("c1",Circle.class);
Rectangle r1=context.getBean("r1",Rectangle.class);
Design d1=context.getBean("d1",Design.class);
//(* com.one.Rectangle.get*())
c1.getName(10);
d1.getName(20);
d1.getName();
c1.getName();
r1.getName();
142
RaghuSir Sathya Technologies
r1.getType();
r1.getName(10);
r1.getType(10);
JARS:
AOP JARS(only):
http://www.mediafire.com/download/2szvk5sjxgoqkdp/Maven.rar
http://central.maven.org/maven2/cglib/cglib/3.1/cglib-3.1.jar
143
RaghuSir Sathya Technologies
With the Dependency Injection(DI) approach, dependencies are explicit and evident
in constructor or JavaBean properties.
IoC containers tend to be lightweight, especially when compared to EJB containers,
for example. This is beneficial for developing and deploying applications on
computers with limited memory and CPU resources.
Spring does not reinvent the wheel instead, it truly makes use of some of the existing
technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK
timers, other view technologies.
Spring is organized in a modular fashion. Even though the number of packages and
classes are substantial, you have to worry only about ones you need and ignore the
rest.
Testing an application written with Spring is simple because environment-dependent
code is moved into this framework. Furthermore, by using JavaBean-style POJOs, it
becomes easier to use dependency injection for injecting test data.
Spring’s web framework is a well-designed web MVC framework, which provides a
great alternative to web frameworks such as Struts or other over engineered or less
popular web frameworks.
Spring provides a consistent transaction management interface that can scale down
to a local transaction (using a single database, for example) and scale up to global
transactions (using JTA, for example).
144
RaghuSir Sathya Technologies
<props>
<prop key="admin">[email protected]</prop>
<prop key="support">[email protected]</prop>
</props>
</property>
</bean>
You can use “util:” namespace as well to create properties bean from properties file, and
use bean reference for setter injection.
<util:properties id="emails" location="com/app/emails.properties" />
145
RaghuSir Sathya Technologies
E.g. You can use @Autowired annotation on setter methods to get rid of
the <property> element in XML configuration file. When Spring finds
an @Autowired annotation used with setter methods, it tries to performbyType autowiring
on the method.
You can apply @Autowired to constructors as well. A constructor @Autowired annotation
indicates that the constructor should be autowired when creating the bean, even if
no <constructor-arg> elements are used while configuring the bean in XML file.
public class TextEditor {
private SpellCheckerspellChecker;
@Autowired
public TextEditor(SpellCheckerspellChecker){
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
146
RaghuSir Sathya Technologies
<context:annotation-config/>
</beans>
147
RaghuSir Sathya Technologies
{
@Autowired
@Qualifier("personA")
private Person person;
}
Setter Injection will overrides the constructor injection value, provided if we write
setter and constructor injection for the same property. But, constructor injection cannot
overrides the setter injected values. It’s obvious because constructors are called to first to
create the instance.
Using setter injection you can not guarantee that certain dependency is injected or not,
which means you may have an object with incomplete dependency. On other hand
constructor Injection does not allow you to construct object, until your dependencies are
ready.
In constructor injection, if Object A and B are dependent each other i.e A is depends
on B and vice-versa, Spring throws ObjectCurrentlyInCreationException while creating
objects of A and B because A object cannot be created until B is created and vice-versa. So
spring can resolve circular dependencies through setter-injection because Objects are
constructed before setter methods invoked.
148
RaghuSir Sathya Technologies
In prototype scope, a single bean definition has any number of object instances.
In request scope, a bean is defined to an HTTP request. This scope is valid only in a web-
aware Spring ApplicationContext.
In session scope, a bean definition is scoped to an HTTP session. This scope is also valid only
in a web-aware Spring ApplicationContext.
In global-session scope, a bean definition is scoped to a global HTTP session. This is also a
case used in a web-aware Spring ApplicationContext.
The default scope of a Spring Bean is Singleton.
no: This is default setting. Explicit bean reference should be used for wiring.
byName: When autowiring byName, the Spring container looks at the properties of the
beans on which autowireattribute is set to byName in the XML configuration file. It then
tries to match and wire its properties with the beans defined by the same names in the
configuration file.
byType: When autowiring by datatype, the Spring container looks at the properties of the
beans on which autowireattribute is set to byType in the XML configuration file. It then tries
to match and wire a property if its type matches with exactly one of the beans name in
configuration file. If more than one such beans exist, a fatal exception is thrown.
constructor: This mode is similar to byType, but type applies to constructor arguments. If
there is not exactly one bean of the constructor argument type in the container, a fatal error
is raised.
autodetect: Spring first tries to wire using autowire by constructor, if it does not work,
Spring tries to autowirebybyType.
149
RaghuSir Sathya Technologies
Dependency injection/ or IoC (inversion of control) – Is the main principle behind decoupling
process that Spring does
Factory – Spring uses factory pattern to create objects of beans using Application Context
reference
Singleton – by default, beans defined in spring config file (xml) are only created once. No
matter how many calls were made using getBean() method, it will always have only one
bean. This is because, by default all beans in spring are singletons.
This can be overridden by using Prototype bean scope.Then spring will create a new bean
object for every request.
Model View Controller – The advantage with Spring MVC is that your controllers are POJOs
as opposed to being servlets. This makes for easier testing of controllers. One thing to note
is that the controller is only required to return a logical view name, and the view selection is
left to a separate ViewResolver. This makes it easier to reuse controllers for different view
technologies.
View Helper – Spring has a number of custom JSP tags, and velocity macros, to assist in
separating code from presentation in views.
Template method – used extensively to deal with boilerplate repeated code (such as closing
connections cleanly, etc..). For example JdbcTemplate, JmsTemplate, JpaTemplate.
Aspect: Aspect is a class that implements cross-cutting concerns, such as logger, encryption.
150
RaghuSir Sathya Technologies
Aspects can be a normal class configured and then configured in Spring Bean configuration
file or we can use Spring AspectJ support to declare a class as Aspect
using @Aspect annotation.
Advice: Advice is the action taken for a particular join point. In terms of programming, they
are methods that gets executed when a specific join point with matching pointcut is reached
in the application. You can think of Advices as Spring interceptors or Servlet Filters.
Pointcut: Pointcut are regular expressions that is matched with join points to determine
whether advice needs to be executed or not. Pointcut uses different kinds of expressions
that are matched with the join points. Spring framework uses the AspectJ pointcut
expression language for determining the join points where advice methods will be applied.
Join Point: A join point is the specific point in the application such as method execution,
exception handling, changing object variable values etc. In Spring AOP a join points is always
the execution of a method.
@Component is used to indicate that a class is a component. These classes are used for auto
detection and configured as bean, when annotation based configurations are used.
@Controller is a specific type of component, used in MVC applications and mostly used with
RequestMapping annotation. Handles mainly servlet request and response
@Service is used to indicate that a class is a Service. Usually the business facade classes that
provide some services are annotated with this.
We can use any of the above annotations for a class for auto-detection but different types
are provided so that we can avoid conversion of objects as per layers.
Spring provides excellent support for localization or i18n through resource bundles.
Basis steps needed to make our application localized are:
151
RaghuSir Sathya Technologies
<beans:bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
</beans:bean>
<beans:bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
</beans:property>
</beans:bean>
<interceptors>
<beans:bean
class="org.springframework.web.servlet.i18n.LocaleChange
Interceptor">
152
RaghuSir Sathya Technologies
</beans:bean>
</interceptors>
Use spring:message element in the view pages with key names, DispatcherServlet
picks the corresponding value and renders the page in corresponding locale and
return as response.
What are some of the important Spring annotations you have used?
@ResponseBody – for sending Object as response, usually for sending XML or JSON data as
response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
Less code: By using the JdbcTemplate class, you don't need to create
connection,statement,starttransaction,commit transaction and close connection to execute
different queries. You can execute the query directly.
153
RaghuSir Sathya Technologies
RowMapper interface allows to map a row of the relations with the instance of user-defined
class. It iterates the ResultSet internally and adds it into the collection. So we don't need to
write a lot of code to fetch the records as ResultSetExtractor.
Advantage of RowMapper :
RowMapper saves a lot of code becuase it internally adds the data of ResultSet into the
collection.
It defines only one method mapRow that accepts ResultSet instance and int as the
parameter list. Syntax of the method is given below:
Example:
this.template = template;
@Override
154
RaghuSir Sathya Technologies
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
return e;
} });
DownloadLinks JARS
Spring :
https://repo.spring.io/release/org/springframework/spring/
Hibernate :
https://sourceforge.net/projects/hibernate/files/hibernate3/
Struts :
https://struts.apache.org/download.cgi
Eclipse :
http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/junosr2
155
RaghuSir Sathya Technologies
Oracle Type 4 :
http://central.maven.org/maven2/com/oracle/ojdbc14/10.2.0.2.0/ojdbc14-10.2.0.2.0.jar
MySQL:
http://central.maven.org/maven2/mysql/mysql-connector-java/5.0.5/mysql-connector-
java-5.0.5.jar
Commons -logging:
http://central.maven.org/maven2/commons-logging/commons-logging/1.2/commons-
logging-1.2.jar
Java Mail :
http://central.maven.org/maven2/javax/mail/mail/1.4.3/mail-1.4.3.jar
Commons-codec:
http://central.maven.org/maven2/commons-codec/commons-codec/1.10/commons-codec-
1.10.jar
156