ObjectDemo1.java
SPRING SUDHEER
ObjectClient.java
Parent.xml
Child.xml
SPRING SUDHEER Output:
Dependencies in the form of Collections
While creating a Spring bean (Pojo) , the bean class can use any one of the following four types of collections as a dependency.
1. Set - <set>
2. List - <list>
3. Map - <map>
4. Properties - <props>
Except the above four types of collections, if the Spring bean class uses any other type of collection as a dependency then the Spring container does not inject that collection object to the Spring bean. In this case spring programmer is responsible for injecting the collection object manually.
Set Collection
If a Spring bean has a property of collection type set then in the Spring configuration file we need to use <set> element to inform the Sprig IoC.
In Spring configuration file we can use <value> and <ref> tags as a sub elements of <set>
tab.
While configuring <set> element in the xml file it does not allow duplicate values.
Because set collection is unique collection.
In Spring Framework if one bean class is collaborating with another bean class then Spring IoC container first creates collaborator bean object and after that dependent bean object
Merging
The merging of collection is allowed in the Spring 2.0.
A parent-style <set/> element can have child-style <set/> element which inherit and overrides the values from the parent collection.
For collection merging you need to specify merge=true attribute on the <set/> element of child bean definition.
Project Structure
DemoSet.java
SPRING SUDHEER
Set.xml
Output
In Client application when we can call factory.getBean(“child) then internally Spring Framework executes the following code.
If a Spring bean is depending on a collection of type List then in Spring configuration file, we need to configure <list> element.
We can use <value> and <ref> tags as sub elements of List
The differences between Set and List Collections are
Set List
Set is an unordered collection List is an ordered collection Set does not allow dublicate values List allows dublicate values Set does not allow index based accessing List allows index base accessing Set does not support list iterator List support list iterator
Merging
SPRING SUDHEER
Example
1. Project Structure
2. DemoList.java
3. DemoListClient.java
4. List.xml
SPRING SUDHEER
Output:
What is the difference between an inner class and a nested class?
A non-static inner class is called inner class and a static inner class is called nested class.
public class A class A {
{ static class B class B {
{
} } } }
What is Map.Entry in java?
Map.Entry is a class . Here map is an interface and Entry is a static class of Map Interface. A Map stores data in the form of key/value pairs and we call each pair as one
entry. In the statement Map.Entry the meaning is we can create static classes inside an interface. We call those classes as nested classes.
public interface Map
If a Map Collection contains 3 key/value pairs then internally it means 3 objects of Map.Entry class.
Map Collection
In a Spring bean if we take collection type as Map then in the Spring configuration file we should configure the <map> element.
In Spring configuration file we need to use the sub element of map as <entry>.
In a map collection one entry represents key/value pair.
We use sub element of entry as either <value> or <ref> element.
Merging
The merging of collection is allowed in the Spring 2.0.
A parent-style <map/> element can have child-style <map/> element which inherit and overrides the values from the parent collection.
For collection merging you need to specify merge=true attribute on the <map/>
element of child bean definition.
Example
1. Project Structure
SPRING SUDHEER
2. DemoMap.java
3. DemoClient.java
4. Map.xml
SPRING SUDHEER
OUT PUT
Properties Collection
Properties collection also stores data in the form key/value pairs. But both key/value are considered as Strings.
If we take Properties collection in the Spring bean then in the Spring configuration file, we need to use <props> element.
The sub element of <props> is <prop> and the <prop> element does not any have subelements.
Merging
The merging of collection is allowed in the Spring 2.0.
A parent-style <props/> element can have child-style <props/> element which inherit and overrides the values from the parent collection.
For collection merging you need to specify merge=true attribute on the <props/>
element of child bean definition.
Example:
1. Project Structure
2. DemoProps.java
SPRING SUDHEER PropsClient.java
3. Props.xml
Output:
Constructor Injection
The constructor Injection method of dependency injection is the method of injecting the dependencies of an object through its constructor arguments. In this mechanism the dependencies are pushed into the object through the constructor argument at the time of instantiating.
Constructor Injection is a Dependency Injection variant where an object gets all its dependencies via the constructor. This is PicoContainer's most important feature.
The most important benefits of Constructor Injection are:
It makes a strong dependency contract
It makes testing easy, since dependencies can be passed in as Mock Objects
It's very succinct in terms of lines of code
Classes that rely on Constructor Injection are generally Good Citizens
A dependency may be made immutable by making the dependency reference final
In the case when the object is instantiated by using some factory method then passing the dependencies as arguments to the factory method is also considered as constructor injection since the dependencies are injected at the time of constructing the object.
The following code snippet shows the sample class that allows the injection of its dependencies as constructor arguments.
The <constructor-arg> element
The bean definition can describe to use a constructor with zero or more arguments to instantiate the bean
The <constructor-arg> element describes one argument of the constructor, which means that to specify a constructor with multiple arguments we need to use <constructor-arg>
SPRING SUDHEER
Index This attribute takes the exact index in the constructor argument list.
This is used to avoid ambiguities like in case of two arguments being of the same type Type This argument takes the type of this constructor argument
Value A short-cut alternatives to a child elment ‘value’
Ref As short-cut alternative to a child element ref bean
Example
Project Structure
ConstructorDemo.java
ConstructorClient.java
SPRING SUDHEER
OUT PUT
In the client application when we call beanF.getBean(“con”) then internally Spring Framework executes the following statements.
ConstructorDemo cd = new ConstructorDemo (“Sachin”, 34);
Circular Dependency Injection
If A and B are two classes/beans and if A depends on B and B depends on A then we will get Circular Dependency.
When circular dependency is occurred then we cannot solve this problem with the help of Constructor Injection.
In this case, instead of constructor injection we need to use setter injection.
For Example
In a client application, when we call factory.getBean(“a”) then Spring IoC
container is trying to create class A object but ‘A’ need ‘B’ object so the container tries to create B class object. But ‘B’ also need ‘A’ Object , So A & B objects are not
SPRING SUDHEER
1. A.java
2. B.java
3. CircularDemo.java
Cic.xml
In the client application, when we call factory.getBean(“a”) internally the following steps
SPRING SUDHEER iv. Finally, class A object is given back to the client application.
Setter Injection Constructor Injection
Wiring a bean means configuring a bean along with its dependencies into an xml file.
By default autowiring is disabled. It means the programmer has to explicitly wire the bean properties into an xml file.
If autowiring is enabled then Spring Framework will take care about injecting the dependencies and programmer is no need to configure into an xml file explicitly.
Bean autowiring is only supported if the dependencies are in the form of objects.
To enable autowiring we should add autowire attribute to the <bean> element.
The different autowire values are
In this case Spring Framework attempts to find out a bean in the configuration file whose id is matching with property name to be wired.
If a bean found with the id as property name then that class object will be injected into that property by calling setter injection.
If no id is found then that property remains unwired.
byType
In this case the Spring Framework attempts to find out a class in the xml file whose name is matching with the property type to be wired or not.
If found then injects that class object by using setter Injection.
If no class found in xml with the same name then that property remains unwired.
If a class is found in xml for more than once then Spring Framework throws UnSatisfiedDependencyException.
SPRING SUDHEER
Constructor
This autowire type is equal to byType. But here constructor injection will be executed.
Example: Previous Example modify with constructor Autodirect
This type of autowiring first work likes a constructor and if not then it works like byType.
Validating the Dependencies
In Spring Framework either in explicit wiring or in auto wiring if all properties are not configured in xml but still Spring container create an object of the bean class.
By default Spring container does not verify whether all properties are set in xml or not.
If we enable the dependency validation then Spring container verifies whether all dependencies are set or not. If not the container does not create an object and throws an Exception.
To enable dependency validation we need to add dependency-check attribute for the
<bean>.
The different values of dependency-check attribute are i. no (by default)
ii. Simple iii. Object iv. All Simple
In this case Spring container verifies for primitives and collections are set or not. If not set then exception will be thrown.
Objects
In this case the Spring Container verifies whether objects are set or not. If not the container throws an Exception
All
In this case the container verifies for objects, primitives and collections.
Example
SPRING SUDHEER
TestBean.java
ValidateClient.java
Validate.xml
Output
Bean Initialization and Destruction
While creating our bean class in Spring apart from injections, we can also create methods for performing initialization and cleanup code required for the bean class.
SPRING SUDHEER ii. destroy()
Code Snippet
In the above bean class when a client request is given for getting the bean object then internally the following steps are executed.
a. Object is created b. Properties are injected.
c. afterPropertiesSet() called
d. Now object is given to Client application.
Before container is removing the object then container first calls the destroy() and then removes that object from the memory.
In the above code snippet the drawback is our class is not a POJO class. Because it is implementing from predefined interfaces given by the framework.
So we can rewrite the above bean class by adding our own methods for initialization and cleanup;
In this case the bean into xml we have to add init-method and destroy-method attributes for <bean> element.
In this case container will do the following before giving the object to client.
a. Object is created b. Properties are injected c. Inint() called
d. Now object is given to client.
When Container is going to to remove the object first it calls tearsDown() method and after that Object is removed.
Example
Project Structure:
LifeBean.java
SPRING SUDHEER
Init.xml
Bean Scopes in Spring Framework
You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration instead of having to 'bake in' the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext).
Scope Definition
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created
off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of a HTTP Session.
Only valid in the context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
The Singleton Scope
When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
SPRING SUDHEER
The Prototype Scope
The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made (that is, it is injected into another bean or it is requested via a programmatic getBean() method call on the container). As a rule of thumb, you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.
Bean Instantiation
Spring Framework instantiates or gets a Spring bean object by using the following three ways.
i. By Calling Constructor.
ii. By Calling Static Factory method iii. By Calling an instance factory method.
By Calling Constructor
When we call getBean(“id1”) method from the client application then the Spring IoC container uses ‘new’ operator and calls constructor of the class and gets an object of the bean class.
After getting the bean object, it will apply injections and after that other initializations and then returns that bean object to the client application.
If we change the bean scope to prototype then the IoC container gets|created new object for each call to the getBean(“id1”) method.
By Calling static factory method
By default Spring IoC container makes each bean as singleton. But when the scope of a bean is changed to prototype then the bean object becomes non-singleton.
If a Spring programmer doesn’t want to make a Spring bean as prototype bean then the programmer has to explicitly make the bean class as singleton.
To make a bean class as Singleton the following rules are need to be followed.
a. Create a Private static object to the class, inside the class.
b. Create a private constructor
c. Create a public static factory method.
Code Snippet
While configuring the above bean class into Spring configuration file, we need to inform the Spring IoC container that calls static factory method of the bean class to get an
SPRING SUDHEER
When getBean(“sb”) method is called from the client application then the IoC container will get the bean object by using the following statement internally.
SampleBean sb = new SampleBean();
How to create Synchrozed Singleton class in java?
If we add Synchronized keyword for the static factory method then the class becomes synchronized singleton class.
By Calling Instance factory method
In this approach Spring IoC container class the factory method defined in one class to get an object of another bean class.
In Java we have two types of factory methods 1. Static factory method
2. Instance factory method
A factory method may or may not return same class object. But a factory method must return an object.
In the below xml, for the bean “tb1” we have removed class attribute and we have added factory-bean attribute.
In a Client application when we call factory.getBean
. (“id1”) internally the following statements are executed by the container.
TestBean1 tb1 = new TestBean1();
TestBean1 tb = tb1.getInstance ();
ean Life Cycle
1. Does not Exist 2. Instantiation 3. Initialization 4. Service 5. Destroy
Doesn’t Exist Factory.getBean(“id”) Instantiation
1. Inject Dependenc 2. Calls aftPropSet
SPRING SUDHEER
Spring JDBC Introduction:
JDBC technology is required either directly or indirectly for getting a connection with the database.
Without using JDBC technologies we cannot able connect with databases using Java.
If a programmer is directly working with JDBC technology then there are some problems facing by the Java Programmer.
a. JDBC technology exceptions are checked exceptions. There we must put try and catch blocks in the code at various places and it increases the complexity of the applications.
b. In a Java Program, repetitive code is required to perform operations on databases from the various client applications. The repetitive code is like loading the drivers, connection opening, creating a statement and finally closing the objects of JDBC. This kind of repetitive code, we call as Boilerplate Code.
c. In JDBC, if we open the connection with database then we are responsible to close it.
If the connection is not closed then later at some point of time, we may get out of connections problem.
d. JDBC throws error codes of the database when an exception is occurred sometimes the error codes are unknown of the Java Programmer and error codes are different from one database to another database. Therefore developing JDBC applications using those error codes will make our application as database dependent.
Spring JDBC frame work has provided an abstraction layer on top of the existing JDBC technology.
Spring JDBC layer concentrates on avoiding connection management coding and error management and Spring JDBC programmer will concentrate on construction and execution of the SQL operations.
Spring framework has provided an exception translator and it translates the checked exceptions obtained while using JDBC into unchecked exceptions of Spring type and finally the unchecked exceptions are thrown to the Java Programmer.
While working with Spring JDBC, the programmer no need to open and close the database connection and it will taken care by the Spring framework.
Table 1.1
The following table describes which actions is developer’s responsibility and which actions are taking care by Spring itself:
6 Loop setup for result iteration(if required) Y
7 Defining work for each iteration Y
8 exception handling Y
9 Handling transactions Y
10 Connection, statement & resultset closing Y
The package hierarchy
The Spring Framework's JDBC abstraction framework consists of four different packages,
The Spring Framework's JDBC abstraction framework consists of four different packages,