SlideShare a Scribd company logo
Java/J2EE Programming Training
Spring Framework
Page 1Classification: Restricted
Agenda
• Understand Spring framework overview & its salient features
• Spring concepts (IoC container / DI)
• Spring-AOP basics
• Spring ORM / Spring DAO overview
• Spring Web / MVC overview
Page 2Classification: Restricted
Why a new framework?
• Because of many problems with traditional J2EE Architecture
• Complexity
• EJB, JNDI, JTA, JDBC etc
• Too many APIs
• EJB is over used
• Simply lots of code
• Petstore as an example
• Much of the code is “Plumbing code”
• Heavy weight runtime environment
• Hard to Unit Test
• Components need to be explicitly deployed to be able to run, even
for testing
• Slow change-deploy-test cycle
Page 3Classification: Restricted
Enter Lightweight Containers
• Frameworks are central to modern J2EE development
• Many projects encounter the same problems
• Service location
• Consistent exception handling
• Parameterizing application code…
• J2EE “out of the box” does not provide a complete (or ideal)
programming model
• Result:
• many in-house frameworks
• Expensive to maintain and develop
• Better to share experience across many projects
• Choose Opensource framework
Page 4Classification: Restricted
How do Lightweight Containers Work?
• Inversion of Control/Dependency Injection
• Sophisticated configuration for POJOs
• Aspect Oriented Programming (AOP)
• Provide declarative services to POJOs
• Out-of-the box (transaction management, security) or custom
(auditing)
• Aim to provide a consistent framework for development
• The Spring Framework and HiveMind are the most compelling offerings
• Spring is the most complete, mature and popular
Page 5Classification: Restricted
Spring Framework
• The Spring Framework
• Open source project
• Apache 2.0 license
• Initially written by Rod Johnson and Juergen Hoeller
• 21 developers
• Interface21 lead development effort, with seven committers (and
counting), including the two project leads
• Aims
• Simplify J2EE development
• Provide a comprehensive solution to developing applications built on
POJOs
• Provide services for applications ranging from simple web apps up to
large financial/“enterprise” applications
Page 6Classification: Restricted
Spring Framework history
• Started 2002/2003 by Rod Johnson and
Juergen Holler
• Started as a framework developed around
Rod Johnson’s book Expert One-on-One J2EE
Design and Development
• Spring 1.0 Released March 2004
• Spring 1.2 - 2005
• Spring 2.0 – October 2006
• Spring 2.5 – November 2007
Page 7Classification: Restricted
Spring Framework mission
Mission Statement
• We believe that:
• J2EE should be easier to use
• It is best to program to interfaces, rather than classes. Spring reduces the complexity cost of using
interfaces to zero.
• JavaBeans offer a great way of configuring applications.
• OO design is more important than any implementation technology, such as J2EE.
• Checked exceptions are overused in Java. A framework shouldn't force you to catch exceptions
you're unlikely to be able to recover from.
• Testability is essential, and a framework such as Spring should help make your code easier to test.
Our philosophy is summarized in Expert One-on-One J2EE Design and Development by Rod Johnson.
We aim that:
• Spring should be a pleasure to use
• Your application code should not depend on Spring APIs
• Spring should not compete with good existing solutions, but should foster integration. (For example,
JDO, Toplink, and Hibernate are great O/R mapping solutions. We don't need to develop another
one.)
Page 8Classification: Restricted
What is Spring Framework?
Spring is a lightweight, inversion of control and aspect-oriented container
framework.
• Lightweight:
• In terms of both size and overhead.
• Entire framework can be distributed in single JAR file(1MB)
• Processing overhead required is negligible
• Is non intrusive: objects have no dependency on Spring specific classes
• Inversion of Control:
• Promotes loose coupling through use of IoC
• Instead of an object looking up dependencies from a container, the
container gives the dependencies to the object at instantiation
without waiting to be asked (reverse of JNDI)
Page 9Classification: Restricted
What is Spring Framework? Contd.
• Aspect-oriented:
• Enables cohesive development by separating application business logic from system
services
• Application objects focus on business logic not other system concerns such as logging,
transaction management
• Container:
• It contains and manages the life cycle of application objects
• You can configure how each of your bean should be created, a single instance
(singleton) or new instance each time (prototype)
• Framework:
• Spring makes it possible to configure and compose complex applications from simpler
components.
• application objects are composed declaratively, typically in an XML file
• Provides infrastructure functionality (transaction management, persistence framework
integration, etc.)
Code which is cleaner, more manageable and easy to test
Page 10Classification: Restricted
Spring modules
Page 11Classification: Restricted
Spring Framework Overview – contd.
• Core module
• is the most fundamental part of the framework and provides the IoC
and Dependency Injection features
• Defines how beans are created, configured, and managed—more of
the nuts-and-bolts of Spring.
Here you’ll find Spring’s BeanFactory, the heart of any Spring-based
application
• Application Context module
• The core module’s BeanFactory makes Spring a container, but the
context module is what makes it a framework.
• Add supports for i18n messages, application lifecycle events,
validation etc
• Supplies many enterprise services such as e-mail, EJB integration,
remoting, and scheduling and integration with templating frameworks
such as Velocity and FreeMarker.
Page 12Classification: Restricted
Spring Framework Overview – contd.
• Spring’s AOP module
• Serves as the basis for developing your own aspects for your Spring-
enabled application.
• Ensures interoperability between Spring and other Java AOP
frameworks
• Supports metadata programming ( aspects can be configured using
annotations)
• JDBC Abstraction and DAO module
• Working with JDBC often results in a lot of boilerplate code
• Abstracts away the boilerplate code and prevents problems that result
from a failure to close database resources
• Uses Spring AOP module to provide Transaction management services
Page 13Classification: Restricted
Spring Framework Overview – contd.
• Object/Relational mapping integration module
• Provide hooks into several popular ORM frameworks, including
Hibernate, JDO, and iBATIS SQL Maps.
• Spring’s transaction management supports each of these ORM
frameworks as well as JDBC.
• Spring’s Web module
• Builds on the application context module
• Support for several web-oriented tasks
• e.g. transparently handling multipart requests
• programmatic binding of request parameters to your business
objects
• contains integration support with Jakarta Struts.
• Spring’s MVC framework and can take advantage of Spring’s services
(for e.g. i18n, validation etc.
Page 14Classification: Restricted
Usage Scenarios
Page 15Classification: Restricted
Spring Core and Application Context
Page 16Classification: Restricted
BeanFactory and Application Context
Page 17Classification: Restricted
Bean Factory
• It is an implementation of Factory design pattern
• Instantiation of beans
• Configuration
• Management of one or more beans
• Create associations between collaborating objects as they are
instantiated, thus giving fully configured, ready to use objects
Page 18Classification: Restricted
Bean Factory API Hierarchy
Page 19Classification: Restricted
Hello World!
package com.example.hello;
public interface GreetingService {
public void sayGreeting();
}
package com.example.hello;
public class GreetingServiceImpl implements GreetingService {
private String greeting;
public GreetingServiceImpl() {}
public GreetingServiceImpl(String greeting) {
this.greeting = greeting;
}
public void sayGreeting() {
System.out.println(greeting);
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
Page 20Classification: Restricted
Hello World! – application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans> The root element
<bean id="greetingService“ Bean instance
class="com.example.hello.GreetingServiceImpl">
<property name="greeting">
<value>Hello World</value>
</property>
</bean>
</beans>
Page 21Classification: Restricted
Hello World! – contd.
import java.io.FileInputStream;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
public class HelloApp {
public static void main(String[] args) throws Exception {
BeanFactory factory = new XmlBeanFactory(new
FileInputStream("hello.xml"));
GreetingService greetingService =
(GreetingService) factory.getBean("greetingService");
greetingService.sayGreeting();
}
Page 22Classification: Restricted
The Spring IoC container
The
Spring Container
Fully Configured System
Ready for User
Configuration
Metadata
Your Business Objects (POJOs)
Page 23Classification: Restricted
What is Inversion of Control (IoC)?
(besides yet another confusing term for a simple concept)
• IoC is all about Object dependencies.
• Traditional "Pull" approach:
• Direct instantiation
• Asking a Factory for an implementation
• Looking up a service via JNDI
• "Push" approach:
• Something outside of the Object "pushes" its dependencies into it.
• The Object has no knowledge of how it gets its dependencies, it just
assumes they are there.
• Hollywood Principle
• Don’t call me, I’ll call you
• Means that the framework calls your code, not the reverse
• The "Push" approach is called "Dependency Injection". (Next slide)
Page 24Classification: Restricted
What is Dependency Injection?
• A specialization of Inversion of Control
• The container injects dependencies into object instances using Java
methods
• Dependencies may be collaborating objects or primitive or simple
types
• This is also known as push configuration
• Configuration values are pushed into objects, rather than pulled by
the objects from an environment such as JNDI or a properties file
Page 25Classification: Restricted
Inversion of Control Types
• Type 1: Interface injection
• Dependency satisfied by interfaces it implemented (Used by Apache’s
Avalon Framework)
• Type 2: Setter injection
• Dependency satisfied by JavaBean properties and its setter/getter
exposed by a component
• Type 3: Constructor injection
• Dependency satisfied by the component’s constructor
• Spring supports Type 2, Type 3 IoC
• Note: Other Lightweight containers
• Pico Container, Nano Container
• HiveMind
• Avalaon
Page 26Classification: Restricted
Dependency Injection using setters
<bean id=”ex1” class=”ExBean1”>
<property name=”bean”>
<ref bean=”ex2”/>
</property>
</bean>
<bean id=”ex2” class=”ExBean2”/>
public class ExBean1 {
private ExBean2 bean;
public void setBean(ExBean2 bean) {
this.bean = bean;
}
}
• The <ref> subelement of <property> helps refer to another bean.
• You can also wire collections such as list, set, map, properties as
subelements of <property>
Page 27Classification: Restricted
<bean id="courseService“
class="com.springinaction.service.training.CourseService
Impl">
<property name="studentService">
<ref bean="studentService"/>
</property>
</bean>
The container gives the courseService bean a StudentService bean (through
setStudentService()), thereby freeing CourseServiceImpl from having to
look
up a StudentService bean on its own.
Disadvantages:
• When this type of bean is instantiated, none of its properties have been
set and it could possibly be in an invalid state.
Page 28Classification: Restricted
Dependency Injection using Constructors
<bean id="studentService“
class="com.springinaction.training.service.StudentServiceImpl"
>
<constructor-arg>
<ref bean="studentDao"/>
</constructor-arg>
</bean>
Advantages:
• A bean cannot be instantiated without being given all of its dependencies.
It is perfectly valid and ready to use upon instantiation.
• No need for superfluous setter methods. This helps keep the lines of code
at a minimum
• By only allowing properties to be set through the constructor, you are, in
effect, making those properties immutable.
Page 29Classification: Restricted
Dependency Injection using Constructors - Contd
Drawback:
• If a bean has several dependencies, the constructor’s parameter list can
be quite lengthy.
• If there are several ways to construct a valid object, it can be hard to
come up with unique constructor. Since constructor signatures vary only
by the number and type of parameters.
• If a constructor takes two or more parameters of the same type, it may
be difficult to determine what each parameter’s purpose is.
• Constructor injection does not lend itself readily to inheritance. A bean’s
constructor will have to pass parameters to super() in order to set private
properties in the parent object.
Page 30Classification: Restricted
Why is push better than pull?
• No more ad-hoc lookup
• Code is self-documenting, describing its own dependencies
• Easy to unit test
• No JNDI to stub, properties files to substitute, RDBMS data to set up
• Simply instantiate class in a JUnit test and use setters or constructors
Page 31Classification: Restricted
Spring Special Beans
• By implementing certain interfaces Spring can treat some beans
as being special—as being part of the Spring framework itself
• For e.g. Special Beans can be used –
• Become involved in the bean’s and the bean factory’s life
cycles by postprocessing bean configuration
• Load configuration information from external property files
• Load textual messages from property files, including
internationalized messages
• Listen for and respond to application events that are published
by other beans and by the Spring container itself
• Are aware of their identity within the Spring container
Page 32Classification: Restricted
For e.g. Externalizing the configuration
Load configuration information from external property files.
<bean id="propertyConfigurer" class="org.springframework.beans.
factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>jdbc.properties</value>
<value>security.properties</value>
</list>
</property>
</bean>
Page 33Classification: Restricted
For e.g. Externalizing the configuration contd.
In the jdbc.properties file:
database.url=jdbc:hsqldb:Training
database.driver=org.hsqldb.jdbcDriver
database.user=appUser
database.password=password
Applying the placeholder variables to the data source configuration:
<bean id="dataSource“ class="org.springframework.
jdbc.datasource.DriverManagerDataSource">
<property name="url">
<value>${database.url}</value>
</property>
<property name="driverClassName">
<value>${database.driver}</value>
</property>
<bean>
Page 34Classification: Restricted
Special Beans Contd.
• Making Beans Aware.
• By implemementing BeanNameAware and ApplicationContextAware
interfaces, beans can be made aware of their name, their
BeanFactory, and their ApplicationContext, respectively.
• By implementing these interfaces, a bean becomes coupled with
Spring.
Page 35Classification: Restricted
Page 36Classification: Restricted
Page 37Classification: Restricted
Spring AOP
• Enables to modularize application concerns
• Helps support declarative transaction.
Page 38Classification: Restricted
What is AOP?
• Paradigm for modularizing crosscutting code
• Code that would otherwise be scattered across multiple methods or
objects can be gathered in one place
Page 39Classification: Restricted
Calls to system-wide concerns such as logging and security are often
scattered about in modules where those concerns are not their primary
concern
Page 40Classification: Restricted
• Using AOP, system wide concerns blanket the components that they impact.
Page 41Classification: Restricted
Before AOP
Client
Method
1. Security check
2. Obtain session
3. Log it to the file
4. Audit trail
5. Start transaction
6. Business Logic
7. Commit
8. Exception handling
Page 42Classification: Restricted
AOP applied
Client Method
1. Business Logic
1. Security check
2. Obtain session
3. Log it to the file
4. Audit trail
5. Start transaction
1. Commit
1. Exception handling
Page 43Classification: Restricted
AOP Interception
• In the simplest case, think about interception
• Callers invoke a proxy
• A chain of interceptors/advice decorate the method call as execution
flows toward the target
• Interceptors provide services such as transaction management or
security checks
• These services are often specified declaratively
Page 44Classification: Restricted
Page 45Classification: Restricted
AOP Terms
• Aspect
• The cross-cutting functionality e.g.. Logging
• Jointpoint
• Point in the execution of the application where an aspect can be
plugged in.
• e.g. method being called, an exception being thrown, or even a field
being modified.
• Advice
• Actual implementation of our aspect.It is inserted into our application
at pointcut
• Different types of advice include "around," "before" and "after" advice.
• Pointcut
• A pointcut defines at what joinpoints advice should be applied.
• for e.g. the execution of a method with a certain name
• Some AOP frameworks allow you to create dynamic pointcuts.
Page 46Classification: Restricted
AOP Terms
• Introduction
• An introduction allows you to add new methods or attributes to existing
classes
• Target
• A target is the class that is being advised.
• Proxy
• A proxy is the object created by AOP framework after applying advice to
the target object.
• As far as the client objects are concerned, the target object (pre-AOP) and
the proxy object (post-AOP) are the same
• Weaving
• Weaving is the process of applying aspects to a target object to create a
new, proxied object either during target classes’s compile time, classload
time, runtime.
Page 47Classification: Restricted
Applying an Aspect
Page 48Classification: Restricted
Advantages and Drawbacks of AOP
• Advantages:
• Decoupling between classes
• A clear line between the different application layers
• Reduction of code duplication
• Better support for refactoring
• Drawbacks
• Steep learning curve
• AOP imposes several requirements on the programming language used
Page 49Classification: Restricted
Spring AOP
• Aspects written in java
• Pointcut written in XML in Spring Configuration File.
• Spring supports only method joinpoints.
• Other AOP frameworks requires special syntax which is not the case with
Spring
• Other AOP frameworks are AspectJ, AspectWerkz, JbossAOP, EAOP,
DynamicAspects
Page 50Classification: Restricted
Creating Advice
• Creating the advice object means writing code to implement the cross
cutting functionality.
• Advice Types in Spring:
Page 51Classification: Restricted
Example for Before advice type
public interface EMart{
Chocolate buyChocolate(Customer customer) throws EMartException;
}
public class XYZEMart implements EMart{
public Chocolate buyChocolate(Customer customer) throws
EMartException {
return new Chocolate();}
}
public interface MethodBeforeAdvice {
void before(Method method, Object[] args, Object target) throws
Throwable
}
The parameters are the target method, the arguments passed to the method
and
target object of method invocation.
Page 52Classification: Restricted
import org.springframework.aop.MethodBeforeAdvice;
public class WelcomeAdvice implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target) {
Customer customer = (Customer) args[0];
System.out.println("Hello " + customer.getName());}
}
Configure the spring configuration file to apply the advice
Page 53Classification: Restricted
<beans>
<bean id="EMartTarget“ class=“XYZEMart"/> create proxy target object
<bean id="welcomeAdvice“ class="WelcomeAdvice"/> create advice
<bean id="EMart“tell Spring to create a proxy bean
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>EMart</value>implement EMart interface
</property>
<property name="interceptorNames">
<list> apply advice object to incoming calls
<value>welcomeAdvice</value>
</list>
</property>
<property name="target"> use XYZEMart bean as target object
<ref bean=“EMartTarget"/>
</property>
</bean>
</beans>
A bean is loaded whose interface matches EMart. This bean is then tied to the
implementation class XYZEMart
Page 54Classification: Restricted
Spring Framework: Before and After Returning Advice
Page 55Classification: Restricted
AOP Pointcut
• Tells us where the advice should be applied.
• Spring defines pointcuts in terms of the class and method that is being
advised.
• To determine if a method is eligible for advising we implement the interface:
public interface MethodMatcher
{
boolean matches(Method m, Class targetClass);
public boolean isRuntime();
public boolean matches(Method m, Class target, Object[] args);
}
Page 56Classification: Restricted
Spring Advisors
• Most aspects are a combination of advice that defines the aspect’s behavior
and a pointcut defining where the aspect should be executed.
• Spring therefore, offers advisors, which combine advice and pointcuts into
one object.
public interface PointcutAdvisor {
Pointcut getPointcut();
Advice getAdvice();
}
• Most of Spring’s built-in pointcuts also have a corresponding
PointcutAdvisor.
Page 57Classification: Restricted
Types of Pointcuts
• Static Pointcuts
• NameMatchedMethodPointcut class has 2 methods:
– public void setMappedName(String)
– public void setMappedNames(String[])
• RegexpMethodPointcut
• Dynamic Pointcuts
• Any Pointcut's implementation with isRuntime() == true
• Built-in dynamic pointcut : ControlFlowPointcut
Page 58Classification: Restricted
Example of Static Pointcut
• Setting the mappedName property to set* will match all setter methods.
<bean id="frequentCustomerPointcutAdvisor"
class="org.springframework.aop.support.NameMatchMethodPointcutAdv
isor">
<property name="mappedName">
<value>buy*</value>
</property>
<property name="advice">
<ref bean=“welcomeAdvice"/>
</property>
</bean>…..ProxyFactoryBean
• When our proxy is created, invocations of any method on our target object,
that begins with buy will be advised by our welcomeAdvice.
• This matching only applies to the method name and not the fully qualified
name that includes the class name as well.
Page 59Classification: Restricted
AOP Configuration
Page 60Classification: Restricted
Using ProxyFactoryBean
• ProxyFactoryBean creates proxied objects.
• It has properties that control its behavior.
• ProxyFactoryBean properties:
• target: The target bean of the proxy. The object that has to adviced.
• proxyInterfaces: A list of interfaces that must be implemented by the
proxy (beans created by the factory). You can specify single interface
or a list of interfaces.
• interceptorNames: The bean names of the advice to be applied to the
target.
Page 61Classification: Restricted
Hitting Database, Remoting
Page 62Classification: Restricted
Springs DAO philosophy
• Service objects are accessing the DAOs through interfaces.
• Advantages:
• Easy unit testing of service objects (DAI can be mocked)
• Data Access Interface does not expose what technology it is using to access
data
Page 63Classification: Restricted
Spring’s DataAccessException
• Spring’s DAO frameworks do not throw technology-specific exceptions, such
as SQLException or HibernateException.
• All exceptions thrown are subclasses of
org.springframework.dao.DataAccessException.
• DataAccessException is a RuntimeException, so it is an unchecked exception.
Thus the code will not be required to handle these exceptions when they are
thrown by the data access tier.
Page 64Classification: Restricted
Page 65Classification: Restricted
Working with DataSources
• Getting a DataSource from JNDI:
<bean id="dataSource“
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/myDatasource</value>
</property>
</bean>
• Spring separates the fixed and variant parts of the data access
process into two distinct classes:
• templates : Templates manage the fixed part of the process like
controlling transactions, managing resources, and handling
exceptions
• Callbacks: Implementations of the callback interfaces define what
is specific to your application—creating statements, binding
parameters
Page 66Classification: Restricted
Page 67Classification: Restricted
Problem with JDBC code
Page 68Classification: Restricted
Problem with JDBC code Contd.
Page 69Classification: Restricted
Problem with JDBC code Contd.
Page 70Classification: Restricted
• Create prepared stmt and set the parameters are the only
unique lines of code.
• The rest is a boilerplate code.( Cleaning resources, handling
errors- which is equally important)
• Spring’s JDBC framework will take care of resource
management and handling errors.
• Spring’s data access frameworks incorporate a template
class. In this case, it is the JdbcTemplate class.
Using JDBCTemplate
Page 71Classification: Restricted
• To make use of the JdbcTemplate, each of your DAO classes
needs to be configured with a JdbcTemplate instance:
public class StudentDaoJdbc implements StudentDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;}
….}
Using JDBCTemplate
Page 72Classification: Restricted
Writing Data
• We create a PreparedStatement from a SQL string and then
bind parameters, JdbcTemplate provides an execute(String
sql, Object[] params) method
Page 73Classification: Restricted
Spring’s Transaction Manager
• Spring does not directly manage transactions
• It has transaction managers that delegate responsibility for
transaction management to platform-specific transaction
implementation provided by either JTA or persistence mechanism.
Page 74Classification: Restricted
Spring’s Transaction Manager Contd
Page 75Classification: Restricted
Springs ORM framework Support
•Spring provides integration for
•Sun’s standard persistence API JDO,
•as well as the open source ORM frameworks:
•Hibernate
•Apache OJB
•iBATIS SQL Maps
Page 76Classification: Restricted
Remoting
• Remoting is a conversation between a client application and
a service.
• The remote application exposes the functionality through a
remote service.
• Spring supports RPC for six different RPC models:
• Remote Method Invocation (RMI)
• Caucho’s Hessian and Burlap
• Spring’s own HTTP invoker
• Enterprise JavaBeans (EJB)
• Web services
Page 77Classification: Restricted
RPC Models supported by Spring
Page 78Classification: Restricted
Proxy Bean
Page 79Classification: Restricted
Advantages of Spring Remoting
• Regardless of whether you are using RMI, Hessian, Burlap,
HTTP invoker, EJB, or web services, you can wire remote
services into your application as if they were POJOs.
• Spring even catches any RemoteExceptions that are thrown
and rethrows runtime RemoteAccessExceptions in their
place, freeing your code from having to deal with an
exception that it probably can’t recover from
• Spring hides many of the details of remote services, making
them appear as though they are local JavaBeans
Page 80Classification: Restricted
Building the Web Layer
Page 81Classification: Restricted
Life Cycle of a Request- Spring MVC
Front Controller
Handles request
Maps url Pattern
Request
Logical name of View
Renders Response
Web Browser
Page 82Classification: Restricted
A. Dispatcher Servlet
• Must be configured in web.xml
<servlet>
<servlet-name>training</servlet-name> training-servlet.xml
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>training</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
Page 83Classification: Restricted
Breaking up the Application Context
Page 84Classification: Restricted
• Configure context loader in web.xml
• A context loader loads context configuration files in addition to the one
that DispatcherServlet loads.
• Two context loaders to choose from:
• ContextLoaderListener
Used when Web Container supports Servlet 2.3 or higher and
initializes servlet listeners before servlets.
• ContextLoaderServlet.
Page 85Classification: Restricted
• For ContextLoaderListener
<listener>
<listener-
class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
• For ContextLoaderServlet
<servlet>
<servlet-name>context</servlet-name>
<servlet-
class>org.springframework.web.context.ContextLoaderServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
• Specify one or more Spring configuration files for the context loader to
load
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/training-service.xml, /WEB-INF/training-data.xml
</param-value>
</context-param>
Page 86Classification: Restricted
Spring MVC in a Nutshell
• Minimum steps required to create home page for a Spring training
example.
1.Write the controller class that performs the logic behind the
homepage.
2.Configure the controller in the DispatcherServlet’s context
configuration file (training-servlet.xml).
3.Configure a view resolver to tie the controller to the JSP.
4.Write the JSP that will render the homepage to the user.
Page 87Classification: Restricted
Building the Controller
public class HomeController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return new ModelAndView("home", "message", greeting);
}
private String greeting;
public void setGreeting(String greeting) {
this.greeting = greeting;}
}
• Similar to struts action but just a simple java bean in application context,
therefore can make use of all the IoC and AOP, for e.g.. Greeting is set
using IoC
Page 88Classification: Restricted
Configuring the Controller Bean
• Configure it in the DispatcherServlet’s context configuration
file (which in this case is training-servlet.xml)
<bean name="/home.htm“
class="com.springinaction.training.mvc.HomeController">
<property name="greeting">
<value>Welcome to Spring Training!</value>
</property>
</bean>
Page 89Classification: Restricted
Declaring a View Resolver
• Configure it in the DispatcherServlet’s context configuration file (which in
this case is training-servlet.xml)
• In the case of HomeController, we need a view resolver to resolve
“home” to a JSP file that renders the home page.
<bean id="viewResolver" class="org.springframework.web.
servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
Page 90Classification: Restricted
Creating the JSP
• Name this JSP “home.jsp” and to place it in the /WEB-INF/jsp folder
within your web application. That’s where InternalResourceViewResolver
will try to find it.
<html>
<head><title>Spring Training, Inc.</title></head>
<body>
<h2>${message}</h2>
</body>
</html>
Page 91Classification: Restricted
Quick Recap
1 DispatcherServlet receives a request whose URL pattern is “/home.htm”.
2 DispatcherServlet consults BeanNameUrlHandlerMapping to find a controller
whose bean name is “/home.htm”, finding the HomeController bean.
3 DispatcherServlet dispatches the request to HomeController for processing.
4 HomeController returns a ModelAndView object with a logical view name of
‘home’.
5 DispatcherServlet consults its view resolver (configured as
InternalResourceViewResolver) to find a view whose logical name is home.
Internal-ResourceViewResolver returns the path to /WEB-INF/jsp/home.jsp.
6 DispatcherServlet forwards the request to the JSP at /WEB-INF/jsp/home.jsp to
render the home page to the user.
Page 92Classification: Restricted
Putting it all together
Page 93Classification: Restricted
Handler mapping
• Mapping Requests to Controller
• When associating a request with a specific controller, DispatcherServlet
consults a handler mapping bean.
• Handler mappings typically map a specific controller bean to a URL
pattern
• All of Spring MVC’s handler mappings implement the
org.springframework.web.servlet.HandlerMapping interface.
• Spring has three useful implementations of HandlerMapping
Page 94Classification: Restricted
Mapping requests to controllers
• BeanNameUrlHandlerMapping—
• Maps controllers to URLs that are based on the controllers’ bean name.
• This is the default handler.
<bean name="/home.htm“
class="com.springinaction.training.mvc.HomeController"></bean>
• SimpleUrlHandlerMapping—
• Maps controllers to URLs using a property collection defined in the
context configuration file
• CommonsPathMapHandlerMapping—
• Maps controllers to URLs using source level metadata placed in the
controller code.
• Example
/**
* @@org.springframework.web.servlet.handler.
commonsattributes.PathMap("/displayCourse.htm")
*/
public class DisplayCourseController extends
AbstractCommandController {…}
Page 95Classification: Restricted
Example for SimpleUrlHandlermapping
<bean id="simpleUrlMapping" class=
"org.springframework.web.servlet.handler.SimpleUrlHandler
Mapping">
<property name="mappings">
<props>
<prop
key="/listCourses.htm">listCoursesController</prop>
<prop
key="/register.htm">registerStudentController</prop>
<prop
key="/displayCourse.htm">displayCourseController</prop>
<prop key="/login.htm">loginController</prop>
<prop key="/enroll.htm">enrollController</prop>
</props>
</property>
</bean>
Page 96Classification: Restricted
Handling Requests with Controllers
Page 97Classification: Restricted
Spring MVC’s selection of controller classes
Page 98Classification: Restricted
Examples
• Simple Controller:
• When you need to take no(or few parameters) e.g.. When you wish to
display the list of all courses.
• Command Controllers:
• For e.g. after viewing a list of available courses, you may want to view
more details about that course.
• This controller will automatically bind parameters to a command
object and provide hooks for you to plug in validators to ensure that
the parameters are valid.
Page 99Classification: Restricted
Page 100Classification: Restricted
Processing Form Submission
E.g. Student registration
Form Controllers add functionality to display a form when
an HTTP GET request is received and process the form
when an HTTP POST is received
If any errors occur in processing the form, the controller
will know to redisplay the form so that the user can
correct the errors and resubmit
Page 101Classification: Restricted
Page 102Classification: Restricted
• doSubmitAction() method handles the form submission (an HTTP POST request) by passing
the command object (which happens to be a Student domain object) to enrollStudent()
• But it is not clear, how registration form is displayed & what is return view
<bean id="registerStudentController" class="com.springinaction.
training.mvc.RegisterStudentController">
<property name="studentService">
<ref bean="studentService"/>
</property>
<property name="formView">
<value>newStudentForm</value>
</property>
<property name="successView">
<value>studentWelcome</value>
</property>
</bean>
Page 103Classification: Restricted
• Disadv of doSubmitAction(): cannot return a model and view object. E.g..
When you wish to display the details of students after successful
registration.
• Use onSubmit()
protected ModelAndView onSubmit(Object command, BindException
errors) throws Exception {
Student student = (Student) command;
studentService.enrollStudent(student);
return new ModelAndView(getSuccessView(),"student", student); }
Page 104Classification: Restricted
Validating Form Input
• The org.springframework.validation.Validator interface accommodates
validation for Spring MVC.
public interface Validator {
void validate(Object obj, Errors errors);
boolean supports(Class clazz);
}
• Examines the fields of the object passed into the validate() method and
reject any invalid values via the Errors object.
• supports() method is used to help Spring determine whether or not the
validator can be used for a given class.
Page 105Classification: Restricted
public class StudentValidator implements Validator {
public boolean supports(Class clazz) {
return clazz.equals(Student.class);}
public void validate(Object command, Errors errors) {
Student student = (Student) command;
ValidationUtils.rejectIfEmpty( errors, "login",
"required.login","Login is required");
ValidationUtils.rejectIfEmpty( errors, "password",
"required.password", "Password is required"); ….}}
<bean id="registerStudentController"
class="com.springinaction.training.mvc.RegisterStudentController">
……
<property name="validator">
<bean class="com.springinaction.training.mvc.StudentValidator"/>
</property>
</bean>
Page 106Classification: Restricted
Resolving Views
• In Spring MVC, a view is a bean that renders results to the user.
• Rendering depends on the type of view used: J
• JSP, Pdf, Excel sheet, Velocity and FreeMarker templates.
• View Resolvers are used to resolve the logical view to a View Bean
• Internal available resolvers:
• InternalResourceViewResolver
• BeanNameViewResolver
• ResourceBundleViewResolver
• XmlViewResolver
Page 107Classification: Restricted
Working with other Web Frameworks
Page 108Classification: Restricted
Working with Jakarta-Struts
• Consider how would you retrieve list of all courses in Struts.
public class ListCourseAction extends Action {
private CourseService courseService;
public ActionForward execute( ActionMapping mapping,
ActionForm form,
HttpServletRequest request, HttpServletResponse
response) throws Exception {
Set allCourses = courseService.getAllCourses();
request.setAttribute("courses", allCourses);
return mapping.findForward("courseList");
}
}
Page 109Classification: Restricted
Spring offers 2 types of Struts Integration
• Implementing Spring-aware Struts actions
• Delegating requests to Struts actions that are managed as Spring
beans
Before that:
• Register a Struts plug-in in struts-config.xml, that is aware of the Spring
application context
<plug-in
className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/training-servlet.xml,/WEB-INF/…"/>
</plug-in>
• ContextLoaderPlugIn loads a Spring application context (a
WebApplication-Context, to be specific) using the context configuration
files listed (comma separated) in its contextConfigLocation property.
Page 110Classification: Restricted
Implementing Spring-aware Struts actions
• Write all of your Struts action classes to extend a common base
class that has access to the Spring application context.
OR
• Spring comes with
org.springframework.web.struts.ActionSupport, an abstract
implementation of the org.apache.struts.action.Action
• It overrides the setServlet() method to retrieve the
WebApplicationContext from the Context-LoaderPlugIn
• Anytime your action needs to access a bean from the Spring
context, it just needs to call the getBean() method.
Page 111Classification: Restricted
Page 112Classification: Restricted
Disadvantages of Spring aware struts type:
• Action class directly uses Spring specific classes. This
tightly couples struts action code with spring
• The action class is responsible for looking up references to
Spring-managed beans. This is in direct opposition to the
notion of inversion of control (IoC)
Page 113Classification: Restricted
Delegating requests to Struts actions that are managed as Spring beans
• In the struts-config.xml write a proxy action.
• The proxy action will
• retrieve the application context from the ContextLoaderPlugIn
• look up the real Struts action from the spring context
• then delegate responsibility to the real Struts action.
• Spring provides org.springframework.web.struts.DelegatingActionProxy
class.
<action path="/listCourses"
type="org.springframework.web.struts.DelegatingActionProxy"/>
Page 114Classification: Restricted
ListCourse Action class
Page 115Classification: Restricted
• You don’t need to register ListCourseAction in struts-
config.xml. Instead, you register it as a bean in your Spring
context configuration file:
<bean name="/listCourses"
class="com.springinaction.training.struts.ListCourseActi
on">
<property name="courseService">
<ref bean="courseService"/>
</property>
</bean>
• Value of the name attribute must exactly match the path
attribute of the <action> in struts-config.xml.
• Adv: Spring is just another bean now and you can use
Spring’s IoC to wire service beans into the Struts action.
Page 116Classification: Restricted
Spring Security
Page 117Classification: Restricted
Spring Security (Acegi security) Features
• Single Sign on
• Reuses your Spring expertise: Spring application contexts
for all configuration
• Provide a comprehensive ACL(Access Control list) package
• Keeps your objects free of security code
• http://acegisecurity.org/index.html
Page 118Classification: Restricted
Spring and Integration
• Spring is essentially an integration platform
•Aims to provide a POJO model in whatever environment,
with whatever services
• Minimal system requirements
•Spring runs in Java 1.3 and above
•Takes advantage of 1.4 and 5.0 features if available
• Spring offers portability between different environments
• Integrates with a large number of products
•Quartz scheduler
•Velocity template engine
•Jasper reports etc
Page 119Classification: Restricted
Spring in a J2EE Environment
• Does not violate J2EE programming restrictions
• Provides services on any J2EE application server
•Runs well on current, stable servers such as WebSphere
4.0–6.0 and WebLogic 6.1-9.0
• Although Spring is an alternative to EJB in many cases, it
provides services for invoking and implementing EJBs
•Codeless EJB proxies, exposing a POJO interface
•Implementing EJBs that internally use Spring
Page 120Classification: Restricted
Momentum Around Spring
• Books:
• Pro Spring (Rod Harrop)
• J2EE without EJB (Rod Johnson, Juergen Hoeller)
• Spring In Action(Craig Walls, Ryan Breidenbach)
• Java Development with the Spring Framework (Rod
Johnson et al.)
• Expert One-on-One: J2EE Design and Development (Rod
Johnson)
• Websites:
• www.springframework.org
• www.springhub.com
• http://martinfowler.com/articles/injection.html
• http://www.roseindia.net/spring/index.shtml
Page 121Classification: Restricted
Who’s using Spring?
Spring is widely used in many industries, including…
• Banking: HSBC Investment Bank, DekaBank, BNP Paribas, BBS, CSFB (New
York), Goldman Sachs, JP Morgan (Bank One)
• Transactional Web applications, message-driven middleware
• Retail and investment banking
• Scientific research
• Defence(Norwegian military)
• A growing number of Fortune 500 companies
• High volume Web sites
• Significant enterprise usage, not merely adventurous early adopters
Page 122Classification: Restricted
Thank You

