0% found this document useful (0 votes)
8 views15 pages

Spring Cocenpts

The document provides an extensive overview of the Spring Framework, covering concepts such as dependency injection, loose and tight coupling, and various injection methods including setter and constructor injection. It also discusses autowiring, Spring JDBC, JdbcTemplate, and the execution flow of Spring MVC. Additionally, it addresses handling multiple configuration files, constructor overloading, and different types of bean scopes in Spring.

Uploaded by

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

Spring Cocenpts

The document provides an extensive overview of the Spring Framework, covering concepts such as dependency injection, loose and tight coupling, and various injection methods including setter and constructor injection. It also discusses autowiring, Spring JDBC, JdbcTemplate, and the execution flow of Spring MVC. Additionally, it addresses handling multiple configuration files, constructor overloading, and different types of bean scopes in Spring.

Uploaded by

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

JAVA4S :

========

Q : What Is Spring Framework ?


ANS:-Spring is a light weight and open source framework created by Rod Johnson in
2003.
Spring is a complete and a modular framework, i mean spring framework can be
used for all layer implementations for a real time application. spring we
can develop all layers
Spring framework is simple because as it is non-invasive, POJO and POJI model

SPRING 1:-non-invasive:
means it doesn�t force a programmer to extend or implement their class from any
predefined class or interface given by Spring API,.

Q: Loose Coupling ?
ans:-
Loose Coupling-

ex:
Interface Vehicle
{
void move();
}

class Car implements Vehicle


{
public void move()
{
// logic
}
}

class Bike implements Vehicle


{
public void move()
{
// logic
}
}

class Traveler
{
Vehicle v;
public void setV(Vehicle v)
{
this.v = v;
}

void startJourney()
{
v.move();
}
}

spring container will inject either Car object or Bike object into the Traveler by
calling setter method, So if Car object is replaced with Bike then no changes are
required in Traveler class, this means there is loose coupling between Traveler and
Vehicle object.
Tight coupling EX:
------------------

class Traveler
{
Car c=new Car();
void startJourney()
{
c.move();
}
}

class Car
{
void move()
{
// logic...
}

In the above example, Traveler object is depends on car object. So traveler class
creating an object of Car class inside it [ line number 3 ]
If the other class object is created in the dependent class [ like Car class object
in Traveler class ], there exist tight coupling, i mean if method in car object is
changed then we need to do the changes in the Traveler class too so its the tight
coupling between Traveler and Car class objects

--------------

Q : what is Dependency injection ?


ans:-For injecting the required things to the current spring class (spring bean) ,

1-Setter injection [<property /> ]


2-Construction injection [<constructor �arg />]
3-Interface injection

Note 1:-to perform setter or constructor injection by reading the information from
an external file called spring configuration file

Note 2:-In case of setter injection, the class must contain a setter method to get
dependencies other wise spring container doesn�t inject the dependencies to
dependent object

Note 3:-Actually this configuration file contains all bean configurations about our
application
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 called
BeanFactory and this container is responsible for creating the bean objects and for
injecting it�s 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

Note 4:-Remember, by default every spring bean is the singleton class.


Note 5:-in spring we can write multiple configuration xmls,
Note 6:
<ref local="someBeanId"> should be used when you have a duplicate id in your
parent-child config files and you want to distinguish between the two in either
config file.

<ref parent="someBeanId"> should be used in the child config file to reference the
parent id.

<ref bean="someBeanId"> should be used when you do not have a duplicate id in your
parent-child config files.

Note 7 :-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,

1-Setter injection
Setter Injection, Dependency In The Form Of Collections-
Set
List
Map
Properties

=>[Setter Injection With Primitive Values]


Note :- it use property tag.

<bean id="id1" class="java4s.WelcomeBean">


<property name="message" value="Welcome to spring" />
</bean>

=>[Spring Dependency In The Form Of Objects] objects with <ref />

1-><ref local=�id value� />:-


IOC container will verify for the collaborator bean with in same container [ i mean
in same xml ].
ex:-<beans>

<bean id="id1">
<property name="sb" class="DemoBean"> // parent object
<ref local="id2" /> // ref obj in parent and local mean search in same xml
</property>
</bean>

2-><ref parent=�id value� />:-


it will checks at local xml file,if not then parent if its not available at local.
<bean id="id1">
<property name="sb" class="DemoBean">
<ref parent="id2" />
</property>
</bean>

public class Travel implements Journey


{
Private Vehicle v;
public void setV(Vehicle v)
{
this.v = v;
}

public void startJorunty()


{
System.out.println("Journey been started....");
v.move();
}
}

<bean id="id3" class="java4s.Travel">

<property name="v">
<ref parent="id2" /> // understand again and do practicle
</property>

</bean>

=>[With Map Collection Property]

<bean id="id1" class="java4s.WelcomeBean">

<property name="data" >


<map>
<entry key="k1">
<value>10</value>
</entry>
<entry key="k2">
<value>java4s</value>
</entry>
<entry key="k3">
<value>10.55</value>
</entry>
</map>
</property>

</bean>

=>[Injection With List Collection Property]

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


<property name="studentsData">
<list>
<value>sun</value>
<value>Oracle</value>
<value>java4s</value>
<value>sun</value>

</list>
</property>
</bean>

=>[Injection With Set Collection Property]

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


<property name="studentsData">
<set>
<value>sun</value>
<value>Oracle</value>
<value>java4s</value>

</set>
</property>
</bean>

2-Construction injection [<constructor �arg />]


-----------------------------------------------

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


<constructor-arg value="Welcome to java4s" />
</bean>
or
<bean id="id1" class="DemoBean">
<constructor-arg value="myuserName" index="0" />
<constructor-arg value="mypassword" index="1" />
</bean>
or
<bean id="id1" class="DemoBean">
<constructor-arg ref="sb" />
</bean>
<bean id="sb" class="SampleBean" />

Difference between Setter Injection and Constructor Injection


=============================================================

Setter Injection:
-----------------
1-> 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,
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.

Constructor Injection:
----------------------

1-> 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-If we have more dependencies for example 15 to 20 are there in our bean class
then, 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]

