0% found this document useful (0 votes)
100 views16 pages

Spring Notes

The document discusses various aspects of configuring and using dependency injection in Spring, including: 1. Spring loads configuration files to initialize the application context and create bean definitions. It supports dependency injection through constructor, setter, and autowiring. 2. Autowiring allows Spring to automatically wire bean dependencies if they are defined by type or name. Common collection types like List, Set, and Map can also be injected. 3. The <ref> tag is used to reference collaborator beans, and attributes like local, parent, and bean specify where the referenced bean is defined. Constructor injection makes objects immutable while setter injection allows partial dependencies.

Uploaded by

kewal259
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views16 pages

Spring Notes

The document discusses various aspects of configuring and using dependency injection in Spring, including: 1. Spring loads configuration files to initialize the application context and create bean definitions. It supports dependency injection through constructor, setter, and autowiring. 2. Autowiring allows Spring to automatically wire bean dependencies if they are defined by type or name. Common collection types like List, Set, and Map can also be injected. 3. The <ref> tag is used to reference collaborator beans, and attributes like local, parent, and bean specify where the referenced bean is defined. Constructor injection makes objects immutable while setter injection allows partial dependencies.

Uploaded by

kewal259
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

1.

Spring environment starts by loading spring configuration xml file into ResourceInterface object, we

call this loading process as bootstrapping (technically) of spring framework..

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

BeanFactory factory = new XmlBeanFactory(res);


// given above Resource object

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

By using inner beans

Using <ref /> element

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.

Using <ref /> element

Syntax will be

<ref local/parent/bean=id of collaborator bean>

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.

<ref local=id value />

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

<ref parent=id value />

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

Spring supports these 4 collections only as the dependencies.


Except above 4 types of collections, if the spring bean class uses any other type of collection as dependency, then
spring container doesnt inject that collection object to the spring bean, in this case spring programmer
is responsible for injection that collection object manually.

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

Create List object like, List l= new ArrayList()

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>

Let us come to the concept, Map.Entry will gives one entry

Map is the interface, Entry is the static class in Map interface, so we can callMap.Entry just remember

<bean id="id2" class="TestBean"/>


</beans>

this concept as of now

Actually In this spring we always use Map.Entry class object only

<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 id="id1" class="DemoBean">


<constructor-arg value="Welcome to java4s" />
<property name="message" value="Welcome to spring" />

</bean>
if argument types are different, then at the time of configuring of xml file we can use type attribute

<bean id="id1" class="DemoBean">


<constructor-arg type="java.lang.string" value="1000" />
<constructor-arg value="10" />
</bean>
if we have 2 properties of same type, like user name and password

<bean id="id1" class="DemoBean">


<constructor-arg value="myuserName" index="0" />
<constructor-arg value="mypassword" index="1" />
</bean>
how to work with dependency in the form of objects in this constructor injection

<bean id="id1" class="DemoBean">


<constructor-arg ref="sb" />
</bean>
<bean id="sb" class="SampleBean" />
Setter Injection
1. In Setter Injection, partial injection of
dependencies can possible, means if we have
3 dependencies like int, string, long, then its
not necessary to inject all values if we use
setter injection. If you are not inject it will takes
default values for those primitives
2. Setter Injection will overrides the constructor
injection value, provided if we write setter and
constructor injection for the same property [i
already told regarding this, hope you
remember ]
3. If we have more dependencies for example
15 to 20 are there in our bean class then, in
this case setter injection is not recommended
as we need to write almost 20 setters right,
bean length will increase.
4. Setter injection makes bean class object as
mutable [We can change ]

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

3. In this case, Constructor injection


is highly recommended, as we can
inject all the dependencies with in 3
to 4 lines [i mean, by calling one
constructor]
4. Constructor injection makes bean
class object as immutable [We
cannot change ]

iring a bean means configuring a bean along with its dependencies into an xml file like previous concepts,

by default autowiring is disabled in spring framework.

It means the programmer has to explicitly wire

the bean properties into an xml file.


If autowiring is enabled then spring container will take care about injecting the dependencies, programmer no need
to configure into an xml file explicitly. Autowiring is only supported if the dependancies are in the form of objects
only, to enable autowiring, we should add autowire attribute to the bean element [or] bean tag, autowire has the
following values

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

nothing more than that.

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

either directly or indirectly for

of framework/technology.

Without

getting

usingJDBC we

the databases using java only.


But there are some problems if a java programmer is a directly work with JDBC

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

By using java.sql.DriverManager [ Class ]

By using javax.sql.DataSource [ Interface ]

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

than DriverManagerDataSourcebecause BasicDataSource having inbuilt connection pooling implementation.


In spring config we need to configure the following 4 properties to obtain connection with database

<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.

Note: execute and update methods


for select operations on the database.

are

for non-select operations

on

the

database,

andquery method

is

JdbcTemplate class

depends

with DataSource.

So

we

on DataSource object
must

give

only, as

it

will

this DataSource object

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

name=driverClassName value= />


name=url value= />
name=username value= />
name=password value= />

</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

name=driverClassName value= />


name=url value= />
name=username value= />
name=password value= />

</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

update() method in spring JdbcTemplate class is suitable for DML [ non-select i


meaninsert, update, delete.. ] operation on the database

update() method accepts either static or dynamic sql commands as parameter

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) );

int k = jt.update( insert into table_name values(?,?) , values);


Object

values[]

jt = object of JdbcTemplate class

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.

et us see the query methods of spring JdbcTemplate

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()

Return type of queryForInt() method is int

Syntax:
int k = queryForInt( static sql command ) ;
&
int k = queryForInt( dynamic sql command , Object array);

See we can pass either static,dynamic sql commands

We used to execute inserting rows, deleting rows bla bla as its return type is integer

queryForLong()

Return type of queryForLong() method is long

Syntax:
long k = queryForLong( static sql command ) ;
&
long k = queryForLong( dynamic sql command , Object array);

See we can pass either static,dynamic sql commands

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);

Object o3 = queryForObject( select empName from emp,String.class);


Date

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()

Return type of queryForList() method is List object

Syntax:
List l = jt.queryForList( static sql command ) ;
&

List l = jt.queryForList( dynamic sql command , Object array);

See we can pass either static,dynamic sql commands

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

Resource res = new ClassPathResource("spconfig.xml");


XmlBeanFactory factory = new XmlBeanFactory(res);
PropertyPlaceholderConfigur ppc = new PropertyPlaceholderConfigurer();
ppc.setLocation(new ClassPathResource(MyPropertiesFile.properties));
ppc.postProcessBeanFactory(factory);

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

spring configuration XML ]

You might also like