More Related Content

What's hot

Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Pei-Tang Huang
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting Started
Murat Doğan
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
Surekha Gadkari
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Serhat Can
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
Javier Lafora Rey
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
Hùng Nguyễn Huy
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
Jadson Santos
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
iFour Technolab Pvt. Ltd.
 
Reactjs
Reactjs Reactjs
Reactjs
Neha Sharma
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
Dzmitry Naskou
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Hùng Nguyễn Huy
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
Rohit Gupta
 
Spring Boot
Spring BootSpring Boot
Spring Boot
koppenolski
 
Spring boot
Spring bootSpring boot
Spring boot
sdeeg
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jaran Flaath
 

What's hot (20)

Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting Started
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Reactjs
Reactjs Reactjs
Reactjs
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 

Similar to Java Spring

Spring
SpringSpring
Spring
Suman Behara
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
Vibrant Technologies & Computers
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
Kongu Engineering College, Perundurai, Erode
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
Manav Prasad
 
Spring intro classes-in-mumbai
Spring intro classes-in-mumbaiSpring intro classes-in-mumbai
Spring intro classes-in-mumbai
vibrantuser
 
Learn spring at amc square learning
Learn spring at amc square learningLearn spring at amc square learning
Learn spring at amc square learning
ASIT Education
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to SpringSujit Kumar
 