AUTOWIRING :- [programmer no need to configure into an xml file


explicitly]
==============
->Wiring a bean means configuring a bean along with its dependencies into an xml
file
-> 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,
EX:- MyClass obj
then MyClass is type and obj is the name of property.

Note:-
1) The default mode in traditional XML based configuration is no.
2) The default mode in java based @Autowired is byType.

autowire has the following values


1 no:- its default type of autowiring
2 byName :-If a bean found with id same as property name then that class object
will be injected into that property by calling setter injection.
3 byType :- confusion
4 constructor :-constructor is similar to spring autowiring byType [ internally it
will considers as byType only ,difference, in byType we used setter injection here
we have to use constructor injection]
4 autoDetect :-Actually spring autowire=�autodetect� frist will works as Spring
Autowiring constructor if not then works as Spring Autowiring byType, byType means
setter injection

Spring JDBC Complete Introduction


==================================
Note:-
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 of
DataSource interface.

Org.springframework.jdbc.datasource.DriverManagerDataSource [ class ]
Org.apache.commons.dbcp.BasicDataSource [ class ]

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,

JdbcTemplate class provided the following 3 type of methods to execute SQL


operations on the database

execute()
update()
query()
Note: execute and update methods are for non-select operations on the database, and
query method is for select operations on the database.

JdbcTemplate class depends on DataSource object only, as it will opens database


connection internally with DataSource. So we must give this DataSource object to
JdbcTemplate,
using constructor:

<bean id=�id1� class=�org.springframework.datasource.DriverManagerDataSource�>


<property name=�driverClassName� value=�� />
<property name=�url� value=�� />
<property name=�username� value=�� />
<property name=�password� value=�� />

</bean>

<bean id="id2" class="org.springframework.jdbc.core.JdbcTemplate">

<constructor-arg ref="id1" />

<bean>

using setter method:


<bean id=�id1� class=�org.springframework.datasource.DriverManagerDataSource�>

<property name=�driverClassName� value=�� />


<property name=�url� value=�� />
<property name=�username� value=�� />
<property name=�password� value=�� />

</bean>

<bean id="id2" class="org.springframework.jdbc.core.JdbcTemplate">

<property name="dataSource" ref="id1" />

<bean>

Method Of Spring JdbcTemplate Class:


------------------------------------
1 execute(sql) :-execute(�static sql command only�)
-----------------------------------------------------
This method is used to execute both DDL [ select ] and DML[ non-select
] operations on the database,
And this method is suitable to perform DDL[ select ] operations on the
database, because for DML[ non-select ] operations this method doesn�t return
the count value to the programmer, else we can use this method for any
DML/DDL operations.
execute() method allows only static sql commands as parameter, i mean
sql command should not contain ?

ex: jt.execute(�insert into table_name values(100,�java4s�)�);

2 update( dynamic sql ) :-


--------------------------
update() method in spring JdbcTemplate class is suitable for DML [ non-select i
mean insert, update, delete.. ] operation on the database
update() method accepts either static or dynamic sql commands as parameter
ex:int k = jt.update(� insert into table_name values(100,�java4s�) �);
int k = jt.update(� insert into table_name values(?,?) �, values);

Object values[] = { new Integer(100),�java4s� };


