SlideShare ist ein Scribd-Unternehmen logo
1 von 63
By- Vinay Kumar
 Introduction
 Injection
 Aspect Dependency Oriented Programming
 Bean Factory
 Wiring Objects
 Spring MVC

 Spring DAO
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?
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
AOP
 Aspect oriented programming
 Cross cutting concerns
 Transaction, Security and Logging requirements
BeanFactory






Interface BeanFactory
BeanFactory creates beans
getBean() method
Implementation classes like the XmlBeanFactory
Methods:
 getBean()
 isSingleton()
 getType()

 getAliases()
 containsBean()

This is how a BeanFactory looks like
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.
ApplicationContext
 Extends the BeanFactory
 Adds the following methods:
 getResource()
 getMessage()
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
!
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”/>
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>
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>
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
Dependency Injection
 Spring allows for:
 Setter based injection
 Constructor based injection
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
Primitive Types
<bean id=“x” class=“y”>
<property name=“age”>
<value>26</value>
</property>
</bean>

This sets “26” to the property age
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
Null values
<bean id=“x” class=“y”>
<property name=“nm”>
<value><null/></value>
</property>
</bean>
Bean
<beans>
<bean id=“myClass” class=“demo.MyClass”>
<property name=“display”>
<ref bean=“a” />
</property>
</bean>
<bean id=“a” class=“util.TestClass”/>
</beans>
Arrays and Lists
<bean id=“x” class=“y”>
<property name=“nm”>
<list>
<value>pqr</value>
<value>xyz</value>
<value>abc</value>
</list>
</property>
</bean>
List of objects
<beans>
<bean id=“x” class=“y”>
<property name=“nm”>
<list>
<ref bean=“a”/>
<ref bean=“b”/>
</list>
</property>
</bean>
<bean id=“a” class=“p”/>
<bean id=“b” class=“q”/>
</beans>
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
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>
Properties
<beans>
<bean id=“x” class=“y”>
<property name=“nm”>
<props>
<prop key=“k1”>val1</prop>
<prop key=“k2”>val2</prop>
</props>
</property>
</bean>
</beans>
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>
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>
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.
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
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
Modules
 Seven modules or packages
Spring Core
 Dependency Injection
 BeanFactory and ApplicationContext
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
Spring Web MVC
 Controller
 Validator
Life cycle of a request

Spring Web MVC

Handler Mapping

2

Request

3

1

Dispatcher Servlet

Controller

4
ModelAndView

5

ViewResolver

6

View
Spring Web MVC
2

Request

Handle Mapping

3

1

Dispatcher Servlet

Controller

4
ModelAndView

5

ViewResolver
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
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’
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
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.
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 -->
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 -->
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
Command Object
 It holds the data that the user enters in the form/GUI
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;
}
}
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>
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.
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.
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);
}
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>
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>
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.
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
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);
}
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");
}
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
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>
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.
Spring Context
 Resource bundles
 Event propagation
 Bean Lookup
Spring ORM
 Hibernate support- Spring provides integration with

Object Relational mapping frameworks like Hibernate
Spring DAO
 Transaction infrastructure
 JDBC support
 DAO support
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>
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>
Spring framework in depth

Weitere Àhnliche Inhalte

Was ist angesagt?

Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 

Was ist angesagt? (20)

Spring ppt
Spring pptSpring ppt
Spring ppt
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Spring core module
Spring core moduleSpring core module
Spring core module
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring framework Introduction
Spring framework IntroductionSpring framework Introduction
Spring framework Introduction
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 

Andere mochten auch

Andere mochten auch (7)

Spring orm notes_by_soma_sekhar_reddy_javabynataraj
Spring orm notes_by_soma_sekhar_reddy_javabynatarajSpring orm notes_by_soma_sekhar_reddy_javabynataraj
Spring orm notes_by_soma_sekhar_reddy_javabynataraj
 
JSR 168 Portal - Overview
JSR 168 Portal - OverviewJSR 168 Portal - Overview
JSR 168 Portal - Overview
 