Introduction to j2 ee frameworks
Introduction to j2 ee frameworksIntroduction to j2 ee frameworks
Introduction to j2 ee frameworks
Mukesh Kumar
 
Developing modular Java applications
Developing modular Java applicationsDeveloping modular Java applications
Developing modular Java applications
Julien Dubois
 
Spring ppt
Spring pptSpring ppt
Spring ppt
Mumbai Academisc
 
TheSpringFramework
TheSpringFrameworkTheSpringFramework
TheSpringFrameworkShankar Nair
 
Spring presentecion isil
Spring presentecion isilSpring presentecion isil
Spring presentecion isilWilly Aguirre
 
Spring presentecion isil
Spring presentecion isilSpring presentecion isil
Spring presentecion isil
Willy Aguirre
 
Transforming to Microservices
Transforming to MicroservicesTransforming to Microservices
Transforming to Microservices
Kyle Brown
 
Spring framework
Spring frameworkSpring framework
Spring frameworkKani Selvam
 

Similar to Java Spring (20)

Spring
SpringSpring
Spring
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Spring intro classes-in-mumbai
Spring intro classes-in-mumbaiSpring intro classes-in-mumbai
Spring intro classes-in-mumbai
 
spring
springspring
spring
 
Spring
SpringSpring
Spring
 
