2. ï Introduction
ï Injection
ï Aspect Dependency Oriented Programming
ï Bean Factory
ï Wiring Objects
ï Spring MVC
ï Spring DAO
3. Introduction
ï Spring Framework
ï is a J2EE Framework
ï that provides a lightweight container
ï for dependency injection
ï and Aspect oriented Programming (AOP)
Now what was that, again?
4. DI or IOC
ï Dependency injection or Inversion of control
ï Alternative to Service Locator
Locate your own dependencies
Let the framework do the dirty job for you
7. Using BeanFactory
public static void main (String args []){
BeanFactory factory = new XmlBeanFactory (new
FileInputStream (âbean-config.xmlâ));
MyBean mybean = (MyBean) factory.getBean
(âmyBeanâ);
mybean.methodx():
}
A Web Application may never need to use code such as
the one shown above as the framework does it all for
us.
9. Wiring Objects
ï Spring provides for declarative wiring of objects
ï Declaring a bean
ï Declaring beans as singleton or prototype
ï Declaring init and destroy methods
ï Injecting values into beans properties
ï Injecting other beans as properties
ï Injecting arrays and collections as properties
Spring book
This book on Spring is marvelous ! Now I am a wiring expert too
!
10. Declaring beans
<beans>
<bean id=âxâ class=âyâ/>
</beans>
When using the id attribute, special characters are not
permitted. Spring therefore allows the use of an
alternative attribute: name
<bean name=âxâ class=âyâ/>
11. To singleton or not
ï Beans are instantiated as Singletons by default. This is how
we can override the default :
<beans>
<bean id=âxâ class=âyâ singleton=âfalseâ/>
</beans>
12. Init and destroy
ï As Spring manages the bean lifecycle, it allows us to
specify the init and destroy methods declaratively.
<beans>
<bean id=âxâ class=âyâ init-method=âaâ/>
<bean id=âpâ class=âqâ destroy-method=âbâ/>
</beans>
13. Alternative
ï Spring defines the following interfaces
ï InitializingBean
ï DisposableBean
ï Beans implementing these interfaces are assured that
the methods defined in these interfaces are called back
by Spring during initialization and destruction.
ï This is thus an alternative to the init and destroy
method declaration in the config.xml
15. Setter injection
ï Setter based injection allows us to inject values into
bean properties through the setter methods.
ï These values may be
ï Primitive Types
ï Strings
ï Beans
ï Arrays
ï Collections
ï Property
16. Primitive Types
<bean id=âxâ class=âyâ>
<property name=âageâ>
<value>26</value>
</property>
</bean>
This sets â26â to the property age
17. Strings
<bean id=âxâ class=âyâ>
<property name=ânmâ>
<value>val</value>
</property>
</bean>
This sets âvalâ to the property nm
<bean id=âxâ class=âyâ>
<property name=âpqâ>
<value></value>
</property>
</bean>
This sets an empty string ââ to the property pq
22. Sets
<bean id=âxâ class=âyâ>
<property name=ânmâ>
<set>
<value>pqr</value>
<value>xyz</value>
<value>abc</value>
</set>
</property>
</bean>
For a set consisting of beans use the <ref bean> tag
23. Maps
<beans>
<bean id=âxâ class=âyâ>
<property name=ânmâ>
<map>
<entry key=âk1â>
<value>val1</value>
</entry>
<entry key=âk2â>
<ref bean=âaâ />
Spring limits the user to declare keys as Strings only
</entry>
</map>
</property>
</bean>
<bean id=âaâ class=âpâ/>
</beans>
25. Constructor injection
Spring allows for injection via constructors
Below is example of constructor based injection
<beans>
<bean id=âmyClassâ class=âdemo.MyClassâ>
<constructor-arg>
<value>42</value>
</constructor-arg>
</bean>
</beans>
26. Constructor injection
Spring allows for injection via constructors
Below is example of constructor based injection for setting multiple
arguments
<beans>
<bean id=âmyClassâ class=âdemo.MyClassâ>
<constructor-arg index=â1â>
<value>42</value>
</constructor-arg>
<constructor-arg index=â2â>
<ref bean=âtestClassâ/>
</constructor-arg>
</bean>
</beans>
27. Constructor injection - Advantage
The data members of the class are set only once at the
time of creation/instantiation of the object. There are
no public setter methods that are exposed to the
outside world and through which the state of an object
can be changed.
Thus the object is immutable.
28. Constructor injection - Disadvantage
The xml declaration for constructor based injection is
complex and the developer has to ensure that there are
no ambiguities in the parameters
29. Autowiring
ï Spring has autowiring capabilities
<beans>
<bean id=âxâ class=âyâ autowire=âbyNameâ>
</bean>
</beans>
The dependencies need not be defined in the xml explicitly. With autowire by
Name option if we ensure that the name of id in xml, and name of the
properties in the java class matches then the Spring framework automatically
invokes setter methods.
Note: byName should be used with only setter based injection
32. Spring Web
ï Web utilities
Spring tags for use in html/jsp
ï Multipart functionality
ï Integration with Struts framework
In one application the struts can be used in web MVC layer and
integrated with other Spring components in the application
bigfile.xml
part1.xml
part2.xml
part3.xml
36. Life cycle of a Request
1.
2.
3.
4.
5.
6.
7.
The client typically web browser send request (1)
The first component to receive is DispatcherServlet. All the
requests goes through single front controller servlet.
DispacherServlet queries HandlerMapping. This is a mapping
of URLs and Controller objects defined in configuration xml
Dispatcher servlet dispatches request to Controller to perform
business logic
Controller returns the model and the view. The model is the
data that need to be displayed in the view. The view is a logical
name that is mapped to the .jsp file that will render the view.
This is defined in the xml mapping file
Controller send request to ViewResolver to resolve which .jsp
to render for which view
Finally the view is rendered
37. Configuring the Dispatcher Servlet
Dispatcher servlet is MVCâs front controller. Like any servlet
it must be configured in Spring application context
Example:
<servlet>
<servlet-name>testapp</servlet-name>
<servletclass>org.springframework.web.servlet.DispatcherServl
et</servlet-class>
<load-on-startup>1</load-on-startup>
<servlet>
Since the dispatcher servletâs name is testapp the servlet will load the application context from a file named
âtestapp-servlet.xmlâ
38. Spring Web MVC - Controller
There are following main Controller types
ï Abstract Controller
ï Simple Form Controller
ï Multi Action Controller
All the above are implementation classes for the Controller
Interface
39. Abstract Controller
ï This controller is used when the view/GUI has to be read
only.
ï No data is entered in the screen
Example
public class ListCircuitsController extends AbstractController{
public ModelAndView handleRequestInternal(HttpServletRequest
req,HttpServletResponse res){
Collection circuits=circuitService.getAllCircuits();
return new ModelAndView(âcircuitListâ,âcircuitsâ, circuits);
}
The first argument âcircuitListâ is the name of the view to which
the controller is associated.
The second argument is the name of the model object which holds the
third argument circuits object.
40. Declaring View Resolver
View Resolver resolves the logical view name returned by controller to the jsp file that
renders the view. Of the various view resolvers InternalResourceViewResolver is
simplest for rendering jsp
Example
<!-- view-resolver -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResource
ViewResolver">
<property name="prefix">
<value>/WEB-INF/ui/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- /view-resolver -->
41. Mapping requests to Controllers
SimpleUrlHandlerMapping is one of the straight forward Springâs handler
mapping. This maps the URL patterns to controllers.
Example
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.Simple
UrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/forum.do">
<ref bean="forumController" />
</entry>
</map>
</property>
</bean>
<!-- /UrlMapping -->
42. Simple Form Controller
ï This controller is used for GUI which have a data entry
form to be filled in and submitted by the user.
ï The controller is responsible for â
ï Displaying the form for data entry
ï Validating data entered by the user
ï Redisplaying the form on error with error message
ï Submitting the data
ï Displaying the success page
44. Simple Form Controller -code
public class EnterCircuitDetailsController extends
SimpleFormController{
public EnterCircuitDetails(){
setCommandClass(Circuit.class);
}
Protected void doSubmitAction(Object command) throws
Exception{
Circuit circuit=(Circuit) command;
circuitService.createCircuit(circuit);
}
Private CircuitService circuitservive;
Public void setCircuitService(CircuitService
circuitservice){
this.circuitService=circuitService;
}
}
45. Simple Form Controller -Configuration
ï The details of configuration of the view is as below:
<bean id=âenterCircuitDetailsController" class="
com.circuit.mvc.CircuitDetailsController">
<property name=âcircuitService" ref=âcircuitService" />
<property
name="formView"><value>circuitForm</value></property>
<property
name="successView"><value>circuitCreated.do</value></pr
operty>
</bean>
46. Simple Form Controller -explained
ï As per the above example EnterCircuitDetailsController
displays a form for taking the details of the circuit that
need to be created as well as processes the data that is
entered.
ï The doSubmitAction() method handles form submission
and takes details of the form from Circuit object
ï The doSubmitAction() does not return ModelAndView
object and hence with this we will not be able to send any
data to the view. If a particular view need to be displayed
with some data in it we need to use the onSubmit() method
instead.
47. Simple Form Controller -explained
ï SimpleFormController is designed to keep view details out of
the controllerâs code. The formView represents the logical
name of the view that is to be displayed when the Controller
gets a GET request or there are any errors on the form. The
success view represents the logical name of the view to be
displayed when form is submitted successfully. The view
resolver will use this to render the actual view to the user.
48. Simple Form Controller
ï Below is an example of onSubmit method
protected ModelAndView onSubmit(Object command,
BindException errors) throws Exception {
Circuit circuit = (Circuit) command;
circuitService.createCircuit(circuit);
return new ModelAndView(getSuccessView(),âcircuit", circuit);
}
49. Multi Action Controller
ï These controllers are used to handle multiple actions in a single
controller. Each action is handled by a different method within
the controller.
ï The specific method that needs to be called in the Action
controller based on the type of resolver.
ï The below example shows that we are using methodName
Resolver
<bean id="multiactionController"
class="com. mvc.ListCircuitsController">
<property name="methodNameResolver">
<ref bean="methodNameResolver"/>
</property>
</bean>
50. Multi Action Controller
ï There are two types of method name resolvers like
ParameterMethodNameResolver and PropertiesMethodNameResolver.
This will ensure that the appropriate method in the Multiaction
Controller is called based on the parameter name passed in the request.
The parameter name will need to be same as the method name in the
MultiActionForm Controller. Below is the configuration that need to be
done
<bean id="methodNameResolver" class="org.springframework.web.
servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName">
<value>action</value>
</property>
</bean>
51. Multi Action Controller
ï Example: If we are accessing the URL
âhttp://âŠ/listCircuits.htm?action=circuitsByDateâ the
method name circuitsByDate() is called in the
MultiActionController since we have configured the name
resolver to be based on the parameter passed in the request.
52. Spring Web MVC-Validator
ï Spring provides a Validator Interface that is used for
validating objects
ï For Example: In the example of a simple form
controller in previous slides in which there is a
command object âcircuitâ which needs to be validated
or in other words we need to validate that the circuit
details entered by the user are correct. In that case the
class Circuit should implement the Validator interface
53. Spring Web MVC-Validator
ï Validator Interface has the following methods defined
in it
public interface Validator {
void validate(Object obj, Errors errors);
boolean supports(Class class);
}
54. Spring Web MVC-Validator Code
ï Sample code below explains how Validator Interface is
implemented to perform validations. We write a class
ValidateCktDetails for validating circuit details entered by user
public class CircuitValidator implements Validator {
public boolean supports(Class class) {
return class.equals(Circuit.class);
}
public void validate(Object command, Errors errors) {
Circuit circuit = (Circuit) command;
ValidationUtils.rejectIfEmpty(
errors, âcircuitType", "required. circuitType ", âCircuit Type is mandatory
for creating a circuit");
}
55. Web MVC-Validator Code Explained
ï The framework uses support() method to check if the
Validator can be used for a given class
ï The validate() methods can validate all the attributes of the
object that is passed into validate() method and reject invalid
values through Errors object
56. Spring Web MVC-Validator
ï The only other thing to do is to use the
CircuitValidator with
EnterCircuitDetailsController which can be
done by wiring the bean
<bean id=âenterCircuitDetailsController" class=
"com.circuit.mvc.CircuitDetailsController">
<property name="validator">
<bean class="com.validate.mvc.CircuitValidator"/>
</property>
</bean>
57. Spring Web MVC
ï When a user enters the circuit details, if all of the
required properties are set and circuit type is not
empty, then EnterCircuitDetailsControllerâs
doSubmitAction() will be called. However, if
CircuitValidator rejects any of the fields, then the user
will be returned to the form view to correct the errors.
61. Spring DAO-JDBC
ï Assuming that the persistence layer in an application is
JDBC. In that case we need to use
DataSourceTrnsactionManger which will manage
transactions on a single JDBC Data Source
ï The source code explains the use of Transaction Manager.
The transaction manager takes care of managing the
transactions.
<bean id="transactionManager" class="org.springframework.jdbc.
datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
62. Spring DAO-JDBC
ï The dataSource property is set with a reference to a bean named
datasource
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@111.21.15.234:1521:TESTSID</value>
</property>
<property name="username">
<value>test</value>
</property>
<property name="password">
<value>test</value>
</property>
</bean>
Hinweis der Redaktion
Life cycle of a RequestThe client typically web browser send request (1)The first component to receive is DispatcherServlet. All the requests goes through single front controller servlet.DispacherServlet queries HandlerMapping. This is a mapping of URLs and Controller objects defined in configuration xmlDispatcher servlet dispatches request to Controller to perform business logicController returns the model and the view. The model is the data that need to be displayed in the view. The view is a logical name that is mapped to the .jsp file that will render the view. This is defined in the xml mapping fileController send request to ViewResolver to resolve which .jsp to render for which viewFinally the view is rendered