Spring Notes
Spring Notes
Spring environment starts by loading spring configuration xml file into ResourceInterface object, we
Resource is an interface and ClassPathResource is an implemented class given by spring, both are given
in org.springframework.core.io. *
Syntax
Resource res = new ClassPathResource(Our Config xml file name);
Actually this configuration file contains all bean configurations about our application [ some thing
like struts.xml in struts 2 ]
Next step is to bring spring IOC container into our program, it will be created by reading configuration xml
through Resource object. Spring IOC container is calledBeanFactory and this container is responsible for
creating the bean objects and forinjecting its dependencies through out our applications.
BeanFactory is the interface and XmlBeanFactory is an implementation class of it, BeanFactory given
in org.springframework.beans.factory. * and XmlBeanFactory is given
in org.springframework.beans.factory.xml.* pack
you can get required object from spring container by calling getBean() method, while calling this method
we need to pass the bean id as a parameter like..getBean(bean id), and this method always returns Object class
object and we need to type caste this into our bean type.
Syntax
Object
FirstBean fb = (FirstBean)ob;
ob
factory.getBean(id1);
Remember, by default every spring bean is the singleton class. Spring IOC container makes a spring
bean as singleton automatically
While constructing spring beans, if one spring bean is depends on another spring bean class for
performing some logic, this process of dependency is called object dependency
spring configuration xml, we have 2 ways to inform to the spring container about this object dependency
Actually with inner beans we have some disadvantages and its not the way to use in the real time projects so am
not going to explain about it.
Syntax will be
Actually we used to write either local or parent or bean, means as i told you earlier, we can write any number of
spring configuration xmls for the spring application. Our collaborator bean may be in same xml or other xml so
spring has given these 3 options, we will see one by one.
If we use the local attribute in the <ref /> element then the spring IOC container will verify for the collaborator
bean with in same container [ i mean in same xml ]
In general we try to configure all spring beans into a single spring configuration xml only.
not mandatory we can create multiple configure files too right.
But its
<beans>
<bean id="id1">
<property name="sb" class="DemoBean">
<ref local="id2" />
</property>
</bean>
<bean id="id2" class="SampleBean">
</beans>
i have specified ref tag with local attribute and given that required class id, why local? because that required
(collaborator) class also i have configured in the samexml file [ line number 9 ], so spring container will check only
in this xml only
But we can also configure the collaborator class in other xml like
<beans>
<bean id="id1">
<property name="sb" class="DemoBean">
<ref parent="id2" />
</property>
</bean>
</beans>
hile creating spring bean (pojo class), the bean class can use any of the following4 types of collections as
dependency, along with some primitives and objects like previous sessions..
Set
List
Map
Properties
In spring config xml, we can use <value /> and <ref /> tags as sub elements of <set> tag
While configuring <set> in xml file it doesnt allow duplicate values, because Set collection is a unique
collection
In spring framework if one bean is collaborating[depends on] with other bean class then spring ioc
container first creates collaborator bean object after only dependentbean object
<beans>
<bean id="id1" class="SampleBean">
<property name="studentsData">
<set>
<value>sun</value>
<value>Oracle</value>
<value>java4s</value>
<ref bean="id2">
</set>
</property>
</bean>
<bean id="id2" class="TestBean"/>
</beans>
Set doesnt allows duplicate right.., but List will allows duplicate values too
Set cannot put values in order, but List will keep the added values in the same order
<beans>
<bean id="id1" class="SampleBean">
<property name="studentsData">
<list>
<value>sun</value>
<value>Oracle</value>
<value>java4s</value>
<value>sun</value>
<ref bean="id2">
</list>
</property>
</bean>
Map is the interface, Entry is the static class in Map interface, so we can callMap.Entry just remember
<map>
<entry key="k1">
<value>Oracle</value>
</entry>
<entry key="k2">
<value>Sun</value>
</entry>
<entry key="k3">
<value>Java4s</value>
</entry>
<entry key="k4" value-ref="id2" />
</map>
In spring bean class, if both constructor and setter injection applied for same property then constructor injection
will be overridden by setter injection, because constructor injection will happen at the object creation time, and
setter after objection right, so setter will overrides
</bean>
if argument types are different, then at the time of configuring of xml file we can use type attribute
Constructor Injection
1. In constructor injection, partial
injection of dependencies cannot
possible, because for calling
constructor we must pass all the
arguments right, if not so we may
get error
2. But, constructor injection cannot
overrides the setter injected values
iring a bean means configuring a bean along with its dependencies into an xml file like previous concepts,
byName
byType
Constructor
autoDetect
none
n this case, spring framework attempts to find out a bean in the configuration file, whose id is matching with
the property name to be wired. If a bean found with id as property name then that class object will
be injected into that property by calling setterinjection. If no id is found then that property remains un-wired, but
never throws anyexception.
<beans>
<bean id="id1" class="MyBean" autowire="byName" />
<bean id="db" class="DemoBean" />
</beans>
our class depends on DemoBean class object right, now see in the xml file line number 2 we have given
autowire=byName, means when ever spring container notice autowire=byName then it will verifies whether the
id in xml file is matching with the property name in the MyBean or not, if yes it will wired automatically
else unwired
<beans>
<bean id="id1" class="java4s.Categories" autowire="byType">
<property name="name" value="General Books" />
</bean>
<bean id="SomeThing" class="java4s.Book">
<property name="bookname" value="The Kids" />
<property name="bookprice" value="300" />
</bean>
</beans>
We called id1 from ClientLogic.java [line number 15], and in spconfig.xml we have written autowire=byType, so
first spring container will checks for the bean with class attribute Book [as autowire=byType and we have written
private Book bk inCategories.java ] and then inserts Book class properties into Book class object [ jav4s.Book ]
and gives this book class object to Categories then injects value General Books into name property of Categories
class.
<beans>
<bean id="id1" class="java4s.Categories" autowire="constructor">
<property name="name" value="General Books" />
</bean>
<bean id="SomeThing" class="java4s.Book">
<property name="bookname" value="The Kids" />
<property name="bookprice" value="300" />
</bean>
</beans>
ctually Spring Autowiring by constructor is similar to spring autowiring byType [ internally it will considers as
byType only ] but with little difference, in byType we used setter injection here we have to
use constructor injection
et us see the example on spring Autowiring with autowire as autodetect. Actually spring autowire=autodetect
frist will works as Spring Autowiring constructor if not then works as Spring Autowiring byType, byType means
setter injection right hope youremember
<beans>
<bean id="id1" class="java4s.Categories" autowire="autodetect">
<property name="name" value="General Books" />
</bean>
<bean id="SomeThing" class="java4s.Book">
<property name="bookname" value="The Kids" />
<property name="bookprice" value="300" />
</bean>
</beans>
Spring JDBC
Normal JDBC technology
regardless
of
type
will
be
involved
of framework/technology.
Without
getting
usingJDBC we
cannot
aconnection with
able
to
database,
connect
with
JDBC technology exceptions are checked, so we must use try, catch blocks in the code at various places
which increases the complexity of the application. And that to this may cause to have lot of repetitive code to
perform the database operations [some thing like we may need to write loading driver, connection, creating
statement lot of times ]
In JDBC if we open the connection with database, we only responsible to close that connection. If not we
may get some connection issues
If you see JDBC, it will throws error codes of the database, when ever an exception israised. In fact all
java programmers may or may not know these code right ?, that to these error codes are different from one
database to other database, so finally our application is gonna be database dependent
In
order
to overcome the
above
problems
by
using
JDBC
directly,
Spring
framework
has
provided
one abstraction layer on top of existing JDBC technology. We used to call this layer as Spring-JDBC. In this layer
spring programmers will work with this abstraction layer and that layer will internally uses JDBC technology
So spring-JDBC layer will take cares about connection management and error managements, and programmers will
concentrate on their logics bla bla.
Even spring framework has provided an exception translator and it translates thechecked exceptions obtained using
JDBC to un-checked exceptions of spring type and finally the un-checked exceptions are thrown to java
programmer, while working with spring-JDBC, the programmer no need to open and close the database connection
and it will be taken care by the spring framework.
A java application can get connection with database using following 2 ways
Spring framework uses DataSource interface to obtain the connection with database internally, i mean we
will use any one of the following 2 implementation classes ofDataSource interface.
Org.springframework.jdbc.datasource.DriverManagerDataSource [ class ]
Org.apache.commons.dbcp.BasicDataSource [ class ]
The above 2 classes are suitable when our spring application is at developing stage, in real time programmers
uses connection pooling service provided by the applicationserver, hope you know this fact
Leave
it,
In
above
classes DriverManagerDataSource is
given
by spring framework
and
it
is
equal
to DriverManager class, it means spring framework internally opens a new connection and closes the connection for
each
operation
done
on
the
database.BasicDataSource is
given
the apache,
and
this
is
better
<bean id=id1
class=org.springframework.datasource.DriverManagerDataSource>
[ or ]
<bean id=id1 class= org.apache.commons.dbcp.BasicDataSource>
<property name=driverClassName value= />
<property name=url value= />
<property name=username value= />
<property name=password value= />
</bean
JdbcTemplate Class In Spring-JDBC
JdbcTemplate class is given in org.springframework.jdbc.core.* package and this class will provides
methods for executing the SQL commands on a database
JdbcTemplate class follows template design pattern, where a template class acceptsinput from the user
and produces output to the user by hiding the interval details [Confused.?? If so forget about this point
JdbcTemplate class provided the following 3 type of methods to execute SQL operations on the database
execute()
update()
query() methods.
are
on
the
database,
andquery method
is
JdbcTemplate class
depends
with DataSource.
So
we
on DataSource object
must
give
only, as
it
will
opens
database
toJdbcTemplate,
connection
actually
internally
we
have
both setter, constructor injections in JdbcTemplate class for inserting DataSource object.
Spring config file if we insert DriverManagerDataSource object into JdbcTemplate class with
constructor injection
<bean id=id1
class=org.springframework.datasource.DriverManagerDataSource>
<property
<property
<property
<property
</bean>
<bean id="id2" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="id1" />
<bean>
Spring config file if we insert DriverManagerDataSource object into JdbcTemplate class with setter
injection
<bean id=id1
class=org.springframework.datasource.DriverManagerDataSource>
<property
<property
<property
<property
</bean>
<bean id="id2" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="id1" />
<bean>
etter if we know some thing about execute(static sql command only) method in spring JdbcTemplate class
This method is used to execute both DDL [ select ] and DML[ non-select ] operations on the database
execute() method allows only static sql commands as parameter, i mean sql command should not
contain ? [ question marks, like preparedstatements
And this method is suitable to perform DDL[ select ] operations on the database, because for DML[ nonselect ] operations this method doesnt return the count value to the programmer, else we can use this method for
any DML/DDL operations. Let me clear this..
Example
jt.execute(insert into table_name values(100,java4s));
jt = object of JdbcTemplate
See this, execute() method will executes the command and it wont returns any valueback, i mean how many
rows inserted/deleted bla bla, as execute() method return type is void. But in case of update() method this will
returns the int value
et us see few pints regarding update() method of JdbcTemplate class in spring framework
Syntax
int update( static sql command );
int update( dynamic sql command , object array);
Example
int k = jt.update( insert into table_name values(100,java4s) );
values[]
new
Integer(100),java4s
};
So what we understood ? if we do any operations with update() method of JdbcTemplateclass on the database it
will returns integer value as count like how many rows got effected in the database.
queryForInt()
queryForLong()
queryForObject()
queryForList()
and 1 or 2 more but these are highly using methods, if you want i will give you the total query methods list..
dont fear nothing is there light..
queryForInt()
Syntax:
int k = queryForInt( static sql command ) ;
&
int k = queryForInt( dynamic sql command , Object array);
We used to execute inserting rows, deleting rows bla bla as its return type is integer
queryForLong()
Syntax:
long k = queryForLong( static sql command ) ;
&
long k = queryForLong( dynamic sql command , Object array);
We used to find sum of salaries of the employees bla bla., as its return type if long
queryForObject()
Return type of queryForObject() method is object of Object class, we used to type cast later
Ex:
Object
Object
o1
o2
queryForObject(
=
queryForObject(
select
select
sysdate
from
salary
dual
from
,
emp,
Date.class)
Integer.class);
Integer
=
=
(Date)o1;
(Integer)o2;
String s = (String)o3;
see above 3 examples, i mean this queryForObject() will return the object of the type we called in the
form of Object class object [ read this point slowly if its not clear
We used to find sum of salaries of the employees bla bla., as its return type if long
queryForList()
Syntax:
List l = jt.queryForList( static sql command ) ;
&
So we are clear about all fundamentals for spring JDBC let us start the applications
et us see how to load the values into spring configuration file dynamically usingResourceBundle concept
Instead of directly placing the values into xml we can load the values at run time for the
dataSource properties using ResourceBundle
If we want to get the dataSource properties at runtime from ResourceBundle, while configuring the bean
into xml we should put bundle keys with expression language into the xml file like
<bean id="id1"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${jdbc.driver}</value>
</property>
</bean>
In ResourceBundle
jdbc.driver = sun.jdbc.odbc.JdbcOdbcDriver
In spring we have pre-defined class given, called PropertyPlaceholderConfigure and this class will read the
data from the bundle and it will write the values into the configuration file
PropertyPlaceholderConfigure given in
org.springframework.beans.factory.config.* package
Notes:
At line number 5, there spring container will read the properties file from bundle.
At line number 6, spring container will write the properties into XML file
et us see how to use Resourcebundle in spring jdbc [ Dynamically load the values forproperty placeholders in