Learn spring at amc square learning
Learn spring at amc square learningLearn spring at amc square learning
Learn spring at amc square learning
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to Spring
 
Introduction to j2 ee frameworks
Introduction to j2 ee frameworksIntroduction to j2 ee frameworks
Introduction to j2 ee frameworks
 
Developing modular Java applications
Developing modular Java applicationsDeveloping modular Java applications
Developing modular Java applications
 
Spring Framework Rohit
Spring Framework RohitSpring Framework Rohit
Spring Framework Rohit
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
TheSpringFramework
TheSpringFrameworkTheSpringFramework
TheSpringFramework
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring presentecion isil
Spring presentecion isilSpring presentecion isil
Spring presentecion isil
 
Spring presentecion isil
Spring presentecion isilSpring presentecion isil
Spring presentecion isil
 
Transforming to Microservices
Transforming to MicroservicesTransforming to Microservices
Transforming to Microservices
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring framework
Spring frameworkSpring framework
Spring framework
 

More from AathikaJava

Java While Loop
Java While LoopJava While Loop
Java While Loop
AathikaJava
 
Java Webservices
Java WebservicesJava Webservices
Java Webservices
AathikaJava
 
Java Type Casting
Java Type Casting Java Type Casting
Java Type Casting
AathikaJava
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
AathikaJava
 
