Spring Notes
Spring Notes
Spring Notes
Contents
What is Spring?. 5
o Constructor Injection. 8
o Setter Injection. 8
o Interface Injection. 8
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 1/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
IoC containers: 35
Implementation of BeanFactory. 36
Implementations of ApplicationContext. 36
FileSystemXmlApplicationContext: 36]
ClassPathXmlApplicationContext. 36]
WebXmlApplicationContext: 37]
Which one should be better to use i.e. service locator or dependency injection?. 40
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 2/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Spring Bean Life Cycle Methods ? InitializingBean, DisposableBean, @PostConstruct, @PreDestroy and *Aware interfaces 45
no: 56]
byName: 56]
byType. 56]
constructor. 56]
autodetect: 56]
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 3/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
RequiredAnnotationBeanPostProcesso. 67
How to use Spring @Component, @Repository, @Service and @Controller Annotations, @RequestMapping?. 70
Initialization callbacks: 74
Destruction callbacks: 75
Task scheduling using cron expression from properties file and @Scheduled annotation. 82
Defining a Controller. 93
Spring JdbcTemplate. 97
JdbcTemplate class. 98
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 4/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Example of RowMapper Interface to show all the records of the table. 104
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 5/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Spring: (WHAT/WHEN/HOW/WHY)
What is Spring?
- It is a lightweight, loosely coupled and integrated framework for developing enterprise applications in java.
- Spring Framework is built on top of two design concepts ? Dependency Injection and Aspect Oriented Programming.
- Whyto use spring is something more of a combination of desire to do things in an easy, secure and efficient way.
- It's been noticed a lot of complexity of code is present in development which can be avoided, Such as code to handle
transaction, JDBC, interaction with ORM, Exception Handling, Testing and many others.
- Springs provides support for existing J2EE technologies and provide easy and efficient way to do the development.
- Lightweight and very little overhead of using framework for our development.
- Dependency Injection or Inversion of Control to write components that are independent of each other, spring container takes
care of wiring them together to achieve our work.
- Spring IoC container manages Spring Bean life cycle and project specific configurations such as JNDI lookup.
- Spring MVC framework can be used to create web applications as well as restful web services capable of returning XML as
well as JSON response.
- Support for transaction management, JDBC operations, File uploading, Exception Handling etc with very little
configurations, either by using annotations or by spring bean configuration file.
- Reducing direct dependencies between different components of the application, usually Spring IoC container is responsible
for initializing resources or beans and inject them as dependencies.
- Writing unit test cases are easy in Spring framework because our business logic doesn't have direct dependencies with
actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing
purposes.
- Reduces the amount of boiler-plate code, such as initializing objects, open/close resources. JdbcTemplate helps us in
removing all the boiler-plate code that comes with JDBC programming.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 6/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
- Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we
don't need Spring transaction management features, we don't need to add that dependency in our project.
- Spring framework support most of the Java EE features and even much more. It's always on top of the new technologies, for
example there is a Spring project for Android to help us write better code for native android applications. This makes spring
framework a complete package and we don't need to look after different framework for different requiremen
Spring Modules:-
This Core Module is the base module of a spring frame work application.
This Core Module will provide the following information to the spring programmers.
The core container provides the essential functionality of the Spring framework. A primary component of the core container is the
BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate
an application's configuration and dependency specification from the actual application code.
While working with JDBC technology directly as programmers, we are writing the Boiler-plate code (Repeated code) like Loading
the driver, opening a connection, creating a statement and closing the objects etc?
Apart from Boiler-plate code, we also need to handle the Exceptions of JDBC explicitly because JDBC Exceptions are checked
exceptions.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 7/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
In order to avoid the Boiler-plate code and to also avoid exception handling Burdon, spring frame work has provided this DAO
module.
The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error
messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of
exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its
generic DAO exception hierarchy.
This ORM Module is an abstraction layer on top of the ORM tools and which makes a spring programmer to transfer a data between
application and database in the form of objects.
ORM tools are very good tools for communicating with databases but having some drawbacks, these drawbacks are eliminated in
spring ORM module.
The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and
iBatis SQL Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies.
Aspect Oriented Programming is a new way to developing real time applications with required services
The AOP module will provide us the way of separating the services from Business logic and also it provides us the way of injecting
the services for business logic at runtime.
In spring terminology, the services are also called ?Cross-Cutting Concerns? (Middle ware services).
The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its
configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring
AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can
incorporate declarative transaction management into your applications without relying on EJB components.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 8/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
This Module is for implementing the middleware services required for Business logic. This spring JEE module is an abstraction
layer on top of RMI, Java mail, JMS, Jars etc?
AOP is just for applying the services (or) injecting the services but not for implementing the services, whereas JEE is a module for
implementing the services.
For real time Business logic development with middleware services, we use spring core, spring AOP, and spring JEE modules.
The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC
framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity,
Tiles, iText, and POI.
This module is either for integrating with web applications created in other frame works (or) for creating complete MVC to based
web application in spring frame work.
Spring web module is also called Spring web MVC module and this module is for creating web applications of java with MVC to
architecture.
The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a
result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part
requests and binding request parameters to domain objects.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 9/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Inversion of control(IoC) is a programming technique in which object coupling is bound at run time by an assembler object and is
typically not known at compile time using static analysis.
- Dependency Injection is a way to achieve Inversion of control (IoC) in our application by moving objects binding from
compile time to runtime. We can achieve IoC through Factory Pattern, Template Method Design Pattern, Strategy Pattern and
Service Locator pattern too.
- Spring, Google Guice and Java EE CDI frameworks facilitate the process of dependency injection through use of Java
Reflection API and java annotations. All we need is to annotate the field, constructor or setter method and configure them in
configuration xml files or classes.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 10/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Files required..
- java
- java [ Our logic
- xml [ spring configuration file, it can be of any name
Open Eclipse ?> File ?> New ?> (Select Java project, if not found just click on) Other
Now it will ask you to give you application name, so give what ever name you want and click finish?
That's it.., now you will see your application will looks like this..
WelcomeBean.java
package technicalstack;
this.message = message;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 11/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
System.out.println(message);
ClientLogic.java
package technicalstack;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Object o = factory.getBean("id1");
WelcomeBean wb = (WelcomeBean)o;
wb.show();
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 12/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
package technicalstack;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
spconfig.xml
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
</bean>
</beans>
Explanation
see WelcomeBean.java, i have written setter method for the property message (primitive), spring container will inject some value in
that property at run time
In ClientLogic.java first we need to load the configuration file, so we done this at line number 12, so res, contains all the information
about the configuration xml.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 13/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
And give this res object to BeanFactory [ Spring container ] with XmlBeanFactory, so now factory knows all the beans in the xml
file so we can now call any bean with bean id.
In ClientLogic.java, if we call getBean(?id1?) then internally the spring framework executes the following statements
wb.setMessage(?Welcome to spring?);
And now will gives WelcomeBean object back [at line number 15,] in the form of Object class object, and i typecast into
WelcomeBean class at line number 16
Remember, by default every spring bean is the singleton class. Spring IOC container makes a spring bean as singleton automatically
Return type of getBean() is always super class object, which is Object class object
i have given that primitive type as String, you can use int, float, double what ever you want
See in spconfig.xml, line number 7 we have written the property element right, here <property /> means we are saying to the spring
container that we have written setter method in our bean class [WelcomeBean.java 7 to 9 lines ], in the that property we assigned
value as an attribute, which means the setter injection is in the form of primitive values [ may be int, string, float bla bla.. ]
If object dependency is there then in spring framework, the spring IOC container is responsible for creating that required object and
injecting into the dependent class
For 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.
So we will see about <ref /> element, and i forgot to tell you actually in previous example we have one spring configuration file
right [ spconfig.xml ], in spring we can write multiple configuration xmls, i will tell you how its going to work in the following
example
Syntax will be
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 14/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
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. But its not mandatory we can create
multiple configure files too right.
Exmple:
public DemoBean
this.sb = sb;
sb.m2();
Note: See am calling m2() method in SamepleBean so now let us see how the xml file will be
<beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 15/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<bean id="id1">
</property>
</bean>
</beans>
So our DemoBean class depends on other class object SampleBean, see in the xml line number 5 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 same
xml 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?
spconfig1.xml
<beans>
<bean id="id1">
</property>
</bean>
spconfig2.xml
<beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 16/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</beans>
In this case, we have to write parent as attribute, see spconfig1.xml line number 5. As we specified parent, spring container will
only checks in the parent i mean spconfig2.xml only
If we give attribute as bean, then first it will checks at local xml file, then parent if its not available at local. Hey you will be able to
understand once you got through the example?, let us see the program on this in the next session.
Let us see one example for previous concept, dependency in the form of objects with <ref /> element
files required..
i am taking complete pojo / poji model this time, And mates this is ? very important and Exact concept of spring framework ? ,
make sure you understood this application from start to end point, if you are not able to understand you may not able to continue
with the remaining concepts :-)
- java
- java
- java
- java
- java
- xml
- xml
- java
Journey.java
void startJournty();
Travel.java
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 17/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Private Vehicle v;
this.v = v;
v.move();
Vehicle is the interface, Car and Bus are the implemented classes
Vehicle.java
void move();
Car.java
package technicalstack;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 18/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
return fuelType;
this.fuelType = fuelType;
return maxSpeed;
this.maxSpeed = maxSpeed;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 19/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
System.out.println("car started....");
package technicalstack;
return fuelType;
this.fuelType = fuelType;
return maxSpeed;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 20/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
this.maxSpeed = maxSpeed;
System.out.println("car started....");
Bus
package technicalstack;
return maxSpeed;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 21/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
this.maxSpeed = maxSpeed;
System.out.println("Bus started....");
spconfig1.xml
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
</bean>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 22/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</bean>
</beans>
spconfig2.xml
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<property name="v">
</property>
</bean>
</beans>
ClientLogic.java
package technicalstack;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 23/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Object o = factory2.getBean("id3");
Journey j = (Journey)o;
j.startJourney();
package technicalstack;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 24/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Object o = factory2.getBean("id3");
Journey j = (Journey)o;
j.startJourney();
Explanation:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 25/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
No confusion, i have taken all the classes with some implementation, i will tell you the reason why? ?
Now come to the configuration files, i have been taken 2 configuration xml (for explaining local, parent, bean attribute concept :) )
Actually we have 2 configuration files right, so in our client logic we need to define factory object two times [ ClientLogic.java, line
numbers, 12,13 ? 15,16 ]. In factory1 object, i have been taken spconfig1.xml [ ClientLogic.java, Line number 12 ], where Car,Bus
classes been configured. factory2 knows factory1, as we included factory1 object in factory2 [ see line number 16, ClientLogic.java
]
Once we call id3 in ClientLogic.java, then spring container will move to spconfig2.xml and checks, there property v depends on
other class right, and we given parent=id2, then control move to spconfig1.xml and finds id2 ?> creates Bus class object, and will
send back that Bus object to our client program
According to our program Bus object will be injected into the Traveler finally and there after we will get it into client application,
and we can change id2 to id1 in the spconfig2.xml for getting Car object, with our recompilation ;)
This is the complete POJO / POJI Model of spring, i will tell you why we need to take Interface for every class like above, you
might have known with this example, but no problem i will rise this topic in the next sessions.
Output:
Spring Setter Injection, Dependency In The Form Of Collections
While creating spring bean (pojo class), the bean class can use any of the following
4 types of collections as dependency, along with some primitives and objects like previous sessions..
- Set
- List
- Map
- Properties
Except above 4 types of collections, if the spring bean class uses any other type of collection as dependency, then spring container
doesn't inject that collection object to the spring bean, in this case spring programmer is responsible for injection that collection
object manually.
Let us see how to use one by one collection property with syntax
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 26/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
If in our spring bean has a property of type Set then in the spring config xml file, we need to use <set> element to inform the Spring
IOC container regarding that Set property
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 dependent bean object
Example
this.studentsData = studentsData;
this.tb = tb;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 27/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
// Some Logic
Our XML
<beans>
<property name="studentsData">
<set>
<value>sun</value>
<value>Oracle</value>
<value>technicalstack</value>
<ref bean="id2">
</set>
</property>
</bean>
</beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 28/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Explanation:
Now in our client when we call getBean(?id1?) then spring framework executes, following code internally [ not be visible :-) ]
s.add("sun");
s.add("oracle");
s.add("technicalstack");
ob.setStudentsData(s);
s.add("sun");
s.add("oracle");
s.add("technicalstack");
ob.setStudentsData(s);
First spring ioc creates TestBean class object as SampleBean depends on TestBean, then creates the Set object and will add the data
into the set object and finally our SampleBean object will be created and set object will be injected.
Actually nothing mates, just like primitive value injections, just we used Collections here nothing more than that :-) , download this
example and test.
- java
- java
- xml
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 29/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Directory structure:
WelcomeBean.java
package technicalstack;
import java.util.Set;
this.studentsData = studentsData;
System.out.println(studentsData);
spconfig.xml
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 30/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<set>
<value>technicalstack</value>
<value>sun</value>
<value>oracle</value>
<value>sun</value>
<value>sun</value>
</set>
</property>
</bean>
</beans>
ClientLogic.java
package technicalstack;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 31/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Object o = factory.getBean("id1");
WelcomeBean wb = (WelcomeBean)o;
wb.show();
Note: Set wont allows duplicates, though you give duplicate values in spconfig.xml it will shows values only once in the output try
this ;)
OutPut
In the previous example [ Dependency In The Form Of Set Collection Property ] just change to <list /> where ever we have <set />
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 32/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Set doesn't 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
this.studentsData = studentsData;
this.tb = tb;
// Some Logic
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 33/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Our XML
<beans>
<property name="studentsData">
<list>
<value>sun</value>
<value>Oracle</value>
<value>technicalstack</value>
<value>sun</value>
<ref bean="id2">
</list>
</property>
</bean>
</beans>
Note: Mates see, in our xml i have been added sun two times, as List will allows the duplicate values, but set doesn't. That's it
mates, but Map is not like these two collection and little more important than these two, so we will see in depth regarding this Map
in the next session.
Mates am not giving any example here as its same as setter injection ( Hello World program only, see how easy ;) ), but you can
download the example and test at your locals.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 34/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
- java
- java
- xml
Directory structure:
WelcomeBean.java
package technicalstack;
import java.util.List;
this.studentsData = studentsData;
System.out.println(studentsData);
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 35/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
spconfig.xml
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<list>
<value>technicalstack</value>
<value>sun</value>
<value>oracle</value>
<value>technicalstack</value>
</list>
</property>
</bean>
</beans>
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 36/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<list>
<value>technicalstack</value>
<value>sun</value>
<value>oracle</value>
<value>technicalstack</value>
</list>
</property>
</bean>
</beans>
ClientLogic.java
package technicalstack;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 37/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Object o = factory.getBean("id1");
WelcomeBean wb = (WelcomeBean)o;
wb.show();
OutPut
k1 Oracle
k2 Sun
k3 technicalstack
k4 id2
See here we have two entries [two pairs], one entry is k1 ? 100 and second entry is k2 ? 200
Map is the interface, Entry is the static class in Map interface, so we can call Map.Entry just remember this concept as of now
In the XML
<map>
<entry key="k1">
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 38/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<value>Oracle</value>
</entry>
<entry key="k2">
<value>Sun</value>
</entry>
<entry key="k3">
<value>technicalstack</value>
</entry>
</map>
See in the xml, we have to configure like this, so we have 3 pairs [ key, values] means spring container will creates 3 Map.Entry
class objects and stores those objects in <map />
One <entry /> tag will produces one object of Map.Entry, by the way k4 is to getting other bean class object.
- java
- java
- xml
Directory structure:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 39/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
WelcomeBean.java
package technicalstack;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
this.data = data;
Set s=data.entrySet();
Iterator it = s.iterator();
while(it.hasNext())
Map.Entry me = (Map.Entry)it.next();
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 40/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
spconfig.xml
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<map>
<entry key="k1">
<value>10</value>
</entry>
<entry key="k2">
<value>technicalstack</value>
</entry>
<entry key="k3">
<value>10.55</value>
</entry>
</map>
</property>
</bean>
</beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 41/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
ClientLogic.java
package technicalstack;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Object o = factory.getBean("id1");
WelcomeBean wb = (WelcomeBean)o;
wb.show();
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 42/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Explanation:
First take our ClientLogic.java, see line number 15 when we call factory.getBean(?id1?) then spring IOC will go to spconfig.xml
and verify the class name having id1, [ you can see this in spconfig.xml line number 5, there our class name is WelcomeBean ]
In WelcomeBean.java we have been taken Map property [ see line number 7 ], and written setter property for that Map
In spconfig.xml we configured some values for that Map property right, so with this setter method spring IOC will inject all these
values into Map data property
now come to show() method at line number 13, here see the concept actually we don't have any iterator for Map right, hope you
know this fact :-) , but we need iterator to get and print the data from the Map, moreover List,Set have the iterator.
So now we need Set or List to get the iterator, so am going to take Set, at line number 15, of course you can go with List as well
Actually data is of Map type, in Map we have one method called entrySet() which always returns Set object, so i got the iterator by
using this Set object at line number 16
Now see line number 19, i have been typecast into Map.Entry, so that i can print key and values separately by calling getKey() and
getValues() methods in the Map.Entry Class [ I already given the concept about this Map.Entry go to top and check if you have any
doubt regarding this ]
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
For Example:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 43/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
This.message = message;
This.message = message;
In Config XML
</bean>
Output
In client application, when we call factory.getBean(?id1?), then internally spring framework executes following statements
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 44/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Ob.setMessage("Welcome to spring");
finally value in message will be Welcome to spring, not Welcome to technicalstack, as setter will over rides constructor, the reason
being see i have taken primitive value [string] as dependency, we have written injection for this property in constructor and setter
method. We all know constructor will be executed at object creation, so at the time of object creation only some value will be
assigned into message property, then setter will be called so previous value will be overrides
???????????? # ???????????
In constructor injection, if argument types are different, then at the time of configuring of xml file we can use type attribute
Example..
This.id = id;
This.sname = sname;
In Config XML
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 45/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</bean>
According to above xml, DemoBean object will be created with 10 as id and 1000 as string [sname]
???????????? # ???????????
Let if we have 2 properties of same type, like user name and password
Example..
This.uname = uname;
This.password = password;
In our xml
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 46/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Now bean object will be created with myuserName as username, and mypassword as password
???????????? # ???????????
Dependency in the form of object in this constructor injection
Let us see how to work with dependency in the form of objects in this constructor injection?
This.sb = sb;
In the xml
</bean>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 47/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</bean>
Note: Here see, directly i given ref as an attribute, so internally it meas ref-bean only not ref-local or ref-parent
???????????? # ???????????
This.id = id;
This.uname = uname;
This.id = id;
This.uname = uname;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 48/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
10
11
12
13
14
15
16
17
18
19
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 49/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
This.id = id;
This.uname = uname;
This.id = id;
This.uname = uname;
<beans>
</bean>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 50/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</bean>
</beans>
10
11
12
13
14
15
16
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 51/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<beans>
</bean>
</bean>
</beans>
In the above example, when we class factory.getBean(?id1?) from client application then spring framework creates an object of
DemoBean by calling 1st constructure
If we call factory.getBean(?id2?) then spring framework crates the object of DemoBean by calling 2nd constructor automatically
This is total about this constructor injection in Spring, nothing more than that.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 52/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<property name="emails">
<props>
<prop key="admin">admin@nospam.com</prop>
<prop key="support">support@nospam.com</prop>
</props>
</property>
</bean>
You can use ?util:? namespace as well to create properties bean from properties file, and use bean reference for setter injection.
IoC containers:
The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework's IoC
container.
The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsible
for containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC container
interface in Spring.
Bean Factory container:This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where
the resources are limited like mobile devices or applet based applications
Spring ApplicationContext Container:This container adds more enterprise-specific functionality such as the ability to resolve
textual messages from a properties file and the ability to publish application events to interested event listeners.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 53/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans
within itself and then instantiates the bean whenever asked for by clients.BeanFactory is able to create associations between
collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans
client. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans
upon request. But it also provides:
Implementation of BeanFactory
The most commonly used BeanFactory implementation is the XmlBeanFactory This container reads the configuration metadata
from an XML file and uses it to create a fully configured system or application.
FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide
the full path of the XML bean configuration file to the constructor.
-
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("F:/my workspace/springAppDemo/sr
c/spring.xml");
ClassPathXmlApplicationContext This container loads the definitions of the beans from an XML file. Here you do not need to
provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration
XML file in CLASSPATH.
-
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:com/dineshonjava/sdnext/springConfig/sprin
g.xml");
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 54/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.
- Application contexts provide a means for resolving text messages, including support for i18n of those messages.
- Application contexts provide a generic way to load file resources, such as images.
- Application contexts can publish events to beans that are registered as listeners.
- Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a
bean factory, can be handled declaratively in an application context.
- ResourceLoader support: Spring's Resource interface us a flexible generic abstraction for handling low-level resources. An
application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource
instances.
- MessageSource support: The application context implements MessageSource, an interface used to obtain localized
messages, with the actual implementation being pluggable
- The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans.
A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created
with the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions.
- The bean definition contains the information called configuration metadata which is needed for the container to know the
followings:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 55/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<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.xsd">
</bean>
</beans>
When defining a <bean> in Spring, you have the option of declaring a scope for that bean. For example, to force Spring to produce
a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you want
Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 56/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
When creating a bean using the constructor approach, all normal classes are usable by and compatible with Spring. That is, the class
being created does not need to implement any specific interfaces or be coded in a specific fashion. Just specifying the bean class
should be enough. When using XML-based configuration metadata you can specify your bean class like so:
<bean id="exampleBean"/>
2. Instantiation using a static factory method
When defining a bean which is to be created using a static factory method, along with the class attribute which specifies the class
containing the static factory method, another attribute named factory-method is needed to specify the name of the factory method
itself.
Spring expects to be able to call this method and get back a live object, which from that point on is treated as if it had been created
normally via a constructor.
factory-method="createInstance"></bean>
The basic principle behind Dependency Injection (DI) is that objects define their dependencies only through constructor arguments,
arguments to a factory method, or properties which are set on the object instance after it has been constructed or returned from a
factory method. Then, it is the job of the container to actually inject those dependencies when it creates the bean. This is
fundamentally the inverse, hence the name Inversion of Control (IoC).
4. Setter injection
Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static
factory method to instantiate your bean.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 57/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
this.demoBean = demoBean;
5. Constructor injection
Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.
Additionally, calling a static factory method with specific arguments to construct the bean, can be considered almost equivalent, and
the rest of this text will consider arguments to a constructor and arguments to a static factory method similarly.
Interface injection In this methodology we implement an interface from the IOC framework. IOC framework will use the interface
method to inject the object in the main class. It is much more appropriate to use this approach when you need to have some logic that
is not applicable to place in a property. Such as logging support.
_notificationService.SetLogger(logger);
_productService.SetLogger(logger);
A service is similar to a component in that it's used by foreign applications. The main difference is that a component to be used
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 58/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
locally (think jar file, assembly, dll, or a source import). A service will be used remotely through some remote interface, either
synchronous or asynchronous (eg web service, messaging system, RPC, or socket.)
Mostly these registries are populated via some configuration files. The key difference is that with a Service Locator every user of a
service has a dependency to the locator. The locator can hide dependencies to other implementations, but you do need to see the
locator.
Which one should be better to use i.e. service locator or dependency injection?
Well, it as I already said that key difference is that with a Service Locator every user of a service has a dependency to the locator. It
means you must know the details of service locator in terms of input and output. So, it actually becomes the deciding factor which
pattern to choose from.
If it is easy and necessary to maintain registry information then go for service locator, or else simply use dependency injection as it
does not bother the users of service with any per-requisites.
The choice between setter and constructor injection is interesting as it mirrors a more general issue with object-oriented
programming -- should you fill fields in a constructor or with setters.
Constructors with parameters give you a clear statement of what it means to create a valid object in an obvious place. If there's more
than one way to do it, create multiple constructors that show the different combinations. Another advantage with constructor
initialization is that it allows you to clearly hide any fields that are immutable by simply not providing a setter. I think this is
important -- if something shouldn't change then the lack of a setter communicates this very well. If you use setters for initialization,
then this can become a pain.
But If you have a lot of constructor parameters things can look messy, particularly in languages without keyword parameters. If you
have multiple ways to construct a valid object, it can be hard to show this through constructors, since constructors can only vary on
the number and type of parameters. Constructors also suffer if you have simple parameters such as strings. With setter injection you
can give each setter a name to indicate what the string is supposed to do. With constructors you are just relying on the position,
which is harder to follow.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 59/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
My preference is to start with constructor injection, but be ready to switch to setter injection as soon as the problems I've outlined
above start to become a problem.
- The Spring Framework supports following five scopes, three of which are available only if you use a web-aware
ApplicationContext.
singleton:This scopes the bean definition to a single instance per Spring IoC container.
prototype:This scopes a single bean definition to have any number of object instances.
request:This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
session:This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-session:This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring
ApplicationContext.
XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring
Bean. For example:
Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This
annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 60/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Configuration
@ComponentScan(value="com.journaldev.spring.main")
@Bean
To get this bean from spring context, we need to use following code snippet:
MyConfiguration.class);
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 61/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with
classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes.
For example:
1
<context:component-scan base-package="com.journaldev.spring" />
singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While
using this scope, make sure spring bean doesn't have shared instance variables otherwise it might lead to data inconsistency issues
because it's not thread-safe.
prototype: A new instance will be created every time the bean is requested.
request: This is same as prototype scope, however it's meant to be used for web applications. A new instance of the bean will be
created for each HTTP request.
session: A new bean will be created for each HTTP session by the container.
global-session: This is used to create global session beans for Portlet applications.
Spring Framework is extendable and we can create our own scopes too, however most of the times we are good with the scopes
provided by the framework.
To set spring bean scopes we can use ?scope? attribute in bean element or @Scope annotation for annotation based configurations.
What is Spring Java-Based Configuration?
The central artifacts in Spring's new Java-configuration support are @Configuration annotated classes and @Bean annotated
methods.
The @Bean annotation is used to indicate that a method instantiates, configures and initializes a new object to be managed by the
Spring IoC container. @Bean annotation plays the same role as the <bean/> element.
Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions. Furthermore,
@Configuration classes allow inter-bean dependencies to be defined by simply calling other @Bean methods in the same class. The
simplest possible @Configuration class would read as follows:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 62/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Configuration
@Bean
The equivalent XML configuration for above java config would be:
<beans>
</beans>
To instantiate such config, you will need the help of AnnotationConfigApplicationContext class.
myService.doStuff();
@Configuration
@ComponentScan(basePackages = "com.technicalstack")
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 63/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
...
In the example above, the com.acme package will be scanned, looking for any @Component annotated classes, and those classes
will be registered as Spring bean definitions within the container.
If you are using above configuration in a web application then you will be using AnnotationConfigWebApplicationContext class.
This implementation may be used when configuring the Spring ContextLoaderListener servlet listener, Spring MVC
DispatcherServlet etc.
<web-app>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.technicalstack.AppConfig</param-value>
</context-param>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 64/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<!-- Bootstrap the root application context as usual using ContextLoaderListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<!-- Again, config locations must consist of one or more comma- or space-delimited
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.technicalstack.web.MvcConfig</param-value>
</init-param>
</servlet>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 65/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<!-- map all requests for /app/* to the dispatcher servlet -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to
describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant
class, method, or field declaration. Annotation injection is performed before XML injection, thus the latter configuration will
override the former for properties wired through both approaches.
Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need
to enable it in our Spring configuration file. So consider to have following configuration file in case you want to use any annotation
in your Spring application.
<beans>
<context:annotation-config/>
</beans>
Once <context:annotation-config/> is configured, you can start annotating your code to indicate that Spring should automatically
wire values into properties, methods, and constructors.
Few important annotations which you will be using in this type of configuration are :
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 66/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Autowired : The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and
properties.
@Qualifier : The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact
bean will be wired.
JSR-250 Annotations : Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy
annotations.
Spring bean factory is responsible for managing the life cycle of beans created through spring container. The life cycle of beans
consist of call back methods which can be categorized broadly in two groups:
Spring framework provides following 4 ways for controlling life cycle events of bean:
For example, customInit() and customDestroy() methods are example of life cycle method.
<beans>
init-method="customInit" destroy-method="customDestroy"></bean>
</beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 67/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
- Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for complete
example of these aware interfaces, please read Spring Aware Interfaces]
- Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet
container specific environment only though.
2
@Autowired
ServletContext servletContext;
Spring Bean Life Cycle Methods ? InitializingBean, DisposableBean, @PostConstruct, @PreDestroy and *Aware interfaces
Spring Beans are the most important part of any Spring application. Spring ApplicationContext is responsible to initialize the Spring
Beans defined in spring bean configuration file.
Spring Context is also responsible for injection dependencies in the bean, either through setter/constructor methods or by spring
autowiring.
Sometimes we want to initialize resources in the bean classes, for example creating database connections or validating third party
services at the time of initialization before any client request. Spring framework provide different ways through which we can
provide post-initialization and pre-destroy methods in a spring bean.
By implementing InitializingBean and DisposableBean interfaces ? Both these interfaces declare a single method where we can
initialize/close resources in the bean. For post-initialization, we can implement InitializingBean interface and provide
implementation of afterPropertiesSet() method. For pre-destroy, we can implement DisposableBean interface and provide
implementation of destroy() method. These methods are the callback methods and similar to servlet listener implementations.
This approach is simple to use but it's not recommended because it will create tight coupling with the Spring framework in our bean
implementations.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 68/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Providing init-method and destroy-method attribute values for the bean in the spring bean configuration file. This is the
recommended approach because of no direct dependency to spring framework and we can create our own methods.
Note that both post-init and pre-destroy methods should have no arguments but they can throw Exceptions. We would also require to
get the bean instance from the spring application context for these methods invocation.
Spring framework also support @PostConstruct and @PreDestroy annotations for defining post-init and pre-destroy methods. These
annotations are part of javax.annotation package. However for these annotations to work, we need to configure our spring
application to look for annotations. We can do this either by defining bean of type
org.springframework.context.annotation.CommonAnnotationBeanPostProcessor or by context:annotation-config element in spring
bean configuration file.
Let's write a simple Spring application to showcase the use of above configurations. Create a Spring Maven project in Spring Tool
Suite, final project will look like below image.
spring-bean-life-cycle-project
We don't need to include any extra dependencies for configuring spring bean life cycle methods, our pom.xml file is like any other
standard spring maven project.
pom.xml
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 69/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>SpringBeanLifeCycle</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.7</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-framework.version>4.0.2.RELEASE</spring-framework.version>
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 70/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 71/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Model Class
Let's create a simple java bean class that will be used in service classes.
Employee.java
package com.journaldev.spring.bean;
return name;
this.name = name;
Let's create a service class where we will implement both the interfaces for post-init and pre-destroy methods.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 72/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
EmployeeService.java
package com.journaldev.spring.service;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import com.journaldev.spring.bean.Employee;
return employee;
this.employee = employee;
public EmployeeService(){
@Override
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 73/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Override
if(employee.getName() == null){
employee.setName("Pankaj");
Since we don't want our services to have direct spring framework dependency, let's create another form of Employee Service class
where we will have post-init and pre-destroy methods and we will configure them in the spring bean configuration file.
MyEmployeeService.java
package com.journaldev.spring.service;
import com.journaldev.spring.bean.Employee;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 74/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
return employee;
this.employee = employee;
public MyEmployeeService(){
//pre-destroy method
//post-init method
if(employee.getName() == null){
employee.setName("Pankaj");
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 75/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
We will look into the spring bean configuration file in a bit. Before that let's create another service class that will use
@PostConstruct and @PreDestroy annotations.
Below is a simple class that will be configured as spring bean and for post-init and pre-destroy methods, we are using
@PostConstruct and @PreDestroy annotations.
MyService.java
package com.journaldev.spring.service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@PostConstruct
public MyService(){
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 76/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@PreDestroy
Let's see how we will configure our beans in spring context file.
spring.xml
<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.xsd">
</bean>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 77/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
init-method="init" destroy-method="destroy">
</bean>
</beans>
Notice that I am not initializing employee name in it's bean definition. Since EmployeeService is using interfaces, we don't need any
special configuration here.
For MyEmployeeService bean, we are using init-method and destroy-method attributes to let spring framework know our custom
methods to execute.
MyService bean configuration doesn't have anything special, but as you can see that I am enabling annotation based configuration
for this.
Our application is ready, let's write a test program to see how different methods get executed.
Test Program
SpringMain.java
package com.journaldev.spring.main;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 78/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.journaldev.spring.service.EmployeeService;
import com.journaldev.spring.service.MyEmployeeService;
System.out.println("Employee Name="+service.getEmployee().getName());
ctx.close();
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 79/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
INFO: Loading XML bean definitions from class path resource [spring.xml]
Employee Name=Pankaj
Important Points:
From the console output it's clear that Spring Context is first using no-args constructor to initialize the bean object and then calling
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 80/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
The order of bean initialization is same as it's defined in the spring bean configuration file.
The context is returned only when all the spring beans are initialized properly with post-init method executions.
Employee name is printed as ?Pankaj? because it was initialized in the post-init method.
When context is getting closed, beans are destroyed in the reverse order in which they were initialized i.e in LIFO
(Last-In-First-Out) order.
You can uncomment the code to get bean of type MyEmployeeService and confirm that output will be similar and follow all the
points mentioned above.
org.springframework.beans.factory.Aware is the root marker interface for all these Aware interfaces. All of the *Aware interfaces
are sub-interfaces of Aware and declare a single setter method to be implemented by the bean. Then spring context uses setter-based
dependency injection to inject the corresponding objects in the bean and make it available for our use.
Spring Aware interfaces are similar to servlet listeners with callback methods and implementing observer design pattern.
- ApplicationContextAware ? to inject ApplicationContext object, example usage is to get the array of bean definition names.
- BeanFactoryAware ? to inject BeanFactory object, example usage is to check scope of a bean.
- BeanNameAware ? to know the bean name defined in the configuration file.
- ResourceLoaderAware ? to inject ResourceLoader object, example usage is to get the input stream for a file in the classpath.
- ServletContextAware ? to inject ServletContext object in MVC application, example usage is to read context parameters
and attributes.
- ServletConfigAware ? to inject ServletConfig object in MVC application, example usage is to get servlet config parameters.
Let's see these Aware interfaces usage in action by implementing few of them in a class that we will configure as spring bean.
MyAwareService.java
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 81/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
package com.journaldev.spring.service;
import java.util.Arrays;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 82/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Override
throws BeansException {
System.out.println("setApplicationContext called");
+ Arrays.toString(ctx.getBeanDefinitionNames()));
@Override
System.out.println("setBeanName called");
+ beanName);
@Override
System.out.println("setBeanClassLoader called");
+ classLoader.getClass().getName());
@Override
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 83/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
System.out.println("setResourceLoader called");
+ resource.getFilename());
@Override
System.out.println("setImportMetadata called");
@Override
System.out.println("setEnvironment called");
@Override
System.out.println("setBeanFactory called");
+ beanFactory.isSingleton("employee"));
@Override
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 84/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
ApplicationEventPublisher applicationEventPublisher) {
System.out.println("setApplicationEventPublisher called");
spring-aware.xml
<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.xsd">
</beans>
SpringAwareMain.java
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 85/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
package com.journaldev.spring.main;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.journaldev.spring.service.MyAwareService;
ctx.getBean("myAwareService", MyAwareService.class);
ctx.close();
INFO: Loading XML bean definitions from class path resource [spring-aware.xml]
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 86/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
setBeanName called
setBeanClassLoader called
setBeanFactory called
setEnvironment called
setResourceLoader called
setApplicationEventPublisher called
setApplicationContext called
Console output of the test program is simple to understand, I won't go into much detail about that.
Instantiate- First the spring container finds the bean's definition from the XML file and instantiates the bean..
Populate properties- Using the dependency injection, spring populates all of the properties as specified in the bean definition..
Set Bean Name- If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method.
Set Bean factory- If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
Pre Initialization- Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls
postProcesserBeforeInitialization() method.
Initialize beans- If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method
declaration, the specified initialization method is called.
Post Initialization- If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods
will be called.
Ready to use- Now the bean is ready to use by the application.
Destroy- If the bean implements DisposableBean , it will call the destroy() method .
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 87/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
- A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean. An inner bean
definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans
are always anonymous and they are always scoped as prototypes.
- Spring offers four types of collection configuration elements which are as follows:
<list>: This helps in wiring i.e. injecting a list of values, allowing duplicates.
<set>: This helps in wiring a set of values but without any duplicates.
<map>: This can be used to inject a collection of name-value pairs where name and value can be of any type.
<props>: This can be used to inject a collection of name-value pairs where the name and value are both Strings.
- The process of injection spring bean dependencies while initializing it called Spring Bean Wiring.
Usually it's best practice to do the explicit wiring of all the bean dependencies, but spring framework also supports autowiring. We
can use @Autowired annotation with fields or methods for autowiring byType. For this annotation to work, we also need to enable
annotation based configuration in spring bean configuration file. This can be done by context:annotation-config
- For more details about @Autowired annotation, please read Spring Autowire Example.]
- The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to
automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory
without using <constructor-arg> and <property> elements.
- The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for
dependency injection:
no: This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to
do special for this wiring. This is what you already have seen in Dependency Injection chapter.
byName: Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to
byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the
configuration file.
byType: Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to
byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans
name in configuration file. If more than one such beans exist, a fatal exception is thrown.
constructor: Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor
argument type in the container, a fatal error is raised.
autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 88/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Overriding possibility: You can still specify dependencies using <constructor-arg> and <property> settings which will always
override autowiring.
Primitive data types: You cannot autowire so-called simple properties such as primitives, Strings, and Classes.
Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
this.db=db;
<beans>
</beans>
Explanation:
See line number 3 in MyBean, 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
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 89/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
file is matching with the property name in the MyBean or not, if yes it will wired automatically else unwired
Complete Example
Files required?
- java
- java
- java
- xml
Book.java
package technicalstack;
return bookname;
this.bookname = bookname;
return bookprice;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 90/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
this.bookprice = bookprice;
Categories.java
package technicalstack;
return name;
this.name = name;
return bk;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 91/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
this.bk = bk;
ClientLogic.java
package technicalstack;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 92/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Object o = factory.getBean("id1");
Categories wb = (Categories)o;
wb.show();
spconfig.xml
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
</bean>
</bean>
</beans>
Notes: We called id1 from ClientLogic.java [line number 15], and in spconfig.xml we have written autowire=byName, so first it will
checks for the class with id name bk [as we have written private Book bk in Categories.java ] and inserts bk class [ jaa4s.Book ]
properties into that object and then injects value ?General Books? into name property of Categories class.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 93/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Output
In this case, spring framework attempts to find out a bean in the configuration file, whose id is matching with the property type to be
wired. If a bean found with class as property type then that class object will be injected into that property by calling setter injection.
If no class found then that property remains un-wired, but never throws any exception just like before.
Files required?
- java
- java
- java
- xml
Book.java
package technicalstack;
return bookname;
this.bookname = bookname;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 94/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
return bookprice;
this.bookprice = bookprice;
Categories.java
package technicalstack;
return name;
this.name = name;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 95/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
return bk;
this.bk = bk;
ClientLogic.java
package technicalstack;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 96/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Object o = factory.getBean("id1");
Categories wb = (Categories)o;
wb.show();
spconfig.xml
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
</bean>
</bean>
</beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 97/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Notes: 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 in
Categories.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. [ read slowly 2 or 3 times]
Friends am using same application to show the difference between byName, byType, constructor, autodetect to avoid confusions [
Out put is same for all these 4 applications ;) ]
Files required?
- java
- java
- java
- xml
Book.java
package technicalstack;
return bookname;
this.bookname = bookname;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 98/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
return bookprice;
this.bookprice = bookprice;
Categories.java
package technicalstack;
this.bk=bk;
return name;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 99/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
this.name = name;
ClientLogic.java
package technicalstack;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 100/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Object o = factory.getBean("id1");
Categories wb = (Categories)o;
wb.show();
spconfig.xml
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
</bean>
</bean>
</beans>
Notes: Friends am not explaining this program, as i told you earlier Spring Autowiring constructor is similar to Spring Autowiring
byType but here we use constructor injection, please refer byType if you still have any doubts.
Output
Example On Spring Autowiring by Autodetect
Let 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 you
remember :-) well will see the example..
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 101/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Files required?
- java
- java
- java
- xml
Book.java
package technicalstack;
return bookname;
this.bookname = bookname;
return bookprice;
this.bookprice = bookprice;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 102/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Categories.java
package technicalstack;
this.bk=bk;
return name;
this.name = name;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 103/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
ClientLogic.java
package technicalstack;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Object o = factory.getBean("id1");
Categories wb = (Categories)o;
wb.show();
spconfig.xml
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 104/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
</bean>
</bean>
</beans>
- An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for
wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer
moves the configuration into the component class itself by using annotations on the relevant class, method, or field
declaration.
- Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we
will need to enable it in our Spring configuration file by configuring <context:annotation-config/>.
- This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit
property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected
bean property has not been populated.
In a production-scale application, there may be hundreds or thousands of beans declared in the IoC container, and the dependencies
between them are often very complicated. One of the shortcomings of setter injection is that it's very hard for you to check if all
required properties have been set or not. To overcome this problem, you can set ?dependency-check? attribute of <bean> and set one
of four attributes i.e. none, simple, objects or all (none is default option). Here this dependency checking feature can only check if
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 105/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
the properties have been set for that bean or not; but it can't check if their value is not null.
In real life application, you will not be interested in checking all the bean properties configured in your context files. Rather you
would like to check if particular set of properties have been set or not in some specific beans only. Spring's dependency checking
feature using ?dependency-check? attribute, will not able to help you in this case. So solve this problem, you can use @Required
annotation.
How to use @Required annotation
Use the @Required annotation over setter method of bean property in class file as below:
return designation;
@Required
this.designation = designation;
RequiredAnnotationBeanPostProcessor is a spring bean post processor that checks if all the bean properties with the @Required
annotation have been set. To enable this bean post processor for property checking, you must register it in the Spring IoC container.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 106/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Note that this processor can check only if the properties have been set, but can't check if their value is not null.
If any properties with @Required have not been set, a BeanInitializationException will be thrown by this bean post processor. For
example, if I will create an instance of EmployeeFactoryBean class without passing property value for designation, then I will get
this error.
applicationContext.xml
</bean>
Error Message
at
org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotat
ionBeanPostProcessor.java:156)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFac
tory.java:1202)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFa
ctory.java:537)
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 107/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
... 11 more
To correct this problem, pass the designation value by un-commenting the line in applicationContext.xml file.
In this way, you can use @Required annotation and RequiredAnnotationBeanPostProcessor class to verify that on context
initialization, all the required bean properties have been set properly.
The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The
@Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property
or methods with arbitrary names and/or multiple arguments.
E.g. You can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. When
Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.
You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be
autowired when creating the bean, even if no <constructor-arg> elements are used while configuring the bean in XML file.
@Autowired
this.spellChecker = spellChecker;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 108/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
spellChecker.checkSpelling();
<beans>
<context:annotation-config/>
</bean>
</bean>
</beans>
See below example, it will autowired a ?person? bean into customer's person property.
@Autowired
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 109/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</bean>
</bean>
Will Spring know which person bean should autowired? NO. When you run above example, it hits below exception :
To fix above problem, you need @Quanlifier to tell Spring about which bean should autowired.
@Autowired
@Qualifier("personA")
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 110/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
How to use Spring @Component, @Repository, @Service and @Controller Annotations, @RequestMapping?
In spring autowiring concepts, we learned about @Autowired annotation that it handles only wiring. You still have to define the
beans themselves so the container is aware of them and can inject them for you. But with @Component, @Repository, @Service
and @Controller annotations in place and after enabling automatic component scanning, spring will automatically import the beans
into the container so you don't have to define them explicitly with XML. These annotations are called Stereotype annotations as
well.
Before jumping to example use of these annotations, let's learn quick facts about these annotations which will help you in making a
better decision about when to use which annotation.
1) The @Component annotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and
pull it into the application context. To use this annotation, apply it over class as below:
@Component
...
2) Although above use of @Component is good enough but you can use more suitable annotation that provides additional benefits
specifically for DAOs i.e. @Repository annotation. The @Repository annotation is a specialization of the @Component annotation
with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions
(thrown from DAO methods) eligible for translation into Spring DataAccessException.
3) The @Service annotation is also a specialization of the component annotation. It doesn't currently provide any additional behavior
over the @Component annotation, but it's a good idea to use @Service over @Component in service-layer classes because it
specifies intent better. Additionally, tool support and additional behavior might rely on it in the future.
4) @Controller annotation marks a class as a Spring Web MVC controller. It too is a @Component specialization, so beans marked
with it are automatically imported into the DI container. When you add the @Controller annotation to a class, you can use another
annotation i.e. @RequestMapping; to map URLs to instance methods of a class.
In real life, you will face very rare situations where you will need to use @Component annotation. Most of the time, you will using
@Repository, @Service and @Controller annotations. @Component should be used when your class does not fall into either of
three categories i.e. controller, manager and dao.
If you want to define name of the bean with which they will be registered in DI container, you can pass the name in annotation itself
e.g. @Service (?employeeManager?).
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 111/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Above four annotation will be scanned and configured only when they are scanned by DI container of spring framework. To enable
this scanning, you will need to use ?context:component-scan? tag in your applicationContext.xml file. e.g.
The context:component-scan element requires a base-package attribute, which, as its name suggests, specifies a starting point
for a recursive component search. You may not want to give your top package for scanning to spring, so you should declare three
component-scan elements, each with a base-package attribute pointing to a different package.
When component-scan is declared, you no longer need to declare context:annotation-config, because autowiring is implicitly
enabled when component scanning is enabled.
As I already said that you use @Repository, @Service and @Controller annotations over DAO, manager and controller classes. But
in real life, at DAO and manager layer we often have separate classes and interfaces. Interface for defining the contract, and classes
for defining the implementations of contracts. Where to use these annotations? Let's find out.
Always use these annotations over concrete classes; not over interfaces.
Once you have these stereotype annotations on beans, you can directly use bean references defined inside concrete classes. Note the
references are of type interfaces. Spring DI container is smart enough to inject the correct instance in this case.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 112/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Repository ("employeeDao")
e.setId(1);
e.setFirstName("Lokesh");
e.setLastName("Gupta");
return e;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 113/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Service ("employeeManager")
@Autowired
EmployeeDAO dao;
return dao.createNewEmployee();
EmployeeController.java
@Controller ("employeeController")
@Autowired
EmployeeManager manager;
return manager.createNewEmployee();
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 114/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
EmployeeDTO.java
return id;
this.id = id;
return firstName;
this.firstName = firstName;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 115/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
return lastName;
this.lastName = lastName;
@Override
TestSpringContext.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.technicalstack.demo.service.EmployeeManager;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 116/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
System.out.println(controller.createNewEmployee());
Output:
startup date [Thu Jan 22 18:17:57 IST 2015]; root of context hierarchy
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 117/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
- The Spring Framework provide several call back methods to created a bean and some method to be destroy the bean in the
Spring IoC Container.
- The Spring Framework provides several marker interfaces to change the behavior of your bean in the container; they
include InitializingBean and DisposableBean. Implementing these interfaces will result in the container calling
afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization
and destruction.
- The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some
initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container,
some cleanup may be required.
- Beans can be notified after creation and all properties are set, and before they are destroyed and removed from the bean
container. This involves specifying the callback method to be invoked by the container. This is done in XML by specifying
attributes init-method="myinit", for the initialization callback, and destroy-method="mydestroy", for the destroy callback.
"myinit" and "cleanUp" are names of instance methods in the bean class.
Initialization callbacks:
Now we can implements above interface and do some initialization functionality with in this method. As below..
@Override
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 118/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Override
Generally, the use of the InitializingBean interface can be avoided (and is discouraged since it unnecessarily couples the code to
Spring). A bean definition provides support for a generic initialization method to be specified. In the case of XML-based
configuration metadata, this is done using the 'init-method' attribute. For example, the following definition:
In the case of XML-based configuration metadata, we can use the init-method attribute to specify the name of the method that has a
void no-argument signature. For example:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 119/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Now using Java annotations can also be used to declare life-cycle callbacks.
//init callback
@PostConstruct
//init callback
@PostConstruct
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 120/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Destruction callbacks:
Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container
containing it is destroyed. The DisposableBean interface specifies one method:
Now we can implements above interface and do some Destruction functionality with in this method. As below..
@Override
@Override
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 121/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Generally, the use of the DisposableBean marker interface can be avoided (and is discouraged since it unnecessarily couples the
code to Spring). A bean definition provides support for a generic destroy method to be specified. When using XML-based
configuration metadata this is done via the 'destroy-method' attribute on the . For example, the following definition:
In the case of XML-based configuration metadata, we can use the destroy-method attribute to specify the name of the method that
has a void no-argument signature. For example:
Now using Java annotations can also be used to declare life-cycle callbacks.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 122/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
//destroy callback
@PreDestroy
//destroy callback
@PreDestroy
If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop environment; you
register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your
singleton beans so that all resources are released. It is recommended that you do not use the InitializingBean or DisposableBean
callbacks, because XML configuration gives much flexibility in terms of naming your method.
Example:
Triangle.java
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 123/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
package com.dineshonjava.sdnext.callbackLifecycle.tutorial;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
/**
*/
this.pointA = pointA;
/**
*/
this.pointB = pointB;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 124/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
/**
*/
this.pointC = pointC;
@Override
@Override
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 125/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Point.java
package com.dineshonjava.sdnext.callbackLifecycle.tutorial;
private int x;
private int y;
/**
* @return the x
*/
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 126/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
return x;
/**
*/
this.x = x;
/**
* @return the y
*/
return y;
/**
*/
this.y = y;
package com.dineshonjava.sdnext.callbackLifecycle.tutorial;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 127/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
private int x;
private int y;
/**
* @return the x
*/
return x;
/**
*/
this.x = x;
/**
* @return the y
*/
return y;
/**
*/
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 128/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
this.y = y;
Following is the configuration file Spring.xml required for init and destroy methods.
Spring.xml
</bean>
</bean>
</bean>
</bean>
</beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 129/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Once you are done with creating source and bean configuration files, let us run the following application. If everything is fine with
your application, this will print the following message:
package com.dineshonjava.sdnext.callbackLifecycle.tutorial;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*/
/**
* @param args
*/
context.registerShutdownHook();
triangle.draw();
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 130/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
package com.dineshonjava.sdnext.callbackLifecycle.tutorial;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*/
/**
* @param args
*/
context.registerShutdownHook();
triangle.draw();
Output:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 131/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
INFO: Loading XML bean definitions from class path resource [spring.xml]
PointA is (0, 0)
PointB is (-20, 0)
PointC is (20, 0)
Default initialization and destroy methods: If you have too many beans having initialization and or destroy methods with the same
name, you don't need to declare init-method and destroy-method on each individual bean. Instead framework provides the flexibility
to configure such situation using default-init-method and default-destroy-method attributes on the <beans> element as follows:
spring.xml
</bean>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 132/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</bean>
</bean>
</bean>
</beans>
Now again run the application with above the configuration file we will get the following output:
Output:
INFO: Loading XML bean definitions from class path resource [spring.xml]
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 133/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
PointA is (0, 0)
PointB is (-20, 0)
PointC is (20, 0)
Spring 3.0 also adds annotation support for both task scheduling and asynchronous method execution. The @Scheduled annotation
can be added to a method along with trigger metadata.
In this post, I will show the means to use this feature in 4 different ways.
This annotation is used for task scheduling. The trigger information needs to be provided along with this annotation. You can use the
properties fixedDelay/fixedRate/cron to provide the triggering information.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 134/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
fixedRate makes Spring run the task on periodic intervals even if the last invocation may be still running.
fixedDelay specifically controls the next execution time when the last execution finishes.
cron is a feature originating from Unix cron utility and has various options based on your requirements.
@Scheduled(fixedDelay =30000)
@Scheduled(fixedRate=30000)
@Scheduled(cron="0 0 * * * *")
To use @Scheduled in your spring application, you must first define below xml namespace and schema location definition in your
application-config.xml file.
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
Above additions are necessary because we will be using annotation based configurations. Now add below definition to enable
annotations.
<task:annotation-driven>
Next step is to create a class and a method inside the class like below:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 135/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Scheduled(cron="*/5 * * * * ?")
Using @Scheduled annotation would in turn make Spring container understand that the method underneath this annotation would
run as a job. Remember that the methods annotated with @Scheduled should not have parameters passed to them. They should not
return any values too. If you want the external objects to be used within your @Scheduled methods, you should inject them into the
DemoService class using autowiring rather than passing them as parameters to the @Scheduled methods.
In this method, fixedDelay attribute is used with @Scheduled annotation. Alternatively, fixedRate can also be used.
package com.technicalstack.service;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 136/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Scheduled(fixedDelay = 5000)
//@Scheduled(fixedRate = 5000)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
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.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
</beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 137/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
In this method, cron attribute is used with @Scheduled annotation. Value of this attribute must be a cron expression.
package com.technicalstack.service;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
@Scheduled(cron="*/5 * * * * ?")
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 138/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
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.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
</beans>
In this method, cron attribute is used with @Scheduled annotation. Value of this attribute must be a cron expression as in previous
method, BUT, this cron expression will be defined in a properties file and key of related property will be used in @Scheduled
annotation.
This will decouple the cron expression from source code, thus making changes easy.
package com.technicalstack.service;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 139/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Scheduled(cron = "${cron.expression}")
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
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.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
</beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 140/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
In this method, cron expression is configured in properties file, and job scheduling is configured in configuration file using property
key for cron expression. Major change is that you do not need to use @Scheduled annotation on any method. Method configuration
is also done in application configuration file.
package com.technicalstack.service;
import java.util.Date;
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 141/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
xmlns:util="http://www.springframework.org/schema/util"
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.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
<task:scheduled-tasks>
</task:scheduled-tasks>
</beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 142/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
In this article, I will show you 10 best practices for writing spring XML configurations. Some of them may seem more necessary
practices rather than best practices, yet I have included them in here because they were highly related to the topic.
Note: Some other factors, such as application design, can impact the XML configuration decisions but I am focusing on the XML
configuration's readability and manageability only.
I always put more stress on code comments. The same goes for configuration files also. It is always very helpful to add a
configuration file header, which summarizes the beans/properties defined in the configuration files.
In spring configuration, you can add comments as adding xml comments or you can use the description element. For example:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 143/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<beans>
<description>
</description>
...
</beans>
One possible advantage of using the description tag is that some tools may pick up the description from this element to help you in
other places.
This is very important thing that you use same naming across all configuration files. Using clear, descriptive, and consistent name
conventions across the project increase the readability of configuration files and make it easy for other developers to avoid some
accidental bugs.
For bean ID, for example, you can follow the Java class field name convention. The bean ID for an instance of
EmployeeUpdateDAO would be employeeUpdateDAO. For large projects, you can add the package name as the prefix of the bean
ID. e.g. finance.employeeUpdateDAO.
I have also pointed out this feature earlier in previous post. I am again including it because it is essential and beneficial in long term
specially to reduce maintainbility. To refresh your memory, specifying version number in bean configuration files for referenced
schemas are not mandatory at all, and you can omit it. If fact, you should omit it all the time.
Spring automatically picks the highest version available from the project dependencies (jars). Also, as the project evolves and the
Spring version will be updated, we won't have to maintain all the XML config files to see the new features.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 144/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
Spring provides three types of dependency injection: constructor injection, setter injection, and method injection. Usually, we all use
first two types only.
<constructor-arg ref="datasource"/>
</bean>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 145/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</bean>
Constructor injection can provide the cheapest thread safety possible i.e. immutable object. Also it guarantees that object will not be
handed over to other beans without complete initialization.
Setter injection provides much desired capability i.e. flexibility or maintainability. If there are multiple attributes to set in a bean,
then creating a long list of parameters to constructor is not good idea. Also, if is possible that some of the attributes might be
optional.
Prefer flexibility. For immutability or thread safety, follow other programming rules.
5) Prefer type over index for constructor argument matching in Constructor injection
Better to avoid constructor injection and prefer to use setter injection for dependency injection. But, if you have an absolute
requirement to use constructor injection then always prefer parameter matching based on type rather than index.
</bean>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 146/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</bean>
As you can see that type based argument passing is more readable and less error prone. But, anytime there is any ambiguity in type
based argument passing, go to index based argument passing without hesitation.
Spring bean configuration semantics allow two forms for specifying property values and other bean references. One is expanded and
other is shorter form. Prefer shorter version.
<property name="datasource">
<ref bean="datasource"></ref>
<value>datasource</value>
</property>
</bean>
</bean>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 147/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Spring provides a very useful capability which you should use extensively in your project and i.e. bean definition re-usability. Here I
am not talking about bean references for setter injection. Rather I am pointing out the bean definition re-use in constructing other
beans.
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="concreteDataSourceOne"
parent="abstractDataSource"
p:url="${jdbc.databaseurlOne}"/>
<bean id="concreteDataSourceTwo"
parent="abstractDataSource"
p:url="${jdbc.databaseurlTwo}"/>
Spring allows two types of identifiers for a bean. Using attribute ?id? or by ?name?. You should always choose attribute id over
name. Usually it does neither increase readability nor benefit any performance scenario. It is just industry standard practice which all
fellow developers are following worldwide and even in your team.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 148/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Autowiring is a great feature if you can manage it in long term. Usually it is beneficial if you project is having very few beans and
you can almost remember them all in your memory as well.
As soon as project gets bigger, autowiring starts creating trouble in identifying correct dependency to use. The main drawback, I find
is not to have a overview of whole system binded together. This is where spring configuration files win. They can represent the
whole system to any new guy in couple of minutes.
Also, when you start debugging some complex issues then all information present in one place in configuration files, actually helps a
lot. Autowiring makes debugging harder.
When importing resources, XML config, properties, etc. Always use the classpath: or classpath*: prefix. This provides consistency
and clarity to the location of the resource. Not every feature of Spring behaves the same, classpath: guarantees consistency.
The classpath is determined by the build tool and IDE. Usually this is src/main/java for java code, src/main/resources for non-java
dependencies and for tests, src/test/java for java code and src/test/resources for non-java resources.
<import resource="classpath:/META-INF/spring/applicationContext-security.xml"/>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 149/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Often there are multiple configuration parameters related to runtime of application. They are passed to bean definitions in bean
configuration context file. DO not hard code them in config file. Instead externalize them to some properties file(s).
Better group them in separate files based on their usage or module i.e. all JDBC datasource related properties in jdbc.properties file.
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
/* file://jdbc.properties */
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=password
You should mostly set the dependency-check attribute on a bean definition to simple, objects, or all (default value is none i.e. no
checking), so that the container can do explicit dependency validation for you. It is useful when all of the properties (or certain
categories of properties) of a bean must be set explicitly, or via autowiring.
destroy-method="close"
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 150/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
p:driverClassName="${jdbc.driverClassName}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"
dependency-check="all" />
In above given example, the container will ensure that all properties/parameters to datasource are set in application initialization
time itself.
Finally, please do not abuse the motive behind introducing dependency injection. Java provide ?new? keyword to create new
objects. Use this wonderful keyword where DI is not necessary e.g. DTO objects. Don't try to play smarter. Just follow the basics.
<context:component-scan/> scan packages and classes within given base packages then find and register beans into
ApplicationContext.It does all things that <context:annotation-config/> is supposed to do.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 151/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
So if you have used annotation for example, @Autowired in your code and <context:component-scan/> in xml then You do not
require to use <context:annotation-config/>
<context:annotation-config /> only works on bean which are already registered on ApplicationContext.Doesn't matter they were
registered using xml or annotations.And it's for only some of annotation which I have mentioned below. So If you have used
@Autowired in your code and beans are registered either using xml or @Configuration then you can use
<contex:annotationconfig/>.
<context:annotation-config /> registers only 4 BeanPostProcessors which are part of the Spring Framework and They are follows as
:
- CommonAnnotationBeanPostProcessor :
Recognizes and processes the JSR 250 common annotations (@PostConstruct, @PreDestroy, @Resource)
- AutowiredAnnotationBeanPostProcessor :
Recognizes the Autowired related annotations (@Autowired, @Value, @Inject, @Qualifier, etc)
- RequiredAnnotationBeanPostProcessor :
- PersistenceAnnotationBeanPostProcessor :
<context:component-scan/> annotation is a super set of the <context:annotation-config/> meaning it registers all those bean post
processors which are mentioned above with addition of other annotation and also scan classes which are annotated with category of
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 152/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
You should either use only one, I usually prefer to use <context:component-scan/>
1) First big difference between both tags is that <context:annotation-config> is used to activate applied annotations in already
registered beans in application context. Note that it simply does not matter whether bean was registered by which mechanism e.g.
using <context:component-scan> or it was defined in application-context.xml file itself.
2) Second difference is driven from first difference itself. It does register the beans in context + it also scans the annotations inside
beans and activate them. So <context:component-scan> does what <context:annotation-config> does, but additionally it scan the
packages and register the beans in application context.
I will elaborate both tags in detail with some examples which will make more sense to us. For keeping the example to simple, I am
creating just 3 beans, and I will try to configure them in configuration file in various ways, then we will see the difference between
various configurations in console where output will get printed.
For reference, below are 3 beans. BeanA has reference to BeanB and BeanC additionally.
package com.technicalstack.beans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 153/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@SuppressWarnings("unused")
@Component
public BeanA(){
@Autowired
this.beanB = beanB;
@Autowired
this.beanC = beanC;
//Bean B
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 154/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
package com.technicalstack.beans;
import org.springframework.stereotype.Component;
@Component
public BeanB(){
//Bean C
package com.technicalstack.beans;
import org.springframework.stereotype.Component;
@Component
public BeanC(){
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 155/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
package com.technicalstack.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
Now let's start writing the configuration file "beans.xml" with variations. I will be omitting the schema declarations in below
examples, to keep focus on configuration itself.
Output:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 156/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
In this case, all 3 beans are created and no dependency in injected in BeanA because we didn't used any property/ref attributes.
</bean>
Output:
<context:annotation-config />
//No Output
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 157/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
As I told already, <context:annotation-config /> activate the annotations only on beans which have already been discovered and
registered. Here, we have not discovered any bean so nothing happened.
<context:annotation-config />
Output:
In above configuration, we have discovered the beans using <bean> tags. Now when we use <context:annotation-config />, it simply
activates @Autowired annotation and bean injection inside BeanA happens.
Output:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 158/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Above configuration does both things as I mentioned earlier in start of post. It does the bean discovery (searches for @Component
annotation in base package) and then activates the additional annotations (e.g. Autowired).
<context:annotation-config />
Output:
Strange !! With above configuration we are discovering beans two times and activating annotations two times as well. But output got
printed one time only. Why? Because spring is intelligent enough to register any configuration processing only once if it is
registered multiple tiles using same or different ways. Cool !!
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 159/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Spring JdbcTemplate
Spring JdbcTemplate internally uses JDBC api, but eliminates a lot of problems of JDBC API.
- We need to write a lot of code before and after executing the query, such as creating connection, statement, closing
resultset, connection etc.
- We need to perform exception handling code on the database logic.
- We need to handle transaction.
- Repetition of all these codes from one to another database logic is a time consuming task.
- Advantage of Spring JdbcTemplate
Spring JdbcTemplate eliminates all the above mentioned problems of JDBC API. It provides you methods to write the queries
directly, so it saves a lot of work and time.
Spring Jdbc Approaches
- JdbcTemplate
- NamedParameterJdbcTemplate
- SimpleJdbcTemplate
- SimpleJdbcInsert and SimpleJdbcCall
JdbcTemplate class
- It is the central class in the Spring JDBC support classes. It takes care of creation and release of resources such as creating
and closing of connection object etc. So it will not lead to any problem if you forget to close the connection.
- It handles the exception and provides the informative exception messages by the help of excepion classes defined in the
org.springframework.dao package.
- We can perform all the database operations by the help of JdbcTemplate class such as insertion, updation, deletion and
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 160/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
We are assuming that you have created the following table inside the Oracle10g database.
id number(10),
name varchar2(100),
salary number(10)
);
Employee.java
This class contains 3 properties with constructors and setter and getters.
package com.javatpoint;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 161/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
EmployeeDao.java
It contains one property jdbcTemplate and three methods saveEmployee(), updateEmployee and deleteEmployee().
package com.javatpoint;
import org.springframework.jdbc.core.JdbcTemplate;
this.jdbcTemplate = jdbcTemplate;
'"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";
return jdbcTemplate.update(query);
return jdbcTemplate.update(query);
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 162/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
return jdbcTemplate.update(query);
applicationContext.xml
- The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection
URL, username and password.
- There are a property named datasource in the JdbcTemplate class of DriverManagerDataSource type. So, we need to
provide the reference of DriverManagerDataSource object in the JdbcTemplate class for the datasource property.
Here, we are using the JdbcTemplate object in the EmployeeDao class, so we are passing it by the setter method but you can use
constructor also.
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 163/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</bean>
</bean>
</bean>
</beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the saveEmployee() method. You can also call
updateEmployee() and deleteEmployee() method by uncommenting the code as well.
package com.javatpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 164/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
System.out.println(status);
System.out.println(status);
*/
e.setId(102);
int status=dao.deleteEmployee(e);
System.out.println(status);*/
We can easily fetch the records from the database using query() method of JdbcTemplate class where we need to pass the instance
of ResultSetExtractor
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 165/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
ResultSetExtractor Interface
ResultSetExtractor interface can be used to fetch records from the database. It accepts a ResultSet and returns the list.
It defines only one method extractData that accepts ResultSet instance as a parameter. Syntax of the method is given below:
Assuming that you have created the following table inside the Oracle10g database.
id number(10),
name varchar2(100),
salary number(10)
);
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 166/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Employee.java
This class contains 3 properties with constructors and setter and getters. It defines one extra method toString().
package com.javatpoint;
EmployeeDao.java
package com.javatpoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 167/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
this.template = template;
@Override
DataAccessException {
while(rs.next()){
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
list.add(e);
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 168/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
return list;
});
ApplicationContext.xml
- The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection
URL, username and password.
- There are a property named datasource in the JdbcTemplate class of DriverManagerDataSource type. So, we need to
provide the reference of DriverManagerDataSource object in the JdbcTemplate class for the datasource property.
- Here, we are using the JdbcTemplate object in the EmployeeDao class, so we are passing it by the setter method but you can
use constructor also.
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 169/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</bean>
</bean>
</bean>
</beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the getAllEmployees() method of EmployeeDao class.
package com.javatpoint;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 170/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
List<Employee> list=dao.getAllEmployees();
for(Employee e:list)
System.out.println(e);
- Like ResultSetExtractor, we can use RowMapper interface to fetch the records from the database using query() method of
JdbcTemplate class. In the execute of we need to pass the instance of RowMapper now.
RowMapper Interface
- RowMapper interface allows to map a row of the relations with the instance of user-defined class. It iterates the ResultSet
internally and adds it into the collection. So we don't need to write a lot of code to fetch the records as ResultSetExtractor.
- RowMapper saves a lot of code becuase it internally adds the data of ResultSet into the collection.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 171/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
- It defines only one method mapRow that accepts ResultSet instance and int as the parameter list. Syntax of the method is
given below:
We are assuming that you have created the following table inside the Oracle10g database.
id number(10),
name varchar2(100),
salary number(10)
);
Employee.java
This class contains 3 properties with constructors and setter and getters and one extra method toString().
package com.javatpoint;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 172/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
EmployeeDao.java
package com.javatpoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
this.template = template;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 173/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
@Override
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
return e;
});
applicationContext.xml
- The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection
URL, username and password.
- There are a property named datasource in the JdbcTemplate class of DriverManagerDataSource type. So, we need to
provide the reference of DriverManagerDataSource object in the JdbcTemplate class for the datasource property.
- Here, we are using the JdbcTemplate object in the EmployeeDao class, so we are passing it by the setter method but you can
use constructor also.
<beans
xmlns="http://www.springframework.org/schema/beans"
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 174/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</bean>
</bean>
</bean>
</beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the getAllEmployeesRowMapper() method of
EmployeeDao class.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 175/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
package com.javatpoint;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
List<Employee> list=dao.getAllEmployeesRowMapper();
for(Employee e:list)
System.out.println(e);
Spring NamedParameterJdbcTemplate
- Spring provides another way to insert data by named parameter. In such way, we use names instead of ?(question mark). So
it is better to remember the data for the column.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 176/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
In this example,we are going to call only the execute method of NamedParameterJdbcTemplate class. Syntax of the method is as
follows:
id number(10),
name varchar2(100),
salary number(10)
);
Employee.java
This class contains 3 properties with constructors and setter and getters.
package com.javatpoint;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 177/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
EmployeeDao.java
package com.javatpoint;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import java.util.*;
NamedParameterJdbcTemplate template;
this.template = template;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 178/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
map.put("id",e.getId());
map.put("name",e.getName());
map.put("salary",e.getSalary());
template.execute(query,map,new PreparedStatementCallback() {
@Override
return ps.executeUpdate();
});
applicationContext.xml
- The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection
URL, username and password.
- There are a property named datasource in the NamedParameterJdbcTemplate class of DriverManagerDataSource type. So,
we need to provide the reference of DriverManagerDataSource object in the NamedParameterJdbcTemplate class for the
datasource property.
- Here, we are using the NamedParameterJdbcTemplate object in the EmployeeDao class, so we are passing it by the
constructor but you can use setter method also.
<beans
xmlns="http://www.springframework.org/schema/beans"
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 179/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</bean>
<bean id="jtemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="ds"></constructor-arg>
</bean>
<constructor-arg>
<ref bean="jtemplate"/>
</constructor-arg>
</bean>
</beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 180/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
SimpleTest.java
This class gets the bean from the applicationContext.xml file and calls the save method.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
EmpDao dao=(EmpDao)factory.getBean("edao");
dao.save(new Emp(23,"sonoo",50000));
Spring SimpleJdbcTemplate
Spring 3 JDBC supports the java 5 feature var-args (variable argument) and autoboxing by the help of SimpleJdbcTemplate class.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 181/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
- SimpleJdbcTemplate class wraps the JdbcTemplate class and provides the update method where we can pass arbitrary
number of arguments.
We should pass the parameter values in the update method in the order they are defined in the parameterized query.
We are assuming that you have created the following table inside the Oracle10g database.
id number(10),
name varchar2(100),
salary number(10)
);
Employee.java
This class contains 3 properties with constructors and setter and getters.
package com.javatpoint;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 182/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
EmployeeDao.java
It contains one property SimpleJdbcTemplate and one method update. In such case, update method will update only name for the
corresponding id. If you want to update the name and salary both, comment the above two lines of code of the update method and
uncomment the 2 lines of code given below.
package com.javatpoint;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
SimpleJdbcTemplate template;
this.template = template;
return template.update(query,e.getName(),e.getId());
//return template.update(query,e.getName(),e.getSalary(),e.getId());
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 183/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
applicationContext.xml
- The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection
URL, username and password.
- There are a property named datasource in the SimpleJdbcTemplate class of DriverManagerDataSource type. So, we need to
provide the reference of DriverManagerDataSource object in the SimpleJdbcTemplate class for the datasource property.
- Here, we are using the SimpleJdbcTemplate object in the EmployeeDao class, so we are passing it by the constructor but
you can use setter method also.
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</bean>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 184/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<constructor-arg ref="ds"></constructor-arg>
</bean>
<constructor-arg>
<ref bean="jtemplate"/>
</constructor-arg>
</bean>
</beans>
SimpleTest.java
This class gets the bean from the applicationContext.xml file and calls the update method of EmpDao class.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 185/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
EmpDao dao=(EmpDao)factory.getBean("edao");
System.out.println(status);
Spring provides API to easily integrate Spring with ORM frameworks such as Hibernate, JPA(Java Persistence API), JDO(Java Data
Objects), Oracle Toplink and iBATIS.
There are a lot of advantage of Spring framework in respect to ORM frameworks. There are as follows:
- Less coding is required: By the help of Spring framework, you don't need to write extra codes before and after the actual
database logic such as getting the connection, starting transaction, commiting transaction, closing connection etc.
- Easy to test: Spring's IoC approach makes it easy to test the application.
- Better exception handling: Spring framework provides its own API for exception handling with ORM framework.
- Integrated transaction management: By the help of Spring framework, we can wrap our mapping code with an explicit
template wrapper class or AOP style method interceptor.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 186/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
- But if we are going to integrate the hibernate application with spring, we don't need to create the hibernate.cfg.xml file. We
can provide all the information in the applicationContext.xml file.
- The Spring framework provides HibernateTemplate class, so you don't need to follow so many steps like create
Configuration, BuildSessionFactory, Session, beginning and committing transaction etc.
//creating configuration
cfg.configure("hibernate.cfg.xml");
SessionFactory factory=cfg.buildSessionFactory();
Session session=factory.openSession();
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 187/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
Transaction t=session.beginTransaction();
t.commit();//transaction is commited
session.close();
As you can see in the code of sole hibernate, you have to follow so many steps.
Now, you don't need to follow so many steps. You can simply write this:
hibernateTemplate.save(e1);
In this example, we are using the Oracle as the database, but you may use any database. Let's create the table in the oracle database
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 188/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
"SALARY" FLOAT(126),
2) Employee.java
It is a simple POJO class. Here it works as the persistent class for hibernate.
package com.javatpoint;
3) employee.hbm.xml
This mapping file contains all the information of the persistent class.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 189/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
4) EmployeeDao.java
It is a java class that uses the HibernateTemplate class method to persist the object of Employee class.
package com.javatpoint;
import org.springframework.orm.hibernate3.HibernateTemplate;
import java.util.*;
HibernateTemplate template;
this.template = template;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 190/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
template.save(e);
template.update(e);
template.delete(e);
Employee e=(Employee)template.get(Employee.class,id);
return e;
list=template.loadAll(Employee.class);
return list;
5) applicationContext.xml
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 191/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
- In this file, we are providing all the informations of the database in the BasicDataSource object. This object is used in the
LocalSessionFactoryBean class object, containing some other informations such as mappingResources and
hibernateProperties. The object of LocalSessionFactoryBean class is used in the HibernateTemplate class. Let's see the code
of applicationContext.xml file.
hibernate template
File: applicationContext.xml
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</bean>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 192/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</bean>
</bean>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 193/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</beans>
6) InsertTest.java
This class uses the EmployeeDao class object and calls its saveEmployee method by passing the object of Employee class.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
EmployeeDao dao=(EmployeeDao)factory.getBean("d");
e.setId(114);
e.setName("varun");
e.setSalary(50000);
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 194/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
dao.saveEmployee(e);
Now, if you see the table in the oracle database, record is inserted successfully.
You can enable many hibernate properties like automatic table creation by hbm2ddl.auto etc. in applicationContext.xml file. Let's
see the code:
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
If you write this code, you don't need to create table because table will be created automatically.
ApplicationContext context =
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 195/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
"Spring-Common.xml"});
This way is not properly organized.It will be better if we can import multiple xml into one xml and then define single main XML
into ClassPathXmlApplicationContext
Ex.
<import resource="common/Spring-Core.xml"/>
<import resource="connection/Spring-Common.xml"/>
</beans>
Load Spring-Main.xml as
Spring MVC
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 196/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
All the above mentioned components ie. HandlerMapping, Controller and ViewResolver are parts ofWebApplicationContext which
is an extension of the plain ApplicationContext with some extra features necessary for web applications.
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 197/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
</web-app>
Upon initialization of HelloWeb DispatcherServlet, the framework will try to load the application context from a file named
[servlet-name]-servlet.xml located in the application's WebContent/WEB-INF directory. In this case our file will be
HelloWeb-servlet.xml.
Next, <servlet-mapping> tag indicates what URLs will be handled by the which DispatcherServlet. Here all the HTTP requests
ending with .jsp will be handled by the HelloWeb DispatcherServlet.
If you do not want to go with default filename as [servlet-name-servlet.xml and default location as WebContent/WEB-INF,
you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as
follows:
<web-app...>
....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>
</context-param>
<listener>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 198/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application's WebContent/WEB-INF
directory:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
</bean>
</beans>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 199/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
- The [servlet-name-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined
with the same name in the global scope.
The <context:component-scan...> tag will be use to activate Spring MVC annotation scanning capability which allows to
make use of annotations like @Controller and @RequestMapping
- The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above defined rule, a
logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp .
Defining a Controller
DispatcherServlet delegates the request to the controllers to execute the functionality specific to it.
The @Controller annotation indicates that a particular class serves the role of a controller.
The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.
@Controller
@RequestMapping("/hello")
@RequestMapping(method = RequestMethod.GET)
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 200/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
return "hello";
- @RequestMapping(method = RequestMethod.GET) is used to declare the printHello() method as the controller's default
service method to handle HTTP GET request. You can define another method to handle any POST request at the same URL.
- Spring MVC supports many types of views for different presentation technologies. These include - JSPs, HTML, PDF,
Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom and RSS feeds, JasperReports etc. But most commonly we
use JSP templates written with JSTL. So let us write a simple hello view in /WEB-INF/hello/hello.jsp:
<html>
<head>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
Here ${message} is the attribute which we have setup inside the Controller. You can have multiple attributes to
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 201/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
In this example show how to write a simple web based application which makes use of HTML forms using Spring Web MVC
framework. To start with it, let us have working STS IDE in place and follow the following steps to develop a Dynamic Form based
Web Application using Spring Web Framework:
Step 1: Create a Dynamic Web Project with a name SpringEmployeeApp and create a package com.dineshonjava.controller under
the src folder in the created project.
Step 2: Add below mentioned Spring 3.0 libraries and other libraries into the folder WebRoot/WEB-INF/lib.
commons-logging-1.1.1.jar
org.springframework.asm-3.0.0.jar
org.springframework.beans-3.0.0.jar
org.springframework.context-3.0.0.jar
org.springframework.core-3.0.0.jar
org.springframework.expression-3.0.0.jar
org.springframework.web.servlet-3.0.0.jar
org.springframework.web-3.0.0.jar
spring-web.3.0.0.jar
Step 3: Create a Java class EmployeeController and Employee under the com.dineshonjava.controller com.dineshonjava.bean
package respectively.
Step 4: Create Spring configuration files Web.xml and sdnext-servlet.xml under the WebRoot/WEB-INF/ folder.
Step 5: Create a sub-folder with a name views under the WebRoot/WEB-INF folder. Create a view file employeeForm.jsp and
employeeDetail.jsp under this sub-folder.
Step 6: The final step is to create the content of all the source and configuration files name sdnext-servlet.xml under the sub-folder
WebRoot/WEB-INF/config and export the application as explained below.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 202/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
- Spring 3.0
- Java 1.6
- Tomcat 7
- JSTL 1.2
- STS Java EE IDE
- Web Application Structure:
Employee.java
view plainprint?
package com.dineshonjava.emp.bean;
/**
*/
/**
*/
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 203/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
return empId;
/**
*/
this.empId = empId;
/**
*/
return name;
/**
*/
this.name = name;
/**
*/
return salary;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 204/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
/**
*/
this.salary = salary;
/**
*/
return age;
/**
*/
this.age = age;
EmployeeController.java
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 205/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
view plainprint?
package com.dineshonjava.emp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.dineshonjava.emp.bean.Employee;
/**
*/
@Controller
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 206/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
model.addAttribute("name", employee.getName());
model.addAttribute("age", employee.getAge());
model.addAttribute("empId", employee.getEmpId());
model.addAttribute("salary", employee.getSalary());
return "employeeDetail";
Here the first service method employee(), we have passed a blank Employee object in the ModelAndView object with name
"command" because the spring framework expects an object with name "command" if you are using tags in your JSP file. So when
employee() method is called it returns employeeForm.jsp view.
Second service method addEmployee() will be called against a POST method on the sdnext/addEmployee URL. You will prepare
your model object based on the submitted information. Finally a "employeeDetail" view will be returned from the service method,
which will result in rendering employeeDetail.jsp
view plainprint?
<display-name>SpringMVCHelloWorld</display-name>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 207/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<servlet>
<servlet-name>sdnext</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/sdnext-servlet.xml</param-value></init-par
am>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
view plainprint?
<beans xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
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
http://www.springframework.org/schema/mvc
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 208/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="com.dineshonjava.emp.controller">
</context:component-scan>
</bean>
</beans>
employeeForm.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
&body>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 209/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
<h2>
<table><tbody>
</tbody></table>
</form:form>
</body>
</html>
employeeDetail.jsp
view plainprint?
pageEncoding="ISO-8859-1"%>
<html>
<head>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 210/211 |
This page was exported from - TechnicalStack
Export date: Thu Oct 27 17:36:04 2022 / +0000 GMT
</head>
<body>
<h2>
<table border="1"><tbody>
</tbody></table>
</body>
</html>
Once you are done with creating source and configuration files, export your application. Right click on your application and use
Export-> WAR File option and save your SpringEmplyeeApp.war file in Tomcat's webapps folder.
Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser.
Now try a URL http://localhost:8080/sdnext/employee and you should see the following result if everything is fine with your Spring
Web Application:
After submitting required information click on submit button to submit the form. You should see the following result if everything is
fine with your Spring Web Application:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 211/211 |