Spring Coremodule
Spring Coremodule
1. Framework is a Software.
2. It is an abstraction layer of existing technology (like JSE, JEE).
3. Framework is not part of JSE and JEE, JME but Framework S/W is using JSE
and JEE APIs.
4. F/W is providing a predefined support to developer in application
development.
5. F/W is a semi-finished application.
6. F/W is a special kind of S/W which comes in the form of set of jar files and it
makes an applications development in less time.
Framework
Note: Container is a Software that manage application life cycle from birth to death.
Spring Versions:
1.x 7 Modules
2.x 6 Modules
3.x 20 Modules (6 Major)
Spring Spring
ORM Web
(Hibernate) (Servlets/JSP) Spring
Spring 3 4 Web
AOP MVC
Spring Spring (Any F/W)
DAO Context
(JDBC) (EJB)
7 2 5 6
Spring Core
(Core Java) 1
Types of Frameworks
1. Invasive F/Ws:
It forces the developers to extend or to implement their
predefined class and interfaces (which are given by F/W S/W).
Ex – Struts 1.x
2. Non-Invasive F/Ws:
It does not force the developers to extend or to implement
their predefined class and interfaces (which are given by F/W S/W). It is also light
weight compare to other F/Ws, because it doesn’t use third party container.
Ex – Spring
Struts 2.x
Hibernate
View 7
HttpResponse
JSP Program 4
Presentation Logic
MVC Architecture
DB
ERP
Spring:
Versions:
1.x (jdk 1.3+)
2.x (compatible with jdk 1.5+)
3.x (compatible with jdk 1.6+)
Vendor: Interface21
Creator: Mr. Rod Jhonson
Note:
Servlets, JSP, EJB containers are heavy weight containers.
Spring Architecture:
Spring 1.x :
1. Core Module
2. DAO Module
3. ORM Module
4. Context Module
5. AOP Module
6. Web Module
7. Web MVC Module
Spring Spring
ORM Web
(Hibernate) (Servlets/JSP) Spring
Spring Web
AOP MVC
Spring Spring (Any F/W)
DAO Context
(JDBC) (EJB)
Spring Core
(Core Java)
1. Core Module:
2. DOA Module:
3. ORM Module:
4. Context Module:
It provides an abstraction layer on JEE Technologies like Java Mail API, JMS
(Java Message Services), EJB, RMI, Web Services etc…
It is used to implement Business Login (Service Layer) of an Enterprise
Application.
6. Web Module:
Spring 2.x:
Note:
Controller
Layer
Data
Client Service
Access
Layer Layer
Presentation Layer
Layer
2. Controlling Logic:
3. Presentation Logic:
Presentation logic views user interface to end user to supply inputs to the
application and view the results of the application.
4. Persistence Logic:
Container:
1. Interface [optional]
2. bean class
3. Spring configuration File
4. Client Application (main class)
1. Interface:
class Demo{
// Demo is POJO
}
class Sample extends Demo{
// Sample is POJO
}
class Demo extends Action{
// Demo is not a POJO, because Action is Struts class
}
class Demo extends AbstractController{
// Demo is not POJO, because AbstractController is Spring class.
}
class Demo implements Serializable{
// Demo is a POJO, because this interface is in java.io package
}
class Sample extends Demo{
// Sample is POJO
}
POJI: [Plain Old Java Interface]
Note:
bean class is always a POJO, but POJO class may or may not be a bean.
2. bean:
class Test{
public static void main(String[] args){
Class cls = Class.forName(“java.lang.Thread”);
System.out.println(cls.getClass());
Object obj = cls.newInstance();
Thread t = (Thread)obj;
System.out.println(t.getClass());
}
}
3. Spring Configuration (cfg) File:
Note:
One important feature of Spring core container is that is does not force the
programmers/ users. To have any one format of configurations, but most of the F/Ws
which are designed to have xml based or .property file based configurations, but
Spring at present allows us to supply the configuration either as an xml format or
.property file format or programmatically using the Spring API.
The Spring core container can be instantiated by creating an object of any one of
the BeanFactory or ApplicatonContext interface.
BeanFactory:
BeanFactory (I)
XmlBeanFactory (C)
Resource (I)
ApplicationContext (I)
ClassPathXmlApplicationContext (C)
XmlWebApplicationContext (C)
FileSystemXmlApplicationContext (C)
Note:
The Spring container performs the injection by executing Spring bean class
setter methods then it is called Setter Injection.
2. Constructor Injection:
In Spring configuration file <beans> tag is a root tag. It encloses all the Spring
bean definitions.
<bean> tag described a Spring bean.
<bean> tag id attribute holds the object name.
Class attribute is used to specify bean class name.
<property> tag is used to describe one setter method property and which allows
only one argument.
Ex –
<property name = “student” value = “1001”/>
|_stdObject.setStudentId(100);
With the <property> tag container calls the corresponding setter method to
perform the injection.
<property> tag support 3 attributes…
I. name attribute:
This attribute is used to specify bean object property name.
It follows a java beans convention like if property name is Uname then
corresponding setter method name is setUname(String uname).
Note:
In Spring primitive types, wrapper object types, String types are called Simple
types.
Application Structure:
F:\Spring Programs\FirstApp
|
|-------Hello.java
|-------myBeans.xml
|-------Student.java
|-------Test.java
|-------com
|-------nareshit
|------Hello.class
|------Student.class
|------client
|-----Test.class
Hello.java
package com.nareshit;
Student.java
package com.nareshit;
myBean.xml
Client Application
Test.java
package com.nareshit.client;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xm.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import com.nareshit.Student;
public class Test{
public static void main(String[] args){
Resource r = new FileSystemResource(“f://FirstSpringApp/myBeans.xml”);
BeanFactory container = new XmlBeanFactory(r);
// get Bean Object from container for this we can call the following method
// from BanFactory
// public Object getBean(String beanName)
Object obj = container.getBean(“std”);
Student student = (Student)obj; // downcasting
String mst = student.sayHello();
System.out.println(msg);
}
}
Note:
Every Framework S/W contains 2 types of jar file…
*. To compile and execute above application we need to set the following jar files
into the classpath -
http://mvnrepository.com/atifact/org.springframework/spring-
core/3.0.0.RELEASE
http://mvnrepository.com/atifact/org.springframework/spring-
bean/2.0.0.RELEASE
Note:
Spring container performs the Dependency Injection only on those spring
bean object, if that are created by spring container itself. That means Spring
container can’t perform DI on Spring bean class object that are created by
developer manually.
When the BeanFactory container is activated it reads and verifies the entries
of spring configuration file.
Spring container internally uses SAS parser of an XML to read and process
spring configuration file entries.
XML parser is a S/W application that can validate XML document against
DTD/Schema rules and read, process the XML document.
FileSystemResource:
ClassPathResource:
Application Structure:
SpringExample1
|------src
| |-------com.nareshit.bean
| | |------Employee.java
|-------com.nareshit.client
| |------Test.java
|-------com.nareshit.config
| |------myBean.xml
|-------com.nareshit.dao
| |------EmployeeDao.java
| |------EmployeeDaoImpl.java
|-------com.nareshit.service
|------EmployeeService.java
|------EmploeeServiceImpl.java
[-]JRE System Library
//Employee.java
package com.nareshit.bean;
public class Employee{
private int empNo;
private String Name;
private double Salary;
//required setter and getter methods
Public int getEmpNo(){
return empNo;
}
}
//EmployeeService.java
package com.nareshit.service;
import com.nareshit.bean.Employee;
public interface EmployeeService{
int createEmloyee(Employee emp);
}
//EmployeeServiceImpl.java
import com.nareshit.bean.employee;
public class EmployeeService{
private EmployeeDao empDao;
public void setEmpDao (EmployeeDao empDao){
this.empDao = empDao;
}
public int createEmployee (Employee emp){
int count = empDao.saveEmployee(emp);
return count;
}
}
//EmployeeDao
import com.nareshit.bean.employee;
public interface EmployeeDao{
int saveEmployee (Employee emp);
}
//EmployeeDaOImpl
import java.sql.connection;
public class EmployeeDaoImpl implements EmployeeDao{
private connection con;
public EmployeeDaoImpl(){
try{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
String url = “jdbc:oracle:thin:@localhot:1521:XE”;
String user = “system”;
String pass = “rajtomar”;
con = DriverManager.getConnection(url,user,pass);
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
catch(SQLException e){
e.printStackTrace();
}
}
public int saveEmployee (Employee emp){
int count = 0;
String sql = “insert into employee values(?,?,?)”;
try{
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1,emp.getEmpNo());
pst.setString(2,emp.getName());
pst.setDouble(3,emp.getSalary());
count = pst.executeUpdate();
}
catch(SQLException e){
e.printStackTrace();
}
return count;
}
}
//myBean.xml
<beans>
<bean id = “empServiceObj”
class = “com.nareshit.service.EmployeeServiceImpl”>
<property name = “empDao” ref = “empDaoObj”/>
</bean>
</beans>
//Test.java
public Test{
public static void main(String[] args){
Resource r = new ClassPathResource(“com/nareshit/config/myBean.xml”);
BeanFactory factory = XmlBeanFactory(r);
Objec obj = factory.getBean(“empServiceObj”);
EmployeeService eservice = (Employee)obj;
Employee emp = new Employee();
emp.setEmpNo(1001);
emp.setName(“Raj”);
emp.setSalary(30000);
int count = eservice.createEmployee(emp);
if(count>0){
System.out.println(“Employee Created”);
}
else{
System.out.println(“Employee not Created”);
}
}
}
Constructor Injection:
Step 1:
Create the bean class with the required properties (dependencies) and with the
required constructors.
Step 2:
Make the user of <constructor-arg> tag inside the <bean> tag. If the
constructor parameter is simple type to pass the value, we can use <value> attribute.
If the constructor parameter is Object type, use <ref> attribute.
Ex –
ConstructorInjectionExample1
|
|------com.nareshit.bean
| |------Employee.java
|------com.nareshit.client
| |------Test.java
|------com.nareshit.xml
|------myBean.xml
//Employee.java
public class Employee{
private int empNo;
private String empName;
public Employee(int empNo, String empName){
this.empNo = empNo;
this.empName = empName;
}
Public void getEmployeeDetails(){
System.out.println(“EmpNo: “+empNo);
System.out.println(“EmpName: “+empName);
}
}
//myBean.xml
<beans>
<bean id = “emp” class = “com.nareshit.bean.Employee”>
<constructor-arg value = “1001”/>
<constructor-arg value = “Raj”/>
</bean>
</beans>
//Test.java
public class Test{
public static void main(String[] agrs){
Resource r = new ClassPathResource(“com/nareshit/xml/myBean.xml”);
BeanFactory factory = new XmlBeanFactory(r);
Employee emp = (Employee)factory.getBean(“emp”);
emp.getEmployeeDetails();
}
}
Ex –
//Employee.java
public class Employee{
private int eno;
private String name;
private double sal;
private String design;
public Employee(int eno, String name){
this.eno = eno;
this.name = name;
}
//myBean.xml
<beans>
<bean id = “emp” class = “com.nareshit.bean.Employee”>
<constructor-arg value = “1001”/>
<constructor-arg value = “Raj”/>
</bean>
</beans>
//Test.java
public class Test{
public static void main(String[] agrs){
Resource r = new ClassPathResource(“com/nareshit/xml/myBean.xml”);
BeanFactory factory = new XmlBeanFactory(r);
Employee emp = (Employee)factory.getBean(emp);
emp.getEmployeeDetails();
}
}
<beans>
<bean id = “emp” class = “Employee”>
<constructor-arg value = “1001” type = “int”, index = “0”/>
<constructor-arg value = “Raj” type = “java.lang.String”, index =
“1”/>
</bean>
</beans>
Note:
If all the bean properties are configured for setter injection, then spring
container create the spring bean class object using zero argument
constructor.
If all the bean properties are configured for constructor injection, then spring
container create the spring bean class object using parameterized argument
constructor.
If same bean property are configured for constructor injection and same bean
property for setter injection, then spring container create the spring bean class
object using parameterized constructor.
Q. What happen if same bean property is configured for setter and constructor
injection with different values?
Ans.
<bean id = “std” class = “Student”>
<property name = “name” “raj”/>
<contructor-arg value = “raja”/>
name = raj
raja
Since setter method executes after constructor execution, so the value passed through
setter injection will override the value injected by constructor injection but bean
object well be created by using parameterized constructor.
Step 2: Make the use of collection configuration element in bean configuration file
i.e. we use <list> tag inside <property> or <constructor> tag.
ListTypeBasedInjectionExample
|------src
| |-------com.nareshit.bean
| | |--------College.java
| | |--------Student.java
| |-------com.nareshit.client
| |--------Test.java
|------myBean.xml
//Student.java
package com.narshit.bean;
public class Student{
private int sid;
private String name;
public String toString(){
return “Student id : ”+sid+”\n”+”Name : ”+name;
}
//required getter and setter methods
}
//College.java
package com.nareshit.bean;
import java.util.List;
public class College{
private String collegeName;
private List<Student> listOfStudetn;
public College(Sting collegeName){
this.collegeName = collegeName;
}
public void setListOfStudent(List<Student> listOfStudent){
this.listOfStudent = listOfStudent;
}
public String getCollegeName(){
return collegeName;
}
public List<Student> getListofStudent(){
return listOfStudent;
}
}
//myBean.xml
<beans>
<bean id = “studentObj1” class = “com.nareshit.bean.Student”>
<property name = “sid” value = “1001”/>
<property name = “name” value = “raj”/>
</bean>
<bean id = “studentObj2” class = “com.nareshit.bean.Student”>
<property name = “sid” value = “1002”/>
<property name = “name” value = “tomar”/>
</bean>
<bean id = “studentObj3” class = “com.nareshit.bean.Student”>
<property name = “sid” value = “1003”/>
<property name = “name” value = “raja”/>
</bean>
<bean id = “collegeObj” class = “com.nareshit.bean.College”>
<constructor-arg value = “NIT”>
</constructor-arg>
<property name = “listOfStudent”>
<list>
<ref bean = “studentObj1”>
<ref bean = “studentObj2”>
<ref bean = “studentObj3”>
</list>
</property>
</bean>
</beans>
//Test.java
public class Test{
public static void main(String[] args){
Resource r = new ClassPathResource(“myBean.xml”);
BeanFactory f = new XmlBeanFactory(r);
College c = (College)f.getBean(“collegeObj);
System.out.println(c.getCollegeName());
List<Student> listOfStudent;
c.listOfStudent();
for(Student.listOfStudent){
System.out.println(Student);
}
}
}
Q. What are the difference between ref bean and ref local?
Ans.
A local attribute looks for the given id based dependent spring bean the current
configuration file only.
Ex –
<bean id = “s1” class = “Student”>
<property name = “address”/>
<ref local = addressObj> // => local search in current Object
</property>
</bean>
ref bean attribute searches for the dependent bean in the current configuration
file if it is not available in current configuration file, then it search parent
configuration file.
Ex –
<bean id = “studentObje” class = “Student”>
<property name = “address”>
<ref bean = “addressObj”/>
</property>
</bean>
Is equal to
Note:
In <constructor-arg> re attribute is there but is not local attribute.
<constructor-agr ref = “addressObj”>
Or
<contructor-arg>
<ref bean = “addressObj”/>
</constructor-arg>
SetTypeBasedInjectionExample
|------src
| |-------com.nareshit.bean
| | |--------College.java
| | |--------Student.java
| |-------com.nareshit.client
| |--------Test.java
|------myBean.xml
//Student.java
package com.narshit.bean;
public class Student{
private int sid;
private String name;
public String toString(){
return “Student id : ”+sid+”\n”+”Name : ”+name;
}
public int hashCode(){
return sid;
}
public Boolean equals(Object obj){
if(obj instanceof Student){
Student std = (Student)obj;
return this.sid = std.sid && this.name = equals(std.name);
}
else{
return false
}
}
//required getter and setter methods
}
//College.java
package com.nareshit.bean;
import java.util.Set;
public class College{
private String collegeName;
private Set<Student> setOfStudents;
//myBean.xml
<beans>
<bean id = “studentObj1” class = “com.nareshit.bean.Student”>
<property name = “sid” value = “1001”/>
<property name = “name” value = “raj”/>
</bean>
<bean id = “studentObj2” class = “com.nareshit.bean.Student”>
<property name = “sid” value = “1002”/>
<property name = “name” value = “tomar”/>
</bean>
<bean id = “studentObj3” class = “com.nareshit.bean.Student”>
<property name = “sid” value = “1003”/>
<property name = “name” value = “raja”/>
</bean>
<bean id = “collegeObj” class = “com.nareshit.bean.College”>
<constructor-arg value = “NIT”>
</constructor-arg>
<property name = “setOfStudents”>
<set>
<ref bean = “studentObj1”/>
<ref bean = “studentObj2”/>
<ref bean = “studentObj3”/>
</set>
</property>
</bean>
</beans>
equals() Method:
If you want to compare two objects of a class with the state, we can override
equals() method in your user-defined class.
(***) Contract between equals() & hashCode() Methods:
Note:
Generally whenever we are working with the HashTable Data Stucture (Set,
HashMap, HashTable) to avoid the duplicate objects (by comparing that objects with
state) we are overriding equals() and hashCode() methods.
Note:
“==” operator compares the two objects with the references only, but equals()
method compare the two objects based on Implementation Logic.
Map is used to define a group of objects as a key and value pairs in Map each key
and value as one entry.
Map is act as root Interface. it is not a child interface of Collection.
Ex –
<map>
<entry key = “key1” value = “1”/>
<entry key = “key2” value ref =”studentobj1”/>
<entry key = “key3”>
<bean id = “studenobj2” class = “Student”>
<property name = “rollno” value = “1001”/>
<property name = “name” value = “rama”/>
</bean>
</entry>
…………….
…………….
</map>
Application Structure
MapTypeBasedInjectionExample1
|------src
| |-------com.nareshit.bean
| | |--------Question.java
| |
| |-------com.nareshit.client
| |--------Test.java
|------myBean.xml
|------log4j.properties
//Question.java
Import java.util.Map;
public class Question{
private int questioned;
private String question;
private Map<String, String> answers;
//Test.java
import java.
//log4j.properties
#log4j property file to write output on log
#file and show on console as well
Log4j.appender.file =
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File = E:\\logginFile.org
log4j.appender.file.MaxFileSize = 1MB
log4j.appender.file.MaxBackupIndex = 1
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversioinPattern = %d{yyyy-MM-dd HH:mm:ss} % -
5p %c{1}:%L - %m%n
log4j.appender.stdout =
org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout =
org.apache.log4j.PatterLayout
log4j.appender.stdout.layour.ConversionPatter = % {yyyy-MM-dd HH:mm:ss} %-
5p %c {1}: %L - %m%n
Log4j:
1. Appender:
This is class which does the actual logging (printing statements). It can
be console appender, File appender, JDBC appender and so on…
2. Layout:
This is nothing but how the log message is formatted. This format is
very similar to C Languages printf() function.
Ex – “Hello I am training java tools”
3. ConversionPattern
It is similar to C language format specifiers.
Application Structure
MapTypeBasedInjectionExample2
|------src
| |-------com.nareshit.bean
| | |--------Question.java
| | |--------Answer.java
| | |--------User.java
| |-------com.nareshit.client
| |--------Test.java
|------myBean.xml
|------log4j.properties
//Question.java
//Answer.java
import java.util.*;
public class Answer{
private int answered;
private String answer;
private Date postedDate;
//User.java
//Test.java
If any java class method is having the capability of for constructing and
returning its own object reference that method is called factory method.
There are two types of factory methods in java-
Note:
If any java class contains private constructor then it is not possible to create
an object by using new operator and constructor from Out Side of the class.
static factory method is very useful to create an Object for private constructor
classes from Out Side of the class.
In some situations in spring it is not possible to create the object for spring bean
class by using new operator and constructor. In this case to create bean object by
using static factory methods.
Note:
We can make the spring container to create the spring bean class object either
by using static factory method or by using instance factory method or by using
regular constructor.
With static factory methods to create spring bean class object we can use
<factory-method> attribute along with <bean> configuration.
Ex –
The factory method attribute indicates to container to create bean object by using
static factory method.
To specify the argument values of a factory method use <constructor–arg> tag.
In this case <constructor-arg> is not constructor injection.
The instance factory method is used to create an object by using an existing object
and its data.
Ex –
FactoryMethodExample1
|------src
| |-------com.nareshit.bean
| | |--------Employee.java
| | |--------Test.java
|
|------myBean.xml
//Employee.java
public class Employee{
public Employee(){
System.out.println(“Employee cons”);
}
public Eployee getEmployee(){
System.out.println(“Factory Method of Employee”);
return new Employee();
}
}
//myBeans.xml
<beans>
<bean id = “emp1” class = “com.nareshit.beans.Employee”/>
<bean id = “emp2” factory-bean = “emp1” factory-method = “getEmployee”/>
</beans>
//Test.java
public class Test{
public static void main(String[] args){
BeanFactory factory = new XmlBeanFactory(new ClassPathResource
(“myBeans.xml”));
Employee emp1 = (Employee)factory.getBean(“emp1”);
System.out.println(emp1.hashCode());
Employee emp2 = (Employee)factory.getBean(“emp2”);
System.out.println(emp2.hashCode());
}
}
Note:
java.uti.Properties Object is used to maintain the group of String objects as a
key and value pairs.
Ex –
<props>
<prop key = “username”>system</prop>
<prop key = “password”>manager</prop>
</props>
PropertiesTypeBasedInjectionExample1
|
|-----src
| |-------default package
| |-------DatabaseConnection.java
| |-------Test.java
|---muBean.xml
//DatabaseConnection
public class DatabseConnection{
private Properties dbProperties;
// required setter and getter methods
}
//myBean.xml
<beans>
<bean id = “databaseConnction” class = “DtabaseConnection”>
<property name = “dbProperties”>
<props>
<prop key = “driverClassName”>oracle.jdbc.driver.OracleDriver</prop>
<prop key = “url”>jdbc:oracle:thin:@localhost:1521:XE</prop>
<prop key = “username”>system</prop>
<prop key = “password”>manager</prop>
</props>
</property>
</bean>
</beans>
//Test.java
public class Test{
BeanFactory factory = new XmlBeanFactory (new
ClassPathResource(“myBean.xml”));
DatabaseConnection db =
(DatabaseConnection)factory.getBean(“dataBaseConnection”);
Properties p = db.getDbProerties();
Enumeration enum = p.keys();
while(enum.hasMoreElements()){
String key = (String)enum.nextElement();
String value = p.getProperty(key);
System.out.println(key+” : “+values);
}
}
BanFactory(I)
|
ApplicationContext(I):
|
|----------ClassPathXmlApplication(c)
|----------XmlWebApplicationContext(c) [used in web applications]
|----------FileSystemXmlApplicationContext(c)
Note:
BeanFactory container not supporting to read the data from .properties files.
ClassPathXmlApplicationContext(C):
ApplicationContext context =
new ClassPathXmlApplicationContext(“myBeans.xml”);
In the above code container reads the configuration file from the classpath. So
even if we change the location of the project in the system our application will
work without the modification, because it reads the configuration file from the
classpath not from the system path.
It is recommended to use ClassPathXmlApplicationContext container
(FileSystemXmlApplicationContext is not recommended).
FileSystemXmlApplicationContext:
After download extract that zip file and set the path environment variables for Maven
Software.
To set the path environment variables go for system variables we can set –
JAVA_HOME C:\ProgramFiles…….\jdk1.7.0
MAVEN_HOME E:\apache-maven
SpringMavenProject1
|
|------com.nareshit.bean
| |-----Employee.java
|------com.nareshit.client
| |-------Test.java
|-----src/test/java
[-] JRE System Library
[-] Maven Dependencies
|------src
| |----main
| | |-----resources
| | | |-----myBean.xml
| |-----test
|------target
|------pom.xml
//Employee.java
public class Employee{
Private int empno;
private String name;
// required setter and getter methods
}
//myBean.xml
<beans>
<bean id = “emp” class = “com.nareshit.bean.Employee”/
<property name = “empno” value = “1001”/>
<property name = “name” value = “rama”/>
//Test.java
public class Test{
public static void main(String[] args){
BeanFactory factory = new XmlBeanFactory
(new ClassPathResource (“myBeans.xml”));
Employee emp = (Employee)factory.getBean(“emp”);
System.out.println(“emp.getName());
}
}
//pom.xml
<modelVersion>4.0.0</modelVersion
<groupId>com.nareshit</groupId>
<artifactId>SpringMavenProject1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringMavenProject1</name>
<url>http:://maven.apache.org</url>.
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<!-- <dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
</project>
groupId
artifactId
version
Every project also has a <version> element, which indicates the current version
number.
This number usually refers to major releases (“Hibernate 3.2.4”, “Spring 3.0.1”
and so on).
modelVersion
Auto wiring is possible only on referenced type bean properties that means auto
wiring is not possible on simple type, collection framework type properties.
Auto wiring kills the readability of spring configuration file.
To perform auto wiring for a particular bean we can use any one of the following
values-
1. byName
2. byType
3. constructor
4. autodetect
In the case of auto wiring byName spring IOC container mainly checks for three
conditions. If all these are valid then it inject the values by setter aproach.
If dependency name is abc, then bean configuration should be abc and the setter
method name should be setAbc(Abc abc)
When it finds <autowire = “byname”> for any bean configuration, first spring
container check for dependency bean name in the dependent bean, then it will
check whether any bean is configured in the spring configuration file with the
same name.
If it finds then it will call corresponding setter method of dependent bean.
AutowiringByNameExample1
|-----src/main/java
| |-----com.nareshit.bean
| | |-----Employee.java
| |----com.nareshit.client
| | |-----Test.java
| |-----com.nareshit.dao
| | |-----EmployeeDao.java
| | |-----EmployeeDaoImpl.java
| |------com.nareshit.service
| | |-----EmployeeService.java
| |-----EmployeeServiceImpl.java
|------ []src/test/java
[] JRE System Library
[] Maven Dependencies
[] Referenced Libraries
|----src
| |----main
| | |-----resource
| | |-----com
| | |----nareshit
| | |----config
| | |-----myBeans.xml
| |---test
|-----target
[] pom.xml
//Employee.java
public class Employee{
private int empno;
private String name;
private double salary;
// required setter and getter method
}
//EmployeeService.java
public interface EmployeeService{
public Employee getEmployee(int empNo);
}
//EmployeeServiceImpl.java
//EmployeeDao.java
public interface Employee{
Employee searchEmployee(int empNo);
}
//EmployeeDaoImpl.java
public class EmployeeDaoImpl implements EmployeeDaoImpl{
private DataSource dataSource;
public void setDataSource(DataSource dataSource){
System.out.println(“Injection- happened in EmployeeDao by using
setDataSource(-)”);
this.dataSource = dataSource;
}
public Employee searchEmployee(int empNo){
Employee emp = null;
Connection connection = null;
try{
connection = dataSource.getConnection();
String sql = “select * form employee where empno = ?”;
PreparedStatement pst = connection.prepareStatement(sql);
pst.setInt(1,empNo);
ResultSet rs = pst.executeQuery();
if(rs.next()){
emp = new Employee();
emp = setEmpNo(rs.getInt(1));
emp = setName(rs.getString(2));
emp = setSalary(rs.getDouble(3));
}// end of if
}
catch(SQLExceptioin e){
e.printStackTrace();
}
finally{
try{
if(connection ==null){
connectin.close();
}
}
catch(SQLException se){
System.out.println(se);
}
}
return emp;
}
}
//myBean.xml
<beans>
<bean id = “employeeService”
class = “com.nareshit.service.EmployeeServiceImpl” autowire = “byName"/>
<bean id = “employeeDao”
class = “com.nareshit.dao.EmployeeDaoImpl” autowire = “byName"/>
<bean id = “dataSource”
class = “org.springframework.jdbc.darasource.DriverManagerDataSource”>
<property name = “driverClassName” value = “jdbc.oracle.driver.OracleDriver”/>
<property name = “url” value = “jdbc:oracle:thin:@localhot:1521:XE”/>
<property name = connectionProperties”>
<props>
<prop key = “user”>system</prop>
<prop key = “password”>manager</prop>
</props>
</bean>
</beans>
//Test.java
public class Test{
public static void main(String[] main){
ApplicationContext context = new ClassPathXmlApplicationContext
(“applicationContext.xml”);
EmployeeService empService =
(Employee)context.getBean(“employeeService”);
int eid = 2;
Employee emp = empService.getEmployee(eid);
System.out.println(“emp.getName()+” “+emp.getSalary());
}
}
In the case of auto wiring byType spring container mainly check for 3 conditions,
if all these are valid, then it inject the values by setter approach.
a) Dependency beanType
b) Configured beanType
c) Setter methodParameterType
When it finds <autowire = “byType> for any bean configuratioin, then first it
checks for dependency beanType in the dependent bean, then it will check any
bean is configured in the spring configuration file with the same Type. If it finds,
then it will call corresponding setter methods.
Note:
In this case container does not bother about the setter method name. It only
bothers the setter methods parameter types.
AutowiringByTypeExample1
|-----src/main/java
| |-----com.nareshit.client
| | |-------App.java
| |-----com.nareshit.controller
| | |-----EmployeeController.java
| |------com.nareshit.service
| | |------EmployeeService.java
|------src/test/java
[] JRE System Library
[] Maven Dependencies
[] Referenced Libraries
|----src
| |----main
| | |-----resource
| | |-----com
| | |----nareshit
| | |----config
| | |-----myBeans.xml
| |---test
|-----target
[] pom.xml
//EmployeeController.java
public EmployeeController{
private EmployeeService emplyeeService1;
public void setEmployeeService2(EmployeeService employeeService1){
System.out.println(“Injection happened in EmployeeController by
using setEmployeeService”);
this.employeeService1 = employeeService1;
}
public void employeeControllerMethod(){
System.out.println(“Employee Controller Method”);
employeeService1.employeeServiceMethod();
}
}
//EmployeeService.java
public EmployeeSerice{
private EmployeeDao employeeDao1;
public void setEmployeeDao3(EmployeeDao employeeDao1){
System.out.println(“Injection happened in EmployeeService by using
setEmployeeDao3”);
this.employeeDao1 = employeeDao1;
}
public void empServiceMethod(){
System.out.println(“Employee Service Method”);
employeeDao1.empDaoMethod();
}
}
//EmployeeDao
public class EmployeeDao{
public void empDaoMethod(){
System.out.println(“Employee Dao Method”);
}
}
//myBean.xml
<beans>
<bean id = “employeeController”
class = “com.nareshit.controller.EmployeeController” auwire = “byType”/>
<bean id = “employeeService”
class = “com.nareshit.service.EmployeeService” autowire = “byType”/>
<bean id = “employeeDao”
class = “com.nareshit.dao.EmployeeDao” autowire = “byType”/>
</beans>
//Test.java
public class App{
public static void main(String[] args){
String configFile = “com/nareshit/config/myBeans.xml”;
ApplicationContext context = new ClassPathXmlApplicationContext
(configFile);
EmployeeController empController = (Employee)context.getBean
(“employeeController”);
empController.employeeControllerMethod();
}
}
3. Auto wiring Constructor:
In the case of auto wiring with constructor spring IOC container mainly check
for 3 conditions, if all these are valid then it inject the values by constructor
approach.
o Dependency type
o Configure bean type
o Constructor parameter type
When it finds <autowire = “constructor> for any bean configuration then it first
check for dependency bean type in the dependent bean then it will check the
spring configuration file whether any bean is configured with the dependency
type.
If it finds it will check for constructor, which will take dependency type as a
parameter, then after it will call corresponding constructor.
//EmployeeController.java
public class EmployeeController{
private employeeService employeeService1;
public EmployeeController(EmployeeService empService2){
employeeService1 = employeeService2;
}
}
//EmployeeService.java
public class EmployeeService{
private employeeDao employeeDao1;
public EmployeeService(EmployeeDao empDao2){
employeeDao1 = employeeDao2;
}
}
//EmployeeDao.java
public class EmployeeDao{
}
//myBeans.xml
<beans>
<bean id = “employeeController”
class = “com.nareshit.controller.EmployeeController” autowire = “constructor”/>
<bean id = “employeeService”
class = “com.nareshit.service.EmployeeService” autowire = “constructor”/>
<bean id = “employeeDao” class =”com.nareshit.dao.EmployeeDao”/>
</beans>
<beans>
<bean id = “employeeController”
class = “com.nareshit.controller.EmployeeController” autowire = “autodetect”/>
<bean id = “employeeService”
class = “com.nareshit.service.EmployeeService” autowire = “autodetect”/>
<beans>
Global default-autowiring:
Instead of defining autowiring attribute for every bean configuration we can set
a default-autowire attribute in the <beans> root element to force the all the beans
declared within the <bean> root element to apply this rule.
However this root default mode will be overridden by a bean tag own mode if it
is specified.
<beans default-aotowire = “byType”>
<bean id = “employeeController”
class = “com.nareshit.controller.EmployeeController”/>
<bean id = “employeeService”
class = “com.nareshit.service.EmployeeService” autowire = “constructor”/>
<bean id = “employeeDao”
class = “com.nareshit.dao.EmployeeService” autowire = “no”/>
<beans>
Note:
The autowire attribute will allow following 5 values –
1. no no autowiring
2. byName
3. byType
4. constructor
4. autodetect
Dependency Checking:
It is used to verify all the dependency of a bean that are configured via injection
are injected or not.
To implement dependency checking to a spring bean we make use of
“dependency-check” attribute of <bean> tag.
This attribute take any of the following four values-
o None
o Simple
o All
o Object
None:
It won’t check whether the dependency injected or not.
Simple:
It checks all simple type (primitive type, wrapper type) dependencies injected
or not.
Object:
It checks all the object type dependencies injected or not.
All:
It checks both simple and object type dependencies injected or not.
If we are using dependency checking by mistake if we forget to set any value any
simple or object type, then container raise an exception like –
“UnSatisfiedDependencyException”.
Note:
By default the dependency check value is none.
DependencyCheckingExample
|----src
|-----default
|------Address.java
|------Student.java
|------Test.java
//Address.java
public class Address{
private String city;
//required setter and getters
}
//Student.java
public class Student{
private int studentId;
private String name;
private Address address;
//required setters and getters
}
//myBean.xml
<xsd
Xsi:schemaLocation = “http://www.springframework.org/schema/beans/spring-
beans-2.5 xsd>
<beans>
<bean id = “student” class = “Student” dependency-check = “all”
autowire =”byType>
<property name = “name” value = “Rama”>
</property>
</bean>
<bean id = “address class = “Address”>
<property name = “city” value = “hyd”/>
<bean>
</beans>
//Test.java
public class Test{
public static void main(String[] args){
BeanFactory f = new XmlBF (new CPR(“myBeans.xml”));
Student s = (Student)f.getBean(“student”);
System.out.println(s.getName()+”:”+s.getStudentId());
}
}
If we are executing the above application we will get the following exception –
“org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name ‘student’ defined in class path resource [myBeans.xml]:
Unsatisfied dependency expressed through bean property ‘studentId’: Set this
property value or disable dependency checking for this bean.
Note:
Ex –
<beans default-dependency-check = “all”
xmlns=http://www.springframework.org/schema/beans
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:context=http://www.springframework.org/schema/context
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd”>
@Autowired Annotation:
package org.springframework.bean.factory.annotation;
@Retention (RetentionPolicy.RUNTIME)
@Target ({ElementType.CONSTRUCTOR, ElementType.FIELD,
ElementType.METHOD})
public @interface Autowired{
boolean required() default true;
}
SpringAnnotationAutowiredExample
|------src
| |-----com.nareshit.client
| | |----Test.java
| |-------com.nareshit.dao
| | |------EmployeeDAO.java
| |-------com.nareshit.service
| |-------EmployeeeSeervice.java
|------myBeans.xml
//EmployeeSerivice.java
//myBean.xml
<beans xmlns=http://www.springframework.org/schema/beans
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:context=http://www.springframework.org/schema/context
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd”>
<context:annotation-config/>
<bean id = “employeeService” class = “com.nareshit.EmployeeService”>
</bean>
<bean id = “employeeDao” class = “com.nareshit.EmployeeDAO”>
</bean>
</beans>
//Test.java
public class Test{
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext
(“myBeans.xml”);
EmployeeService eservice = (EmployeeService)context.getBean
(“employeeService”);
System.out.println(eservice);
}
}
Note:
Dependency Checking:
@Qualifier Annotation:
//EmployeeService.java
public class EmployeeService{
private EmployeeDAO employeeDao;
@Autowired
@Qualifier (“employeeDao2”)
public void setEmployeeDao (EmployeeDAO employeeDao){
this.employeeDao = employeeDao;
}
public String toString(){
return “This is Employee Service : Hello “+employeeDao;
}
}
The java class that allows to creates only one object for JVM underlying
container or run time environment creates only one object for class then only the
class is called singleton.
If the class allows to create multiple objects, then that class is not called singleton
java class.
When a programmer try to create multiple objects for a class, if the java class
allows to create only one object, then that class is called as Singleton.
src
|------com.nareshit
|------Car.java
|------Main.java
//Car.java
class Car{
private static Car car = new Car();
private Car(){
}
public static Car getCar(){
return car;
}
}
//Main.java
class Main{
public static void main(String[] args){
Car c1 = car.getCar();
Car c2 = car.getCar();
Car c3 = car.getCar();
Here getCar()
System.out.println(c1.hashCode()); method allows
System.out.println(c2.hashCode()); return the existed
System.out.println(c3.hashCode()); Car object reference
}
}
Spring Singleton:
The process of creating only one object for container is called spring singleton.
We can make the spring container to create the spring bean class object in one
of the five following scopes-
1. Singleton it is a default value of scope attribute.
2. Prototype
3. Request
4. Session
5. Global session
1. Singleton:
Spring container creates only one object for spring bean but it never makes
spring bean as singleton java class i.e. when scope attribute is singleton the spring
container creates and returns one object for spring bean class for multiple
factory.getBean() method call. The default value of scope attribute is singleton.
SpringSingletonScopeExample
|------src
|-------com.nareshit.bean
|-----Employee.java
|-------com.nareshit.client
|------Test.java
|-------com.nareshit.config
|-------myBeans.xml
//Employee.java
class Employee{
private int empNo;
private String empName;
private double salary;
// required setter and getter
}
//myBeans.xml
<beans>
<bean id = “emp” class = “com.nareshit.bean.Employee”
scope = “singleton”/>
</beans>
//Test.java
public class Test{
public static void main(String[] args){
ApplicationContext context =
new ClassPathXmlApplicationContext(“myBeans.xml”);
Employee emp1 = (Employee)context.getBean(“emp”);
emp1.setEmpNo(111);
emp1.setEmpName(“Rama”);
emp1.setSalary(3000);
System.out.println(“emp1: ”+emp1);
Employee emp2 = (Employee)context.getBean(“emp”);
System.out.println(“emp2: “+emp2);
}
}
Ex –
<bean id = “emp1” class = “com.nareshit.bean.Employee” scope = “singleton”/>
<bean id = “emp2” class = “com.nareshit.bean.Employee” scope = “singleton”/>
Here two instance will created for Employee class, here bean (scope = “singleton”)
never make the spring bean class as a singleton java class.
Note:
Singleton beans in spring and singleton design pattern both are different.
1. Scope = Prototype:
If the Spring bean scope = prototype spring container creates and returns
multiple objects for spring bean class for multiple factory.getBean() method call.
Ex- in spring configuration file
<bean id = “emp1” class = “com.nareshit.bean.Employee” scope = “prototyoe”/>
In client Application
Employee emp1 = (Employee)context.getBean(“emp1”);
emp1.setEmpNo(102);
emp1.setEmpName(“rama”);
emp1.setSalary(3000);
Employee emp2 = (Employee)context.getBean(“emp2”);
System.out.println(emp1); //102 rama 3000
System.out.println(emp2); // 0 null 0
Spring IOC container manages the life cycle of a bean i.e. instantiation to
destruction
Spring bean object has 4 life cycle state.
1. Instantiation
2. Initialization
3. Ready to use
4. Destruction
Spring framework provides a support of the bean to listen for its life cycle events
performed by the IOC container.
In many real world components have to perform certain type of initialization
tasks before they are ready to use such task as opening a file, opening a network
or database connection, allocating memory and so on and also they have to
perform the corresponding destruction tasks at the end of their life cycle. So we
have to need to customize Bean initialization and destruction in the spring IOC
container to listen the life cycle events and also to perform above tasks.
In addition to the bean registration the managing the life cycle of the Beans and
it allows you to perform custom tasks at a particular point of their life cycle.
Your tasks should be encapsulated in callback method for the IOC container to
call any suitable time.
The spring IOC container manages a life cycle of a bean and also it will take the
following responsibility-
SpringBeanLifeCycle
|------src
|------default package
| |------Cashier.java
| |-------Product.java
| |-------ShoppingCart.java
| |-------Test.java
|-------log4j
|-------myBeans.xml
//Product.java
public class Product{
int pid;
String name;
double price;
//required setter and getter
}
//ShoppingCart.java
public class ShoppingCart{
List<Product> items;
//required setter and getter
}
//Cashier.java
public class Cashier implements initializingBean, DisposableBean{
private static Logger logger = Logger.getLogger(Cashier.class);
private String name;
private String path;
private PrintWriter writer;
//myBeans.xml
<beans>
<bean id = “cashier1” class = “Cashier”>
<property name = “name” value = “cashier”/>
<property name = “path” value = “E:logFile”/>
</bean>
</beans>
//Test.java
public class Test{
public static void main(String[] args){
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(“myBeans.xml”);
Cashier cashier = (Cashier)context.getBean(“cashier1”);
Product p1 = new Product();
p1.setPid(1001);
p1.setName(“mouse”);
p1.setPrice(3000);
Product p2 = new Product();
p2.setPid(1002);
p2.setName(“Keyboard”);
p2.setPrice(4000);
List list = new ArrayList();
list.add(p1);
list.add(p2);
ShoppinCart cart = new ShoppingCart();
cart.setItem(list);
cashier.checkOut(cart);
context.destroy();
}
}
Note:
Whenever we are implementing InitializinBean and DisposableBean
interface, our bean class not a POJO. So a better approach of specifying the
initialization and destruction callback method and destroy() attribute in bean
declaration.
<bean id = “cashier” class = “Cashier” init-method= “openFile”
destroy-method = “closeFile”>
<property name = “name” value = “cashier1”/>
<property name = “path” value = “E:logFile”/>
</bean>
Note:
Both BeanFactory and ApplicationContext container support the life cycle
methods, but we can’t stop the BeanFactory container explicitly to destroy the
singleton beans at the end of the client application. We can call
factory.destroySingletons(), if the container is BeanFactory.
Ex-
//Test.java
class Test{
public static void main(String[] args){
XmlBeanFactory factory = new XmlBeanFactory
(new ClassPathresource(“myBeans.xml”);
……………
……………
Factory.destroySingletons();
}
}
Interface Injection:
BeanNameAware Interface:
BeanFactoryAware interface:
ApplicationContextAware Interface:
Note:
While implementing the interface injection our spring bean is not a POJO.
InterfaceInjection
|------default package
|-----MyBean.java
|------Test.java
|------myBeans.xml
//MyBean.java
public class MyBean implements BeanNameAware{
private ApplicatonContext context;
private String BeanName;
public void setApplicationContext(ApplicationContext context)
throws BeansException{
this.context = context;
}
public void setBeanName(String name){
this.beanName = name;
}
public void getDetails(){
System.out.println(“The current BeanName is :”+beanName);
System.out.println(“is Singleton Bean :”+
context.isSingleton(beanName));
System.out.println(“is prototypeBean :”+
context.isPrototype(beanName);
System.out.println(“Current no of bean are managed by container :”+
context.getBeanDefinationCount());
System.out.println(“Other Bean managed by container : “+
Context.getBean(date1);
}
}
//myBean.xml
<beans>
<bean id = “myBean” class = “MyBean”/>
<bean id = “date1” class = “java.util.Date”/>
<bean id = “date2” class = “java.util.Date”/>
</beans>
//Test.java
public class Test{
public static void main(String[] args){
ApplicationContext context = new ClassXmlApplicationContext
(“myBeans.xml”);
MyBean myBean = (MyBean)context.getBean(“myBean”);
myBean.getDetails();
}
}
BeanPostProcessor:
It is an interface present in org.springframework.beans.factory.config package.
The interface contains the following two method –
BeanPostProcessor is used to provide some common logic to all the beans or set
of beans which are configured in the spring configuration file.
The BeanPostProcessor allows additional bean processing before and after
initialization call back method.
The main characteristic of a BeanPostProcessor is that it will process all the bean
instances in IOC container one by one not just a single bean instance.
postProcessBeforeInitialization() method is executed just before the call back
initialization method call.
postProcessAfterInitialization() method is executed just after the call back
initialization method call.
Note:
These methods are called for each spring bean which are configured in spring
configuration file.
SpringBeanLifeCycleWithBeanPostProcessorObject
|------src
|------(default package)
|-------Cashier.java
|-------PathCheckingBeanPostProcessor.java
|-------Product.java Same as SpringBean life cycle
|-------ShoppingCart.java Same as SpringBean life cycle
|-------StorageConfig.java
|-------Test.java Same as SpringBean life cycle
|------log4j.properties
//PathCheckingBeanPostProcessor.java
//StorageConfig.java
public interface StorageConfig{
String getPath();
}
//Cashier.java
public class Cashier implements StorageConfig{
private static Logger logger = Logger.getLogger(Cashier.class);
private String name;
private String path;
private PrintWriter writer;
//configuration File
<beans XSD….>
<context: annotation-config/>
<bean class = “PathCheckingBeanPostProcessor”/>
<bean id = “cashier1” class = “Cashier”>
<property name = “name” value = “cashier1”/>
<property name = “path” value = “G://CashierData”/>
</bean>
</beans>
During the above Cashier Bean instantiation the following operations are
performed by spring IOC containser-
Pre-Initialization of Spring
managed pojo
Destoryed
Spring IOC container creates an instance of the spring bean by using java
Reflection-API.
If any properties are mentioned, if the setter injection is configured, then
container will call setXXX() methods.
If the bean class implements BeanNameAware interface, then container calls
setBeanName() method.
If the bean class implements the ApplicationContextAware interface, then
container calls setApplicationContext() method.
If the bean class implements the BeanFactoryAware interface, then container
calls setBeanFactory() method.
If any beanPostProcessors are associated with the container, then container will
call postProcessBeforeInitialization() method.
If the bean class implements the InitializingBean interface OR any custom init()
method is declared OR any method is annotated with @PostConstruct annotation,
then container calls that callback initialization methods.
If any bean postPorcessors are associated with the container, then container calls
postProcessAfterInitialization() method.
The bean is initialized and ready to be used.
If the bean class implements Disposable interface OR any custom destroy method
is declared OR any method is annotated with @PreDestroy annotation, then
container calls callback destruction methods.
Inner Bean:
//FishBean.java
public class FishBean{
public FishBean(){
System.out.println(“FishBean constructor”);
}
public void fishBeanMethod(){
System.out.println(“Fish Bean Method”);
}
}
//WaterBean.java
public class WaterBean{
private FishBean fishBean;
public void setFishBean(FishBean fishBean){
this.fishBean = fishBean;
}
public WaterBean(){
System.out.println(“WaterBean Constructor”);
}
public void waterBeanMethod(){
System.out.println(“WaterBean Method”);
fishBean.fishBeanMethod();
}
}
//myBeans.xml
<beans>
<bean id = “wb” class = “WaterBean”>
<property name = “fishBean”>
<bean class = “FishBean”/>
</property>
</bean>
</beans>
//Test.java
public class Test{
public static void main(String[] args(){
String configfile = “myBeans.xml”;
ApplicationContext context =
new ClassPathXmlApplicationContext(configfile);
WaterBean w = (WaterBean)context.getBean(“wb”);
w.waterBeanMethod();
}
}
2. By passing all the spring bean configuration files as a String array to the
constructor of the container.
Ex –
ApplicationContext context = “new classPathXmlApplicationContext
(new String[]{“beans1.xml”,”beans2.xml”,”beans3.xml”});
MultiConfigExample
|-------src
|------com.nareshit.client
|------Test.java
|------com.nareshtit.controller
|------Controller.java
|------com.nareshit.dao
|-------DAO.java
|------com.nareshit.service
|-------Service.java
|------com.nareshit.xml
|------controllerBeans.xml
|------daoBeans.xml
|------serviceBeans.xml
//Controller.java
public class Controller{
private Service service;
// required setter and getter
public void controllerMethod(){
service.serviceMethod();
System.out.println(“Controller Method”);
}
}
//Service.java
public class Service{
private DAO dao;
//required setter and getter
public void serviceMethod(){
dao.daoMethod();
System.out.println(“Service Method”);
}
}
//DAO.java
public class DAO{
public void daoMethod(){
System.out.println(“DAO Method”);
}
}
//controllerBeans.xml
<beans>
<import resource = “serviceBeans.xml”/>
<bean id = “controllerObj” class = “com.nareshit.controller.Controller”>
<property name = “service” ref = “serviceObj”/>
</bean>
</beans>
//serviceBeans.xml
<beans>
<import resource = “daoBeans.xml”/>
<bean id = “serviceObj” class = “com.nareshit.service.Service”>
<property name = “dao” ref = “daoObj”/>
</bean>
</beans>
//daoBeans.xml
<beans>
<bean id = “doaObj” class = “com.nareshit.doa.DAO”>
</bean>
</beans>
//Test.java
public class Test{
public static void main(String[] args){
String configfile = “com/nareshit/xml/controllerBeans.xml”;
ApplicationContext context =
new ClassPathXmlApplicationContext(configfile);
Controller c = (Controller)context.getBean(“controllerObj”);
c.controllerMethod();
}
}
Id attribute is used to hold the object name, name attribute is used to hold the
alias names.
By using name attribute is possible to provide more than one name,
While getting the bean object from container, we can id attribute name or name
attribute name.
Ex-
<bean id = “std”, name = “std1, std2, std3” class = “Student”>
In Client App
Student s = (Student)container.getBean(“std”);
OR
Student s1 = (Student)container.getBean(“std1”);
Note:
The text file that maintain the entries in the form of key-value pairs is called
as text properties file.
Ex-
Myfile.properties
#properties file(comment)
name = 3sha
age = 30
mobile = 9878243567
“Here name and are keys and 3sha and 30 are values”.
In JDBC applications we use properties file to pass JDBC driver details and database
details to get the flexibility on modifications.
Note:
Spring application can’t directly communicate with the properties file, it is
done by using XML file.
${<key name>}
Note:
BeanFactory containser can’t work with .properties file.
ApplicationContext container can work with .properties file.
ExternalPropertiesFileExample
|-------src
|------com.nareshit.client
|----Test.java
|------com.nareshit.jdbc
|------DatabaseConnectionDetails.java
|------db.properties
|------db1.properties
|------myBeans.xml
//DatabaseConectionDetails.java
public class DatabaseConectionDetails{
private String userName;
private String url, password, driverClass;
//required setter and getter
}
//db.properties
#Oracle databaseConnectionDetails
user = system
password = manager
url = jdbc:oracle:thin:@localhot:1521:XE
driverClass = oracle.jdbc.driver.OracleDriver
//db1.proerties
user = 3sha
password = 9tra
//myBeans.xml
<beans>
<bean class =
“org.springframework.beans.factory.config.PropertyPlaceholderconfigurer”>
<property name = “Locations”>
<list>
<value>db.properties</value>
<value>db1.properties</value>
</list>
</property>
</bean>
<bean id = “dbConnection” class = “con.nareshit.DatabaseConnectionDetails”>
<property name = “username” value = “${user}”/>
<property name = “password” value = “${password}”/>
<property name = “url” value = “${url}”/>
<propert name = “driverClass” value = “${driverClass}”/>
</bean>
</beans>
//Test.java
public class Test{
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicatonContext
(“myBeans.xml”);
DatabaseConnectoinDetails dbConnection =
(DatabaseConnectionDetais)context.getBean(“dbConnection”);
System.out.println(“UserName:”+dbConnection.getUserName());
System.out.println(“Password:”+dbConnection.getPassword());
System.out.println(“DriverClass:”+dbConnection.getDriverClass());
System.out.println(“URL:”+dbConnection.getUrl());
}
}
Spring Annotations:
Normally we can declare all the bean or components in XML bean configuration
file, so that spring container can detect and register your beans or components.
But actually, Spring container able to auto scan, detect and instantiate your beans
from project package.
To enable the spring auto component scanning feature annotate the classes with
@Component annotation.
This annotation indicate to the container this class is an auto scan component.
Ex-
import org.springframework.beans.stereotype.Components;
@Component
public class EmployeeService{
}
Custom auto scan component name by default, Spring Container will create with
“EmployeeService” to “employeeService” i.e. lower case of the first character of
the component (with the same Component Name).
We can retrieve this component name with “employeeService” -
Note:
In Spring 2.5 there are 4 types of auto components scan annotation types.
@Component – indicates an auto scan component.
@Repository – indicates DAO component in the persistence layer.
@Service – indicates a Service component in the business/service layer.
@Controller – indicates a controller component in the presentation layer.
Note:
@Repository, @Service and @Controller annotations are annotated with
@Component. To increase the readability of the program we should always declare
@Repository, @Service and @@controller for a specified layer.
Note:
To auto-scan to components in the configuration file we can use the following
tag –
<context:component-scan base-package = “com.nareshit”/>
|-----default value is default package
SpringAnnotationExmple
|------src
|-------com.nareshit.client
| |--------Test.java
|-------com.nareshit.dao
| |-------EmployeeDAO.java
|-------com.nareshit.service
| |--------EmployeeService.java
|-------myBeans.xml
//EmployeeService.java
package com.nareshit.service
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.nareshit.dao.EmployeeDAO;
@Service(“eservice”)
public class EmployeeService{
@Autowired
@Qualifier(“edao”)
Private EmployeeDAO employeeDao;
public String toString(){
return “this is Employee Service: “+employeeDao;
}
}
//EmployeeDAO.java
package com.nareshit.dao;
import org.springframework.stereotype.Repository;
@Repository(“edao”)
public class EmployeeDAO{
public String toString(){
return “EmployeeDAO”;
}
}
//myBeans.xml
<beans>
<context:component-scan base-package = “com.nareshit”/>
//Test.java
public class Test{
public static void main(Stringp[] args){
ApplicationContext context =
new ClassPathXmlApplicationContext(“myBeans.xml”);
EmployeeSerivce eservice =
(EmployeeeService)context.getBean(“eservice”);
System.out.println(eservice);
}
}