Java Session
Java SessionJava Session
Java Session
AathikaJava
 
Java Servlet Lifecycle
Java Servlet LifecycleJava Servlet Lifecycle
Java Servlet Lifecycle
AathikaJava
 
Java Rest
Java Rest Java Rest
Java Rest
AathikaJava
 
Java Request Dispatcher
Java Request DispatcherJava Request Dispatcher
Java Request Dispatcher
AathikaJava
 
Java Polymorphism Part 2
Java Polymorphism Part 2Java Polymorphism Part 2
Java Polymorphism Part 2
AathikaJava
 
Java MVC
Java MVCJava MVC
Java MVC
AathikaJava
 
Java Polymorphism
Java PolymorphismJava Polymorphism
Java Polymorphism
AathikaJava
 
Mapping Classes with Relational Databases
Mapping Classes with Relational DatabasesMapping Classes with Relational Databases
Mapping Classes with Relational Databases
AathikaJava
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
AathikaJava
 
Java Encapsulation and Inheritance
Java Encapsulation and Inheritance Java Encapsulation and Inheritance
Java Encapsulation and Inheritance
AathikaJava
 
Hibernate basics
Hibernate basicsHibernate basics
Hibernate basics
AathikaJava
 
Java Filters
Java FiltersJava Filters
Java Filters
AathikaJava
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
AathikaJava
 

More from AathikaJava (17)

Java While Loop
Java While LoopJava While Loop
Java While Loop
 
Java Webservices
Java WebservicesJava Webservices
Java Webservices
 
Java Type Casting
Java Type Casting Java Type Casting
Java Type Casting
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Java Session
Java SessionJava Session
Java Session
 
Java Servlet Lifecycle
Java Servlet LifecycleJava Servlet Lifecycle
Java Servlet Lifecycle
 
Java Rest
Java Rest Java Rest
Java Rest
 
Java Request Dispatcher
Java Request DispatcherJava Request Dispatcher
Java Request Dispatcher
 
Java Polymorphism Part 2
Java Polymorphism Part 2Java Polymorphism Part 2
Java Polymorphism Part 2
 
Java MVC
Java MVCJava MVC
Java MVC
 
Java Polymorphism
Java PolymorphismJava Polymorphism
Java Polymorphism
 
Mapping Classes with Relational Databases
Mapping Classes with Relational DatabasesMapping Classes with Relational Databases
Mapping Classes with Relational Databases
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Java Encapsulation and Inheritance
Java Encapsulation and Inheritance Java Encapsulation and Inheritance
Java Encapsulation and Inheritance
 
Hibernate basics
Hibernate basicsHibernate basics
Hibernate basics
 
Java Filters
Java FiltersJava Filters
Java Filters
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 

Recently uploaded

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 

Recently uploaded (20)

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 