3 Query Methods :-
-----------------
queryForInt() :- int k = queryForInt(� static sql command �) ;
queryForLong() :- long k = queryForLong(� dynamic sql command �, Object
array);
queryForObject() :- Object o1 = queryForObject(� select sysdate from dual
�, Date.class) ;
queryForList() :- List l = jt.queryForList(� dynamic sql command �, Object
array);

Spring MVC 3.2 Execution Flow


=============================:

Step 1: First request will be received by DispatcherServlet


Step 2: DispatcherServlet will take the help of HandlerMapping and get to know the
Controller class name associated with the given request
Step 3: So request transfer to the Controller, and then controller will process the
request by executing appropriate methods and returns ModeAndView object (contains
Model data and View name) back to the DispatcherServlet
Step 4: Now DispatcherServlet send the model object to the ViewResolver to get the
actual view page
Step 5: Finally DispatcherServlet will pass the Model object to the View page to
display the result

Note : to activate annotation we add:-


<context:component-scan base-package="java4s" />

<mvc:annotation-driven />
<mvc:annotation-driven />
===========================================================================http://
www.java2novice.com=============================================================

Q How to handle or load multiple spring bean configuration files?


-----------------------------------------------------------------
ans:-to handle multiple spring bean configurations files, we can achieve this by
using <import> tag.

1 database-config.xml :-handles all jdbc configurations.


2 bean-config.xml :-which handles all beans with in the application,

3 applicationContext.xml :-configuration file imports the above two


configuration files,
ex:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<import resource="bean-config.xml" />


<import resource="database-config.xml" />
</beans>

Q:-Constructor overloading issue with spring constructor based injection ?


or
what if a class has two constructors with same number of input parameters with
differen types of arguments?
-----------------------------------------------------------------------------------
-------------------------------------------
ans:we must specify constructor input parameter type.
<constructor-arg type="java.lang.String">
<value>Java2novice article</value>
</constructor-arg>

<constructor-arg type="int">
<value>120</value>
</constructor-arg>

Q :-Differen types of spring bean scopes ?


------------------------------------------
ans:
scope' defines what kind of object has to created and returned. There are 5 types
of bean scopes available, they are:
1) singleton: Returns a single bean instance per Spring IoC container.

2) prototype: Returns a new bean instance each time when requested.

3) request: Returns a single instance for every HTTP request call.

4) session: Returns a single instance for every HTTP session.

5) global session: global session scope is equal as session scope on portlet-based


web applications.

If no bean scope is specified in bean configuration file, then it will be by


default 'singleton'.

Q : Spring bean java based configuration using @Configuration and @Bean ?


-------------------------------------------------------------------------
created a maven project, and here is the sample pom.xml file and spring
dependencies.
@Configuration
public class MyAppConfig {

@Bean(name="myColorBean")
public MyColor getMyColors(){
return new RedColor();
}
}

Q : -How to inject inner bean in spring?


-----------------------------------------
ans:
a <bean/> element inside the <property/> or <constructor-arg/> elements is called
inner bean. This page gives an example to inject inner bean in spring.

<bean id="paymentGwBean" class="com.java2novice.beans.PaymentGateway">


<constructor-arg>
<bean class="com.java2novice.beans.Order">
<property name="item" value="Java2Novice" />
<property name="price" value="RS 22.50" />
<property name="address" value="Bangalore" />
</bean>
</constructor-arg>
</bean>
</beans>

Q - How to read property file in spring using xml based configuration file ?
----------------------------------------------------------------------------
ans:-
using xml based configuration file
----------------------------------
Declare your property file in your xml based configuration file using
"context:property-placeholder" tag, and refer property key any where in the xml
based configuration file using ${db.host.url} syntax.

ex: db.properties file:


ex: Xml based configuration file:->
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:property-placeholder location="classpath:db.properties" />

<bean id="dbConfig" class="com.java2novice.beans.MyDbConfig">


<property name="dbHost" value="${db.host.url}"/>
<property name="dbPort" value="${db.port.number}"/>
<property name="dbService" value="${db.service.name}"/>
<property name="dbUrl" value="${db.user}"/>
<property name="dbPassword" value="${db.password}"/>
</bean>
</beans>

using java based configuration:


---------------------------------

@Configuration
@PropertySource("classpath:/db.properties")
public class MyApplicationConfig {

@Autowired
Environment env;

@Bean(name="dbConfig")
public MyDbConfig getDbConfig(){

MyDbConfig dbConf = new MyDbConfig();


dbConf.setDbHost(env.getProperty("db.host.url"));
dbConf.setDbPort(env.getProperty("db.port.number"));
dbConf.setDbService(env.getProperty("db.service.name"));
dbConf.setDbUser(env.getProperty("db.user"));
dbConf.setDbPassword(env.getProperty("db.password"));
return dbConf;
}
}

Spring bean inheritance configuration