Spring framework part 2
Spring framework  part 2Spring framework  part 2
Spring framework part 2
 
Getting Started with Spring Framework
Getting Started with Spring FrameworkGetting Started with Spring Framework
Getting Started with Spring Framework
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring notes
Spring notesSpring notes
Spring notes
 

Ähnlich wie Spring framework in depth

Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
MichaƂ Orman
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
Guo Albert
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
Tuna Tore
 
Sel study notes
Sel study notesSel study notes
Sel study notes
Lalit Singh
 

Ähnlich wie Spring framework in depth (20)

Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1
 
Spring
SpringSpring
Spring
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Sel study notes
Sel study notesSel study notes
Sel study notes
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2
 
Spring tutorial
Spring tutorialSpring tutorial
Spring tutorial
 
Spring training
Spring trainingSpring training
Spring training
 
Spring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 IntegrationSpring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 Integration
 
Jsf
JsfJsf
Jsf
 

Mehr von Vinay Kumar

Extend soa with api management Doag18
Extend soa with api management Doag18Extend soa with api management Doag18
Extend soa with api management Doag18
Vinay Kumar
 
award-3b07c32b-b116-3a75-8974-d814d37026ca
award-3b07c32b-b116-3a75-8974-d814d37026caaward-3b07c32b-b116-3a75-8974-d814d37026ca
award-3b07c32b-b116-3a75-8974-d814d37026ca
Vinay Kumar
 
award-3b07c32b-b116-3a75-8974-d814d37026ca
award-3b07c32b-b116-3a75-8974-d814d37026caaward-3b07c32b-b116-3a75-8974-d814d37026ca
award-3b07c32b-b116-3a75-8974-d814d37026ca
Vinay Kumar
 

Mehr von Vinay Kumar (20)

Modernizing the monolithic architecture to container based architecture apaco...
Modernizing the monolithic architecture to container based architecture apaco...Modernizing the monolithic architecture to container based architecture apaco...
Modernizing the monolithic architecture to container based architecture apaco...
 
Kafka and event driven architecture -apacoug20
Kafka and event driven architecture -apacoug20Kafka and event driven architecture -apacoug20
Kafka and event driven architecture -apacoug20
 
Kafka and event driven architecture -og yatra20
Kafka and event driven architecture -og yatra20Kafka and event driven architecture -og yatra20
Kafka and event driven architecture -og yatra20
 
Extend soa with api management Sangam18
Extend soa with api management Sangam18Extend soa with api management Sangam18
Extend soa with api management Sangam18
 
Extend soa with api management Doag18
Extend soa with api management Doag18Extend soa with api management Doag18
Extend soa with api management Doag18
 
Roaring with elastic search sangam2018
Roaring with elastic search sangam2018Roaring with elastic search sangam2018
Roaring with elastic search sangam2018
 
Extend soa with api management spoug- Madrid
Extend soa with api management   spoug- MadridExtend soa with api management   spoug- Madrid
Extend soa with api management spoug- Madrid
 
Expose your data as an api is with oracle rest data services -spoug Madrid
Expose your data as an api is with oracle rest data services -spoug MadridExpose your data as an api is with oracle rest data services -spoug Madrid
Expose your data as an api is with oracle rest data services -spoug Madrid
 
Modern application development with oracle cloud sangam17
Modern application development with oracle cloud sangam17Modern application development with oracle cloud sangam17
Modern application development with oracle cloud sangam17
 
award-3b07c32b-b116-3a75-8974-d814d37026ca
award-3b07c32b-b116-3a75-8974-d814d37026caaward-3b07c32b-b116-3a75-8974-d814d37026ca
award-3b07c32b-b116-3a75-8974-d814d37026ca
 
award-3b07c32b-b116-3a75-8974-d814d37026ca
award-3b07c32b-b116-3a75-8974-d814d37026caaward-3b07c32b-b116-3a75-8974-d814d37026ca
award-3b07c32b-b116-3a75-8974-d814d37026ca
 