Java Spring

  • 2. Page 1Classification: Restricted Agenda • Understand Spring framework overview & its salient features • Spring concepts (IoC container / DI) • Spring-AOP basics • Spring ORM / Spring DAO overview • Spring Web / MVC overview
  • 3. Page 2Classification: Restricted Why a new framework? • Because of many problems with traditional J2EE Architecture • Complexity • EJB, JNDI, JTA, JDBC etc • Too many APIs • EJB is over used • Simply lots of code • Petstore as an example • Much of the code is “Plumbing code” • Heavy weight runtime environment • Hard to Unit Test • Components need to be explicitly deployed to be able to run, even for testing • Slow change-deploy-test cycle
  • 4. Page 3Classification: Restricted Enter Lightweight Containers • Frameworks are central to modern J2EE development • Many projects encounter the same problems • Service location • Consistent exception handling • Parameterizing application code… • J2EE “out of the box” does not provide a complete (or ideal) programming model • Result: • many in-house frameworks • Expensive to maintain and develop • Better to share experience across many projects • Choose Opensource framework
  • 5. Page 4Classification: Restricted How do Lightweight Containers Work? • Inversion of Control/Dependency Injection • Sophisticated configuration for POJOs • Aspect Oriented Programming (AOP) • Provide declarative services to POJOs • Out-of-the box (transaction management, security) or custom (auditing) • Aim to provide a consistent framework for development • The Spring Framework and HiveMind are the most compelling offerings • Spring is the most complete, mature and popular
  • 6. Page 5Classification: Restricted Spring Framework • The Spring Framework • Open source project • Apache 2.0 license • Initially written by Rod Johnson and Juergen Hoeller • 21 developers • Interface21 lead development effort, with seven committers (and counting), including the two project leads • Aims • Simplify J2EE development • Provide a comprehensive solution to developing applications built on POJOs • Provide services for applications ranging from simple web apps up to large financial/“enterprise” applications
  • 7. Page 6Classification: Restricted Spring Framework history • Started 2002/2003 by Rod Johnson and Juergen Holler • Started as a framework developed around Rod Johnson’s book Expert One-on-One J2EE Design and Development • Spring 1.0 Released March 2004 • Spring 1.2 - 2005 • Spring 2.0 – October 2006 • Spring 2.5 – November 2007
  • 8. Page 7Classification: Restricted Spring Framework mission Mission Statement • We believe that: • J2EE should be easier to use • It is best to program to interfaces, rather than classes. Spring reduces the complexity cost of using interfaces to zero. • JavaBeans offer a great way of configuring applications. • OO design is more important than any implementation technology, such as J2EE. • Checked exceptions are overused in Java. A framework shouldn't force you to catch exceptions you're unlikely to be able to recover from. • Testability is essential, and a framework such as Spring should help make your code easier to test. Our philosophy is summarized in Expert One-on-One J2EE Design and Development by Rod Johnson. We aim that: • Spring should be a pleasure to use • Your application code should not depend on Spring APIs • Spring should not compete with good existing solutions, but should foster integration. (For example, JDO, Toplink, and Hibernate are great O/R mapping solutions. We don't need to develop another one.)
  • 9. Page 8Classification: Restricted What is Spring Framework? Spring is a lightweight, inversion of control and aspect-oriented container framework. • Lightweight: • In terms of both size and overhead. • Entire framework can be distributed in single JAR file(1MB) • Processing overhead required is negligible • Is non intrusive: objects have no dependency on Spring specific classes • Inversion of Control: • Promotes loose coupling through use of IoC • Instead of an object looking up dependencies from a container, the container gives the dependencies to the object at instantiation without waiting to be asked (reverse of JNDI)
  • 10. Page 9Classification: Restricted What is Spring Framework? Contd. • Aspect-oriented: • Enables cohesive development by separating application business logic from system services • Application objects focus on business logic not other system concerns such as logging, transaction management • Container: • It contains and manages the life cycle of application objects • You can configure how each of your bean should be created, a single instance (singleton) or new instance each time (prototype) • Framework: • Spring makes it possible to configure and compose complex applications from simpler components. • application objects are composed declaratively, typically in an XML file • Provides infrastructure functionality (transaction management, persistence framework integration, etc.) Code which is cleaner, more manageable and easy to test
  • 12. Page 11Classification: Restricted Spring Framework Overview – contd. • Core module • is the most fundamental part of the framework and provides the IoC and Dependency Injection features • Defines how beans are created, configured, and managed—more of the nuts-and-bolts of Spring. Here you’ll find Spring’s BeanFactory, the heart of any Spring-based application • Application Context module • The core module’s BeanFactory makes Spring a container, but the context module is what makes it a framework. • Add supports for i18n messages, application lifecycle events, validation etc • Supplies many enterprise services such as e-mail, EJB integration, remoting, and scheduling and integration with templating frameworks such as Velocity and FreeMarker.
  • 13. Page 12Classification: Restricted Spring Framework Overview – contd. • Spring’s AOP module • Serves as the basis for developing your own aspects for your Spring- enabled application. • Ensures interoperability between Spring and other Java AOP frameworks • Supports metadata programming ( aspects can be configured using annotations) • JDBC Abstraction and DAO module • Working with JDBC often results in a lot of boilerplate code • Abstracts away the boilerplate code and prevents problems that result from a failure to close database resources • Uses Spring AOP module to provide Transaction management services
  • 14. Page 13Classification: Restricted Spring Framework Overview – contd. • Object/Relational mapping integration module • Provide hooks into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. • Spring’s transaction management supports each of these ORM frameworks as well as JDBC. • Spring’s Web module • Builds on the application context module • Support for several web-oriented tasks • e.g. transparently handling multipart requests • programmatic binding of request parameters to your business objects • contains integration support with Jakarta Struts. • Spring’s MVC framework and can take advantage of Spring’s services (for e.g. i18n, validation etc.
  • 16. Page 15Classification: Restricted Spring Core and Application Context
  • 18. Page 17Classification: Restricted Bean Factory • It is an implementation of Factory design pattern • Instantiation of beans • Configuration • Management of one or more beans • Create associations between collaborating objects as they are instantiated, thus giving fully configured, ready to use objects
  • 19. Page 18Classification: Restricted Bean Factory API Hierarchy
  • 20. Page 19Classification: Restricted Hello World! package com.example.hello; public interface GreetingService { public void sayGreeting(); } package com.example.hello; public class GreetingServiceImpl implements GreetingService { private String greeting; public GreetingServiceImpl() {} public GreetingServiceImpl(String greeting) { this.greeting = greeting; } public void sayGreeting() { System.out.println(greeting); } public void setGreeting(String greeting) { this.greeting = greeting; } }
  • 21. Page 20Classification: Restricted Hello World! – application-context.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> The root element <bean id="greetingService“ Bean instance class="com.example.hello.GreetingServiceImpl"> <property name="greeting"> <value>Hello World</value> </property> </bean> </beans>
  • 22. Page 21Classification: Restricted Hello World! – contd. import java.io.FileInputStream; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; public class HelloApp { public static void main(String[] args) throws Exception { BeanFactory factory = new XmlBeanFactory(new FileInputStream("hello.xml")); GreetingService greetingService = (GreetingService) factory.getBean("greetingService"); greetingService.sayGreeting(); }
  • 23. Page 22Classification: Restricted The Spring IoC container The Spring Container Fully Configured System Ready for User Configuration Metadata Your Business Objects (POJOs)
  • 24. Page 23Classification: Restricted What is Inversion of Control (IoC)? (besides yet another confusing term for a simple concept) • IoC is all about Object dependencies. • Traditional "Pull" approach: • Direct instantiation • Asking a Factory for an implementation • Looking up a service via JNDI • "Push" approach: • Something outside of the Object "pushes" its dependencies into it. • The Object has no knowledge of how it gets its dependencies, it just assumes they are there. • Hollywood Principle • Don’t call me, I’ll call you • Means that the framework calls your code, not the reverse • The "Push" approach is called "Dependency Injection". (Next slide)
  • 25. Page 24Classification: Restricted What is Dependency Injection? • A specialization of Inversion of Control • The container injects dependencies into object instances using Java methods • Dependencies may be collaborating objects or primitive or simple types • This is also known as push configuration • Configuration values are pushed into objects, rather than pulled by the objects from an environment such as JNDI or a properties file
  • 26. Page 25Classification: Restricted Inversion of Control Types • Type 1: Interface injection • Dependency satisfied by interfaces it implemented (Used by Apache’s Avalon Framework) • Type 2: Setter injection • Dependency satisfied by JavaBean properties and its setter/getter exposed by a component • Type 3: Constructor injection • Dependency satisfied by the component’s constructor • Spring supports Type 2, Type 3 IoC • Note: Other Lightweight containers • Pico Container, Nano Container • HiveMind • Avalaon
  • 27. Page 26Classification: Restricted Dependency Injection using setters <bean id=”ex1” class=”ExBean1”> <property name=”bean”> <ref bean=”ex2”/> </property> </bean> <bean id=”ex2” class=”ExBean2”/> public class ExBean1 { private ExBean2 bean; public void setBean(ExBean2 bean) { this.bean = bean; } } • The <ref> subelement of <property> helps refer to another bean. • You can also wire collections such as list, set, map, properties as subelements of <property>
  • 28. Page 27Classification: Restricted <bean id="courseService“ class="com.springinaction.service.training.CourseService Impl"> <property name="studentService"> <ref bean="studentService"/> </property> </bean> The container gives the courseService bean a StudentService bean (through setStudentService()), thereby freeing CourseServiceImpl from having to look up a StudentService bean on its own. Disadvantages: • When this type of bean is instantiated, none of its properties have been set and it could possibly be in an invalid state.
  • 29. Page 28Classification: Restricted Dependency Injection using Constructors <bean id="studentService“ class="com.springinaction.training.service.StudentServiceImpl" > <constructor-arg> <ref bean="studentDao"/> </constructor-arg> </bean> Advantages: • A bean cannot be instantiated without being given all of its dependencies. It is perfectly valid and ready to use upon instantiation. • No need for superfluous setter methods. This helps keep the lines of code at a minimum • By only allowing properties to be set through the constructor, you are, in effect, making those properties immutable.
  • 30. Page 29Classification: Restricted Dependency Injection using Constructors - Contd Drawback: • If a bean has several dependencies, the constructor’s parameter list can be quite lengthy. • If there are several ways to construct a valid object, it can be hard to come up with unique constructor. Since constructor signatures vary only by the number and type of parameters. • If a constructor takes two or more parameters of the same type, it may be difficult to determine what each parameter’s purpose is. • Constructor injection does not lend itself readily to inheritance. A bean’s constructor will have to pass parameters to super() in order to set private properties in the parent object.
  • 31. Page 30Classification: Restricted Why is push better than pull? • No more ad-hoc lookup • Code is self-documenting, describing its own dependencies • Easy to unit test • No JNDI to stub, properties files to substitute, RDBMS data to set up • Simply instantiate class in a JUnit test and use setters or constructors
  • 32. Page 31Classification: Restricted Spring Special Beans • By implementing certain interfaces Spring can treat some beans as being special—as being part of the Spring framework itself • For e.g. Special Beans can be used – • Become involved in the bean’s and the bean factory’s life cycles by postprocessing bean configuration • Load configuration information from external property files • Load textual messages from property files, including internationalized messages • Listen for and respond to application events that are published by other beans and by the Spring container itself • Are aware of their identity within the Spring container
  • 33. Page 32Classification: Restricted For e.g. Externalizing the configuration Load configuration information from external property files. <bean id="propertyConfigurer" class="org.springframework.beans. factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>jdbc.properties</value> <value>security.properties</value> </list> </property> </bean>
  • 34. Page 33Classification: Restricted For e.g. Externalizing the configuration contd. In the jdbc.properties file: database.url=jdbc:hsqldb:Training database.driver=org.hsqldb.jdbcDriver database.user=appUser database.password=password Applying the placeholder variables to the data source configuration: <bean id="dataSource“ class="org.springframework. jdbc.datasource.DriverManagerDataSource"> <property name="url"> <value>${database.url}</value> </property> <property name="driverClassName"> <value>${database.driver}</value> </property> <bean>
  • 35. Page 34Classification: Restricted Special Beans Contd. • Making Beans Aware. • By implemementing BeanNameAware and ApplicationContextAware interfaces, beans can be made aware of their name, their BeanFactory, and their ApplicationContext, respectively. • By implementing these interfaces, a bean becomes coupled with Spring.
  • 38. Page 37Classification: Restricted Spring AOP • Enables to modularize application concerns • Helps support declarative transaction.
  • 39. Page 38Classification: Restricted What is AOP? • Paradigm for modularizing crosscutting code • Code that would otherwise be scattered across multiple methods or objects can be gathered in one place
  • 40. Page 39Classification: Restricted Calls to system-wide concerns such as logging and security are often scattered about in modules where those concerns are not their primary concern
  • 41. Page 40Classification: Restricted • Using AOP, system wide concerns blanket the components that they impact.
  • 42. Page 41Classification: Restricted Before AOP Client Method 1. Security check 2. Obtain session 3. Log it to the file 4. Audit trail 5. Start transaction 6. Business Logic 7. Commit 8. Exception handling
  • 43. Page 42Classification: Restricted AOP applied Client Method 1. Business Logic 1. Security check 2. Obtain session 3. Log it to the file 4. Audit trail 5. Start transaction 1. Commit 1. Exception handling
  • 44. Page 43Classification: Restricted AOP Interception • In the simplest case, think about interception • Callers invoke a proxy • A chain of interceptors/advice decorate the method call as execution flows toward the target • Interceptors provide services such as transaction management or security checks • These services are often specified declaratively
  • 46. Page 45Classification: Restricted AOP Terms • Aspect • The cross-cutting functionality e.g.. Logging • Jointpoint • Point in the execution of the application where an aspect can be plugged in. • e.g. method being called, an exception being thrown, or even a field being modified. • Advice • Actual implementation of our aspect.It is inserted into our application at pointcut • Different types of advice include "around," "before" and "after" advice. • Pointcut • A pointcut defines at what joinpoints advice should be applied. • for e.g. the execution of a method with a certain name • Some AOP frameworks allow you to create dynamic pointcuts.
  • 47. Page 46Classification: Restricted AOP Terms • Introduction • An introduction allows you to add new methods or attributes to existing classes • Target • A target is the class that is being advised. • Proxy • A proxy is the object created by AOP framework after applying advice to the target object. • As far as the client objects are concerned, the target object (pre-AOP) and the proxy object (post-AOP) are the same • Weaving • Weaving is the process of applying aspects to a target object to create a new, proxied object either during target classes’s compile time, classload time, runtime.
  • 49. Page 48Classification: Restricted Advantages and Drawbacks of AOP • Advantages: • Decoupling between classes • A clear line between the different application layers • Reduction of code duplication • Better support for refactoring • Drawbacks • Steep learning curve • AOP imposes several requirements on the programming language used
  • 50. Page 49Classification: Restricted Spring AOP • Aspects written in java • Pointcut written in XML in Spring Configuration File. • Spring supports only method joinpoints. • Other AOP frameworks requires special syntax which is not the case with Spring • Other AOP frameworks are AspectJ, AspectWerkz, JbossAOP, EAOP, DynamicAspects
  • 51. Page 50Classification: Restricted Creating Advice • Creating the advice object means writing code to implement the cross cutting functionality. • Advice Types in Spring:
  • 52. Page 51Classification: Restricted Example for Before advice type public interface EMart{ Chocolate buyChocolate(Customer customer) throws EMartException; } public class XYZEMart implements EMart{ public Chocolate buyChocolate(Customer customer) throws EMartException { return new Chocolate();} } public interface MethodBeforeAdvice { void before(Method method, Object[] args, Object target) throws Throwable } The parameters are the target method, the arguments passed to the method and target object of method invocation.
  • 53. Page 52Classification: Restricted import org.springframework.aop.MethodBeforeAdvice; public class WelcomeAdvice implements MethodBeforeAdvice { public void before(Method method, Object[] args, Object target) { Customer customer = (Customer) args[0]; System.out.println("Hello " + customer.getName());} } Configure the spring configuration file to apply the advice
  • 54. Page 53Classification: Restricted <beans> <bean id="EMartTarget“ class=“XYZEMart"/> create proxy target object <bean id="welcomeAdvice“ class="WelcomeAdvice"/> create advice <bean id="EMart“tell Spring to create a proxy bean class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>EMart</value>implement EMart interface </property> <property name="interceptorNames"> <list> apply advice object to incoming calls <value>welcomeAdvice</value> </list> </property> <property name="target"> use XYZEMart bean as target object <ref bean=“EMartTarget"/> </property> </bean> </beans> A bean is loaded whose interface matches EMart. This bean is then tied to the implementation class XYZEMart
  • 55. Page 54Classification: Restricted Spring Framework: Before and After Returning Advice
  • 56. Page 55Classification: Restricted AOP Pointcut • Tells us where the advice should be applied. • Spring defines pointcuts in terms of the class and method that is being advised. • To determine if a method is eligible for advising we implement the interface: public interface MethodMatcher { boolean matches(Method m, Class targetClass); public boolean isRuntime(); public boolean matches(Method m, Class target, Object[] args); }
  • 57. Page 56Classification: Restricted Spring Advisors • Most aspects are a combination of advice that defines the aspect’s behavior and a pointcut defining where the aspect should be executed. • Spring therefore, offers advisors, which combine advice and pointcuts into one object. public interface PointcutAdvisor { Pointcut getPointcut(); Advice getAdvice(); } • Most of Spring’s built-in pointcuts also have a corresponding PointcutAdvisor.
  • 58. Page 57Classification: Restricted Types of Pointcuts • Static Pointcuts • NameMatchedMethodPointcut class has 2 methods: – public void setMappedName(String) – public void setMappedNames(String[]) • RegexpMethodPointcut • Dynamic Pointcuts • Any Pointcut's implementation with isRuntime() == true • Built-in dynamic pointcut : ControlFlowPointcut
  • 59. Page 58Classification: Restricted Example of Static Pointcut • Setting the mappedName property to set* will match all setter methods. <bean id="frequentCustomerPointcutAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdv isor"> <property name="mappedName"> <value>buy*</value> </property> <property name="advice"> <ref bean=“welcomeAdvice"/> </property> </bean>…..ProxyFactoryBean • When our proxy is created, invocations of any method on our target object, that begins with buy will be advised by our welcomeAdvice. • This matching only applies to the method name and not the fully qualified name that includes the class name as well.
  • 61. Page 60Classification: Restricted Using ProxyFactoryBean • ProxyFactoryBean creates proxied objects. • It has properties that control its behavior. • ProxyFactoryBean properties: • target: The target bean of the proxy. The object that has to adviced. • proxyInterfaces: A list of interfaces that must be implemented by the proxy (beans created by the factory). You can specify single interface or a list of interfaces. • interceptorNames: The bean names of the advice to be applied to the target.
  • 63. Page 62Classification: Restricted Springs DAO philosophy • Service objects are accessing the DAOs through interfaces. • Advantages: • Easy unit testing of service objects (DAI can be mocked) • Data Access Interface does not expose what technology it is using to access data
  • 64. Page 63Classification: Restricted Spring’s DataAccessException • Spring’s DAO frameworks do not throw technology-specific exceptions, such as SQLException or HibernateException. • All exceptions thrown are subclasses of org.springframework.dao.DataAccessException. • DataAccessException is a RuntimeException, so it is an unchecked exception. Thus the code will not be required to handle these exceptions when they are thrown by the data access tier.
  • 66. Page 65Classification: Restricted Working with DataSources • Getting a DataSource from JNDI: <bean id="dataSource“ class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>java:comp/env/jdbc/myDatasource</value> </property> </bean> • Spring separates the fixed and variant parts of the data access process into two distinct classes: • templates : Templates manage the fixed part of the process like controlling transactions, managing resources, and handling exceptions • Callbacks: Implementations of the callback interfaces define what is specific to your application—creating statements, binding parameters
  • 71. Page 70Classification: Restricted • Create prepared stmt and set the parameters are the only unique lines of code. • The rest is a boilerplate code.( Cleaning resources, handling errors- which is equally important) • Spring’s JDBC framework will take care of resource management and handling errors. • Spring’s data access frameworks incorporate a template class. In this case, it is the JdbcTemplate class. Using JDBCTemplate
  • 72. Page 71Classification: Restricted • To make use of the JdbcTemplate, each of your DAO classes needs to be configured with a JdbcTemplate instance: public class StudentDaoJdbc implements StudentDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate;} ….} Using JDBCTemplate
  • 73. Page 72Classification: Restricted Writing Data • We create a PreparedStatement from a SQL string and then bind parameters, JdbcTemplate provides an execute(String sql, Object[] params) method
  • 74. Page 73Classification: Restricted Spring’s Transaction Manager • Spring does not directly manage transactions • It has transaction managers that delegate responsibility for transaction management to platform-specific transaction implementation provided by either JTA or persistence mechanism.
  • 75. Page 74Classification: Restricted Spring’s Transaction Manager Contd
  • 76. Page 75Classification: Restricted Springs ORM framework Support •Spring provides integration for •Sun’s standard persistence API JDO, •as well as the open source ORM frameworks: •Hibernate •Apache OJB •iBATIS SQL Maps
  • 77. Page 76Classification: Restricted Remoting • Remoting is a conversation between a client application and a service. • The remote application exposes the functionality through a remote service. • Spring supports RPC for six different RPC models: • Remote Method Invocation (RMI) • Caucho’s Hessian and Burlap • Spring’s own HTTP invoker • Enterprise JavaBeans (EJB) • Web services
  • 78. Page 77Classification: Restricted RPC Models supported by Spring
  • 80. Page 79Classification: Restricted Advantages of Spring Remoting • Regardless of whether you are using RMI, Hessian, Burlap, HTTP invoker, EJB, or web services, you can wire remote services into your application as if they were POJOs. • Spring even catches any RemoteExceptions that are thrown and rethrows runtime RemoteAccessExceptions in their place, freeing your code from having to deal with an exception that it probably can’t recover from • Spring hides many of the details of remote services, making them appear as though they are local JavaBeans
  • 82. Page 81Classification: Restricted Life Cycle of a Request- Spring MVC Front Controller Handles request Maps url Pattern Request Logical name of View Renders Response Web Browser
  • 83. Page 82Classification: Restricted A. Dispatcher Servlet • Must be configured in web.xml <servlet> <servlet-name>training</servlet-name> training-servlet.xml <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>training</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> <taglib> <taglib-uri>/spring</taglib-uri> <taglib-location>/WEB-INF/spring.tld</taglib-location> </taglib>
  • 84. Page 83Classification: Restricted Breaking up the Application Context
  • 85. Page 84Classification: Restricted • Configure context loader in web.xml • A context loader loads context configuration files in addition to the one that DispatcherServlet loads. • Two context loaders to choose from: • ContextLoaderListener Used when Web Container supports Servlet 2.3 or higher and initializes servlet listeners before servlets. • ContextLoaderServlet.
  • 86. Page 85Classification: Restricted • For ContextLoaderListener <listener> <listener- class>org.springframework.web.context.ContextLoaderListener</listener- class> </listener> • For ContextLoaderServlet <servlet> <servlet-name>context</servlet-name> <servlet- class>org.springframework.web.context.ContextLoaderServlet</servlet- class> <load-on-startup>1</load-on-startup> </servlet> • Specify one or more Spring configuration files for the context loader to load <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/training-service.xml, /WEB-INF/training-data.xml </param-value> </context-param>
  • 87. Page 86Classification: Restricted Spring MVC in a Nutshell • Minimum steps required to create home page for a Spring training example. 1.Write the controller class that performs the logic behind the homepage. 2.Configure the controller in the DispatcherServlet’s context configuration file (training-servlet.xml). 3.Configure a view resolver to tie the controller to the JSP. 4.Write the JSP that will render the homepage to the user.
  • 88. Page 87Classification: Restricted Building the Controller public class HomeController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("home", "message", greeting); } private String greeting; public void setGreeting(String greeting) { this.greeting = greeting;} } • Similar to struts action but just a simple java bean in application context, therefore can make use of all the IoC and AOP, for e.g.. Greeting is set using IoC
  • 89. Page 88Classification: Restricted Configuring the Controller Bean • Configure it in the DispatcherServlet’s context configuration file (which in this case is training-servlet.xml) <bean name="/home.htm“ class="com.springinaction.training.mvc.HomeController"> <property name="greeting"> <value>Welcome to Spring Training!</value> </property> </bean>
  • 90. Page 89Classification: Restricted Declaring a View Resolver • Configure it in the DispatcherServlet’s context configuration file (which in this case is training-servlet.xml) • In the case of HomeController, we need a view resolver to resolve “home” to a JSP file that renders the home page. <bean id="viewResolver" class="org.springframework.web. servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean>
  • 91. Page 90Classification: Restricted Creating the JSP • Name this JSP “home.jsp” and to place it in the /WEB-INF/jsp folder within your web application. That’s where InternalResourceViewResolver will try to find it. <html> <head><title>Spring Training, Inc.</title></head> <body> <h2>${message}</h2> </body> </html>
  • 92. Page 91Classification: Restricted Quick Recap 1 DispatcherServlet receives a request whose URL pattern is “/home.htm”. 2 DispatcherServlet consults BeanNameUrlHandlerMapping to find a controller whose bean name is “/home.htm”, finding the HomeController bean. 3 DispatcherServlet dispatches the request to HomeController for processing. 4 HomeController returns a ModelAndView object with a logical view name of ‘home’. 5 DispatcherServlet consults its view resolver (configured as InternalResourceViewResolver) to find a view whose logical name is home. Internal-ResourceViewResolver returns the path to /WEB-INF/jsp/home.jsp. 6 DispatcherServlet forwards the request to the JSP at /WEB-INF/jsp/home.jsp to render the home page to the user.
  • 94. Page 93Classification: Restricted Handler mapping • Mapping Requests to Controller • When associating a request with a specific controller, DispatcherServlet consults a handler mapping bean. • Handler mappings typically map a specific controller bean to a URL pattern • All of Spring MVC’s handler mappings implement the org.springframework.web.servlet.HandlerMapping interface. • Spring has three useful implementations of HandlerMapping
  • 95. Page 94Classification: Restricted Mapping requests to controllers • BeanNameUrlHandlerMapping— • Maps controllers to URLs that are based on the controllers’ bean name. • This is the default handler. <bean name="/home.htm“ class="com.springinaction.training.mvc.HomeController"></bean> • SimpleUrlHandlerMapping— • Maps controllers to URLs using a property collection defined in the context configuration file • CommonsPathMapHandlerMapping— • Maps controllers to URLs using source level metadata placed in the controller code. • Example /** * @@org.springframework.web.servlet.handler. commonsattributes.PathMap("/displayCourse.htm") */ public class DisplayCourseController extends AbstractCommandController {…}
  • 96. Page 95Classification: Restricted Example for SimpleUrlHandlermapping <bean id="simpleUrlMapping" class= "org.springframework.web.servlet.handler.SimpleUrlHandler Mapping"> <property name="mappings"> <props> <prop key="/listCourses.htm">listCoursesController</prop> <prop key="/register.htm">registerStudentController</prop> <prop key="/displayCourse.htm">displayCourseController</prop> <prop key="/login.htm">loginController</prop> <prop key="/enroll.htm">enrollController</prop> </props> </property> </bean>
  • 97. Page 96Classification: Restricted Handling Requests with Controllers
  • 98. Page 97Classification: Restricted Spring MVC’s selection of controller classes
  • 99. Page 98Classification: Restricted Examples • Simple Controller: • When you need to take no(or few parameters) e.g.. When you wish to display the list of all courses. • Command Controllers: • For e.g. after viewing a list of available courses, you may want to view more details about that course. • This controller will automatically bind parameters to a command object and provide hooks for you to plug in validators to ensure that the parameters are valid.
  • 101. Page 100Classification: Restricted Processing Form Submission E.g. Student registration Form Controllers add functionality to display a form when an HTTP GET request is received and process the form when an HTTP POST is received If any errors occur in processing the form, the controller will know to redisplay the form so that the user can correct the errors and resubmit
  • 103. Page 102Classification: Restricted • doSubmitAction() method handles the form submission (an HTTP POST request) by passing the command object (which happens to be a Student domain object) to enrollStudent() • But it is not clear, how registration form is displayed & what is return view <bean id="registerStudentController" class="com.springinaction. training.mvc.RegisterStudentController"> <property name="studentService"> <ref bean="studentService"/> </property> <property name="formView"> <value>newStudentForm</value> </property> <property name="successView"> <value>studentWelcome</value> </property> </bean>
  • 104. Page 103Classification: Restricted • Disadv of doSubmitAction(): cannot return a model and view object. E.g.. When you wish to display the details of students after successful registration. • Use onSubmit() protected ModelAndView onSubmit(Object command, BindException errors) throws Exception { Student student = (Student) command; studentService.enrollStudent(student); return new ModelAndView(getSuccessView(),"student", student); }
  • 105. Page 104Classification: Restricted Validating Form Input • The org.springframework.validation.Validator interface accommodates validation for Spring MVC. public interface Validator { void validate(Object obj, Errors errors); boolean supports(Class clazz); } • Examines the fields of the object passed into the validate() method and reject any invalid values via the Errors object. • supports() method is used to help Spring determine whether or not the validator can be used for a given class.
  • 106. Page 105Classification: Restricted public class StudentValidator implements Validator { public boolean supports(Class clazz) { return clazz.equals(Student.class);} public void validate(Object command, Errors errors) { Student student = (Student) command; ValidationUtils.rejectIfEmpty( errors, "login", "required.login","Login is required"); ValidationUtils.rejectIfEmpty( errors, "password", "required.password", "Password is required"); ….}} <bean id="registerStudentController" class="com.springinaction.training.mvc.RegisterStudentController"> …… <property name="validator"> <bean class="com.springinaction.training.mvc.StudentValidator"/> </property> </bean>
  • 107. Page 106Classification: Restricted Resolving Views • In Spring MVC, a view is a bean that renders results to the user. • Rendering depends on the type of view used: J • JSP, Pdf, Excel sheet, Velocity and FreeMarker templates. • View Resolvers are used to resolve the logical view to a View Bean • Internal available resolvers: • InternalResourceViewResolver • BeanNameViewResolver • ResourceBundleViewResolver • XmlViewResolver
  • 108. Page 107Classification: Restricted Working with other Web Frameworks
  • 109. Page 108Classification: Restricted Working with Jakarta-Struts • Consider how would you retrieve list of all courses in Struts. public class ListCourseAction extends Action { private CourseService courseService; public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Set allCourses = courseService.getAllCourses(); request.setAttribute("courses", allCourses); return mapping.findForward("courseList"); } }
  • 110. Page 109Classification: Restricted Spring offers 2 types of Struts Integration • Implementing Spring-aware Struts actions • Delegating requests to Struts actions that are managed as Spring beans Before that: • Register a Struts plug-in in struts-config.xml, that is aware of the Spring application context <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/training-servlet.xml,/WEB-INF/…"/> </plug-in> • ContextLoaderPlugIn loads a Spring application context (a WebApplication-Context, to be specific) using the context configuration files listed (comma separated) in its contextConfigLocation property.
  • 111. Page 110Classification: Restricted Implementing Spring-aware Struts actions • Write all of your Struts action classes to extend a common base class that has access to the Spring application context. OR • Spring comes with org.springframework.web.struts.ActionSupport, an abstract implementation of the org.apache.struts.action.Action • It overrides the setServlet() method to retrieve the WebApplicationContext from the Context-LoaderPlugIn • Anytime your action needs to access a bean from the Spring context, it just needs to call the getBean() method.
  • 113. Page 112Classification: Restricted Disadvantages of Spring aware struts type: • Action class directly uses Spring specific classes. This tightly couples struts action code with spring • The action class is responsible for looking up references to Spring-managed beans. This is in direct opposition to the notion of inversion of control (IoC)
  • 114. Page 113Classification: Restricted Delegating requests to Struts actions that are managed as Spring beans • In the struts-config.xml write a proxy action. • The proxy action will • retrieve the application context from the ContextLoaderPlugIn • look up the real Struts action from the spring context • then delegate responsibility to the real Struts action. • Spring provides org.springframework.web.struts.DelegatingActionProxy class. <action path="/listCourses" type="org.springframework.web.struts.DelegatingActionProxy"/>
  • 116. Page 115Classification: Restricted • You don’t need to register ListCourseAction in struts- config.xml. Instead, you register it as a bean in your Spring context configuration file: <bean name="/listCourses" class="com.springinaction.training.struts.ListCourseActi on"> <property name="courseService"> <ref bean="courseService"/> </property> </bean> • Value of the name attribute must exactly match the path attribute of the <action> in struts-config.xml. • Adv: Spring is just another bean now and you can use Spring’s IoC to wire service beans into the Struts action.
  • 118. Page 117Classification: Restricted Spring Security (Acegi security) Features • Single Sign on • Reuses your Spring expertise: Spring application contexts for all configuration • Provide a comprehensive ACL(Access Control list) package • Keeps your objects free of security code • http://acegisecurity.org/index.html
  • 119. Page 118Classification: Restricted Spring and Integration • Spring is essentially an integration platform •Aims to provide a POJO model in whatever environment, with whatever services • Minimal system requirements •Spring runs in Java 1.3 and above •Takes advantage of 1.4 and 5.0 features if available • Spring offers portability between different environments • Integrates with a large number of products •Quartz scheduler •Velocity template engine •Jasper reports etc
  • 120. Page 119Classification: Restricted Spring in a J2EE Environment • Does not violate J2EE programming restrictions • Provides services on any J2EE application server •Runs well on current, stable servers such as WebSphere 4.0–6.0 and WebLogic 6.1-9.0 • Although Spring is an alternative to EJB in many cases, it provides services for invoking and implementing EJBs •Codeless EJB proxies, exposing a POJO interface •Implementing EJBs that internally use Spring
  • 121. Page 120Classification: Restricted Momentum Around Spring • Books: • Pro Spring (Rod Harrop) • J2EE without EJB (Rod Johnson, Juergen Hoeller) • Spring In Action(Craig Walls, Ryan Breidenbach) • Java Development with the Spring Framework (Rod Johnson et al.) • Expert One-on-One: J2EE Design and Development (Rod Johnson) • Websites: • www.springframework.org • www.springhub.com • http://martinfowler.com/articles/injection.html • http://www.roseindia.net/spring/index.shtml
  • 122. Page 121Classification: Restricted Who’s using Spring? Spring is widely used in many industries, including… • Banking: HSBC Investment Bank, DekaBank, BNP Paribas, BBS, CSFB (New York), Goldman Sachs, JP Morgan (Bank One) • Transactional Web applications, message-driven middleware • Retail and investment banking • Scientific research • Defence(Norwegian military) • A growing number of Fortune 500 companies • High volume Web sites • Significant enterprise usage, not merely adventurous early adopters