--------------------------------------
xml based configurations, you can see the bean reference "baseEmployeeBean" playing
as parent bean and bean reference "myEmployeeBean" playing as child bean and
inheriting property called company, and adding new properties empId and name.

<bean id="baseEmployeeBean" class="com.java2novice.beans.Employee">


<property name="company" value="Java2novice" />
</bean>
<bean id="myEmployeeBean" parent="baseEmployeeBean">
<property name="empId" value="1016" />
<property name="name" value="Nataraja Gootooru" />
</bean>
</beans>

Note:-
Spring allows you to restrict parent bean by specifying abstract property. Below
configuration makes the parent bean abstract, so you cannot creat object for parent
bean

<bean id="baseEmployeeBean" class="com.java2novice.beans.Employee" abstract="true">


<property name="company" value="Java2novice" />
</bean>
<bean id="myEmployeeBean" parent="baseEmployeeBean">
<property name="empId" value="1016" />
<property name="name" value="Nataraja Gootooru" />
</bean>
</beans>

Q what is @Required annotation ?


or
Spring dependency checking with @Required annotation
ans:
Sometimes, we need to make sure that all the required dependencies are set to the
spring bean. Spring provides @Required annotation to check spring dependencies. If
the required dependencies are not set, then it throws BeanInitializationException.
ex:
public class PaymentGateway {

private String client;

private Order order;

@Required
public void setOrder(Order ord){
this.order = ord;
}
}

Q: Difference between @Component, @Service, @Repository and @Controller ?


ans:
You can annotate your services or DAOs with on of @Component, @Service,
@Repository, or @Controller annotations.
If you specify the class with one of these annotations, the class is eligible for
auto scan.
The base-package value should be package name and will be scanned for the
components with in the packages and its sub-packages.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

<context:component-scan base-package="com.java2novice" />


</beans>
@Component: It is a basic auto component scan annotation, it indicates annotated
class is a auto scan component.

@Repository: You need to use this annotation with in the persistance layer, which
acts like database repository.

@Service: It indicates annotated class is a Service component in the business


layer.

@Controller: Annotated class indicates that it is a controller components, and


mainly used at presentation layer.

Q: Spring bean auto-wiring modes ?


ans:-
no: No autowiring at all. Bean references must be defined via a ref element. This
is the default, and changing this is discouraged for larger deployments, since
explicitly specifying collaborators gives greater control and clarity. To some
extent, it is a form of documentation about the structure of a system.

byName: Autowiring by property name. This option will inspect the container and
look for a bean named exactly the same as the property which needs to be autowired.
For example, if you have a bean definition which is set to autowire by name, and it
contains a master property (that is, it has a setMaster(..) method), Spring will
look for a bean definition named master, and use it to set the property.

byType: Allows a property to be autowired if there is exactly one bean of the


property type in the container. If there is more than one, a fatal exception is
thrown, and this indicates that you may not use byType autowiring for that bean. If
there are no matching beans, nothing happens; the property is not set. If this is
not desirable, setting the dependency-check="objects" attribute value specifies
that an error should be thrown in this case.

constructor: This is analogous to byType, but applies to constructor arguments. If


there isn't exactly one bean of the constructor argument type in the container, a
fatal error is raised.

autodetect: Chooses constructor or byType through introspection of the bean class.


If a default constructor is found, the byType mode will be applied.

Q: auto-wiring by providing @Autowired annotation ?


ans:-
Note- To use auto-wire feature through annotations, you must include annotation-
config tag with in your xml based configuration file:
<context:annotation-config />

>Spring also provides annotation based auto-wiring by providing @Autowired


annotation. you can use @Autowired annotation to auto wire spring bean on setter
method, instance variable, and constructor. If you use @Autowired annotation,
spring container auto-wires the bean by matching data type.
>Note:- If spring fails to find matching bean for auto-wiring, it throws an
exception. If you don't dependency check, then use "required" attribute of
@Autowired annotation, and set it false. Here is an example:

@Autowired(required=false)
public PaymentGateway(Order ord){
this.order = ord;
}

Q: What if a same bean declared twice? Which bean will be auto-wired? or


[ @Qualifier annotation]
ans
<context:annotation-config />

<bean id="paymentGateway" class="com.java2novice.beans.PaymentGateway"/>

<bean id="javaOrderBean" class="com.java2novice.beans.Order" >


<property name="item" value="Java Book" />
<property name="price" value="RS 225" />
</bean>
<bean id="oracleOrderBean" class="com.java2novice.beans.Order" >
<property name="item" value="Oracle Book" />
<property name="price" value="RS 305" />
</bean>
</beans>

To solve this issue, use @Qualifier annotation with bean name, so spring container
picks the right bean declaration and assigned to the property.

You might also like