Adf spotlight-webcenter task flow-customzation
Adf spotlight-webcenter task flow-customzationAdf spotlight-webcenter task flow-customzation
Adf spotlight-webcenter task flow-customzation
 
Personalization in webcenter portal
Personalization in webcenter portalPersonalization in webcenter portal
Personalization in webcenter portal
 
Custom audit rules in Jdeveloper extension
Custom audit rules in Jdeveloper extensionCustom audit rules in Jdeveloper extension
Custom audit rules in Jdeveloper extension
 
File upload in oracle adf mobile
File upload in oracle adf mobileFile upload in oracle adf mobile
File upload in oracle adf mobile
 
Webcenter application performance tuning guide
Webcenter application performance tuning guideWebcenter application performance tuning guide
Webcenter application performance tuning guide
 
Tuning and optimizing webcenter spaces application white paper
Tuning and optimizing webcenter spaces application white paperTuning and optimizing webcenter spaces application white paper
Tuning and optimizing webcenter spaces application white paper
 
Oracle adf performance tips
Oracle adf performance tipsOracle adf performance tips
Oracle adf performance tips
 
Oracle Fusion Architecture
Oracle Fusion ArchitectureOracle Fusion Architecture
Oracle Fusion Architecture
 
Incentive compensation in fusion CRM
Incentive compensation in fusion CRMIncentive compensation in fusion CRM
Incentive compensation in fusion CRM
 

KĂŒrzlich hochgeladen

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

KĂŒrzlich hochgeladen (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Spring framework in depth

  • 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
  • 5. AOP  Aspect oriented programming  Cross cutting concerns  Transaction, Security and Logging requirements
  • 6. BeanFactory      Interface BeanFactory BeanFactory creates beans getBean() method Implementation classes like the XmlBeanFactory Methods:  getBean()  isSingleton()  getType()  getAliases()  containsBean() This is how a BeanFactory looks like
  • 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.
  • 8. ApplicationContext  Extends the BeanFactory  Adds the following methods:  getResource()  getMessage()
  • 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
  • 14. Dependency Injection  Spring allows for:  Setter based injection  Constructor based injection
  • 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
  • 18. Null values <bean id=“x” class=“y”> <property name=“nm”> <value><null/></value> </property> </bean>
  • 19. Bean <beans> <bean id=“myClass” class=“demo.MyClass”> <property name=“display”> <ref bean=“a” /> </property> </bean> <bean id=“a” class=“util.TestClass”/> </beans>
  • 20. Arrays and Lists <bean id=“x” class=“y”> <property name=“nm”> <list> <value>pqr</value> <value>xyz</value> <value>abc</value> </list> </property> </bean>
  • 21. List of objects <beans> <bean id=“x” class=“y”> <property name=“nm”> <list> <ref bean=“a”/> <ref bean=“b”/> </list> </property> </bean> <bean id=“a” class=“p”/> <bean id=“b” class=“q”/> </beans>
  • 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>
  • 24. Properties <beans> <bean id=“x” class=“y”> <property name=“nm”> <props> <prop key=“k1”>val1</prop> <prop key=“k2”>val2</prop> </props> </property> </bean> </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
  • 31. Spring Core  Dependency Injection  BeanFactory and ApplicationContext
  • 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
  • 33. Spring Web MVC  Controller  Validator
  • 34. Life cycle of a request Spring Web MVC Handler Mapping 2 Request 3 1 Dispatcher Servlet Controller 4 ModelAndView 5 ViewResolver 6 View
  • 35. Spring Web MVC 2 Request Handle Mapping 3 1 Dispatcher Servlet Controller 4 ModelAndView 5 ViewResolver
  • 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
  • 43. Command Object  It holds the data that the user enters in the form/GUI
  • 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.
  • 58. Spring Context  Resource bundles  Event propagation  Bean Lookup
  • 59. Spring ORM  Hibernate support- Spring provides integration with Object Relational mapping frameworks like Hibernate
  • 60. Spring DAO  Transaction infrastructure  JDBC support  DAO support
  • 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

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