SlideShare una empresa de Scribd logo
1 de 66
Descargar para leer sin conexión
Spring
Spring Overview
 “Lightweight Container”
 Very loosely coupled
 Components widely reusable and separately
packaged
 Created by Rod Johnson
 Based on “Expert one-on-one J2EE Design and
Development”
 Currently on version 1.1.1
Why Use Spring?
 Wiring of components (Dependency Injection)
 Promotes/simplifies decoupling, design to interfaces, TDD
 Declarative programming without J2EE
 Easily configured aspects, esp. transaction support
 Simplify use of popular technologies
 Abstractions insulate application from specifics, eliminate
redundant code, and handle common error conditions
 Underlying technology specifics still accessible (closures)
Why Use Spring?
 Conversion of checked exceptions to
unchecked
 (Or is this a reason not to use it?)
 Not an all-or-nothing solution
 Extremely modular and flexible
 Well designed
 Easy to extend
 Many reusable classes
Spring Framework
Spring Application
Spring Dependency Injection
 Inversion of Control (IoC)
 “Hollywood Principle”
 Don't call me, I'll call you
 “Container” resolves (injects) dependencies of
components by setting implementation object (push)
 As opposed to component instantiating or Service
Locator pattern where component locates
implementation (pull)
 Martin Fowler calls Dependency Injection
Dependency Injection Variants
 Variations on dependency injection
 Interface based (Avalon)
 Constructor-based (PicoContainer, Spring)
 Setter-based (Spring)
 BeanFactory provides configuration framework to
initialize and “wire” JavaBeans
 org.springframework.beans and
org.springframework.context
 Typically use the XmlBeanFactory, employing XML
configuration files
Dependency Injection (cont'd)
 BeanFactory configured components need have
no Spring dependencies
 Simple JavaBeans
 Beans are singletons by default
 Properties may be simple values or references to
other beans
 Built-in support for defining Lists, Maps, Sets,
and Properties collection types.
 Custom PropertyEditors may be defined to
convert string values to other, arbitrary types.
XmlBeanFactory Example
 Property and constructor based IoC
<bean id="exampleBean" class="examples.ExampleBean">
<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<property name="beanTwo"><ref bean="yetAnotherBean"/></property>
<property name="integerProperty">1</property>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg><ref bean="anotherExampleBean"/></constructor-arg>
<constructor-arg><ref bean="yetAnotherBean"/></constructor-arg>
<constructor-arg><value>1</value></constructor-arg>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
Bean Creation
 Direct instantiation
 <bean id=“beanId” class=“className”>
 BeanFactory instantiation
 Same syntax but class is subclass of BeanFactory
 getObject() called to obtain Bean
 Static Factory
 <bean id=“beanId” class=“className" factory-method="
staticCreationMethod“>
 Instance Factory Method
 <bean id=“beanId” factory-bean=“existingBeanId" factory-
method=“nonStaticCreationMethod">
Bean Creation
 Beans may be singletons or “prototypes”
 Attribute singleton=“false” causes instantiation
with each getBean() lookup
 Singleton is default
 XmlBeanFactory pre-instantiates singletons
 May be overridden on per-instance basis by lazy-
init=“true”
 Beans may also be marked abstract, allowing
reuse of attribute values through inheritance
Autowiring Properties
 Beans may be auto-wired (rather than using <ref>)
 Per-bean attribute autowire
 Explicit settings override
 autowire=“name”
 Bean identifier matches property name
 autowire=“type”
 Type matches other defined bean
 autowire=”constructor”
 Match constructor argument types
 autowire=”autodetect”
 Attempt by constructor, otherwise “type”
Dependency Checking
 Ensures properties are defined
 Per-bean attribute dependency-check
 None required by default
 Verifies autowiring succeeded
 “simple”
 all but collaborators
 “object”
 collaborators only
 “all”
 Collaborators, primitive types, and collections
Lifecycle Customization
 Can define init method called after properties set
 init-method=”<method-name>”
 Can define destroy method as shutdown hook
 destroy-method=”<method-name>”
 May alternatively implement InitializingBean
and/or DisposableBean
 At cost of Spring dependency
BeanFactory Miscellany
 BeanFactoryAware interface provides BeanFactory for
bean
 setBeanFactory(BeanFactory)
 BeanNameAware interface provides bean name
 setBeanName(String)
 FactoryBean for beans which are themselves factories
 Object getObject()
 Boolean isSingleton()
 Class getObjectType()
BeanFactory Usage
InputStream is = new FileInputStream("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(is);
MyBeanClass bean = (MyBeanClass)factory.getBean(“myBean”);
ApplicationContext ctx = new
ClassPathXmlApplicationContext("beans.xml");
MyBeanClass bean = (MyBeanClass)ctx.getBean(“myBean”);
OR
ApplicationContext
 Extends functionality of BeanFactory
 Pre-instantiates singleton beans
 Detects and registers BeanPostProcessors and
BeanFactoryPostProcessors
 Supports nesting of contexts
 ApplicationListener and ApplicationEvents
 Initialized and closed predefined
 Custom may be created
 MessageSource provides i18n messaging
 <bean id=”messageSource”
class=”...ResourceBundleMessageSource”/>
 Contains list of bundle base names
Web Initialization
 Web applications may use
ContextLoaderListener to initialize Spring
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
web.xml
Automatically done by Spring DispatcherServlet
Specialized Beans
 MethodInvokingFactoryBean
 Invokes method on registered beans or any static
methods
 Stores return value
 SingletonBeanFactoryLocator and
ContextSingletonBeanFactoryLocator
 Useful for sharing BeanFactories
 Eliminate duplication of beans in multiple similar
factories or contexts
ApplicationContext customization
 Defined beans inheriting from
BeanFactoryPostProcessor are detected and invoked
 CustomEditorConfigurer
 Registers custom PropertyEditors for converting
configuration string values to specific types
 AutoProxyCreators
 Wrap beans in proxies based on various criteria (name,
metadata, etc)
 PropertyResourceConfigurer
 Sets from property file and/or system properties
ApplicationContext Example
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>database.properties</value></property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${database.connection.driver_class}</value>
</property>
<property name="url">
<value>${database.connection.url}</value>
</property>
</bean>
Spring AOP
AOP Fundamentals
 Aspect-oriented programming (AOP) provides for
simplified application of cross-cutting concerns
 Transaction management
 Security
 Logging
 Auditing
 Locking
 AOP sometimes (partially) achieved via Decorators or
Proxies
 CORBA Portable Interceptors
 Servlet Filters
AOP Fundamentals
 Aspect - Implementation of a cross-cutting concern.
 Spring Advisors or Interceptors
 Joinpoint - Execution point to target
 Typically, methods
 Advice - Action taken at a particular joinpoint.
 Pointcut - A set of joinpoints specifying where advice
should be applied (e.g. Regular expression)
 Introduction/Mixin - Adding methods or fields to an
advised class.
 Weaving - Assembling aspects into advised objects.
Spring AOP
 Generally, applies aspects to beans using BeanFactory
 Uses Dynamic Proxies if interface available
otherwise CGLIB
 CGLIB creates derived class which proxies requests
 Bean class may not be final
 Less capable than AspectJ
 does not have field interception
 only runtime weaving solution is available
 Closer integration with AspectJ anticipated
Spring Pointcuts
 Pointcut applicability to a class may be evaluated
statically or dynamically
 Spring only creates proxies where necessary
public interface Pointcut {
ClassFilter getClassFilter();
MethodMatcher getMethodMatcher();
}
public interface ClassFilter {
boolean matches(Class clazz);
}
Pointcuts (cont'd)
public interface MethodMatcher {
boolean matches(Method m, Class targetClass);
boolean isRuntime();
boolean matches(Method m, Class targetClass, Object[] args);
}
 Pointcut may be statically or dynamically
evaluated based on isRuntime()
 Abstract class StaticMethodMatcherPointcut
requires override of 1st
method only
Only called if isRuntime() == true
Pointcuts (cont'd)
 Spring predefined pointcuts
 In org.springframework.aop.support package
 RegexpMethodPointcut
 Union of multiple regular expressions
 Uses Jakarta ORO package
 ControlFlowPointcut
 Similar to AspectJ cflow
 Applied if call stack includes specific class and, optionally,
method
 UnionPointcut
 Merges pointcuts
Spring Advice
 Can have per-class or per-instance Advice
 Spring provides several Advice types
 Around Advice
 AOP Alliance compliant
 Must call invocation.proceed() to call target
public class MyAdvice implements AroundAdvice {
Object invoke(MethodInvocation invocation) {
// change arguments, start transaction, lock, etc.
invocation.proceed();
// change return value, stop transaction, unlock,etc.
}
}
Spring Advice
 MethodBeforeAdvice
 void before(Method m, Object[] args, Object target)
 Cannot alter return type
 ThrowsAdvice
 Marker interface
 Implementors define methods of form:
 afterThrowing([Method], [args], [target], subclassOfThrowable)
 AfterReturningAdvice
 void afterReturning(Object returnValue, Method, m,
Object[] args, Object target)
 Cannot modify return value
Spring Advice
 IntroductionInterceptor provides ability to define
mixins
public class RollbackAdvice extends DelegatingIntroductionInterceptor
implements RollbackSupport {
Map map = new HashMap();
void rollback(Date date) {
// rollback to state at given time
}
public Object invoke(MethodInvocation invocation) {
// record change and time of change
}
}
Injecting Advice
<bean id=“meetingTarget" class=“ex.DefaultMeeting“
singleton=“false”>
<property name=“topic">Spring</property>
</bean>
<bean id="myAdvisor" class=“ex.RollbackAdvice"
singleton=”false”>
</bean>
<bean id="debugInterceptor"
class="org.springframework.aop.interceptor.DebugInterceptor">
</bean>
Injecting Advice (cont'd)
<bean id=“meeting"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>ex.Meeting</value>
</property>
<property name="target"><ref local=“meetingTarget"/></property>
<property name="interceptorNames">
<list>
<value>myAdvisor</value>
<value>debugInterceptor</value>
</list>
</property>
</bean>
Advisors applied in order
All methods
using CGLib
if none defined
Autoproxying
 Autoproxy bean definitions automatically proxy
selected beans.
 BeanNameAutoProxyCreator
 Adds listed advisors/interceptors to beans
with names matching regular expression
 DefaultAdvisorAutoProxyCreator
 Generic autoproxy infrastructure support
 Applies all advisors defined in the context to
all beans, proxying appropriately
Metadata support
 Spring supports obtaining meta data Object
attributes at class, method, and field level
 Not yet argument level (as JSR-175)
 Currently supports Jakarta Commons Attributes
 Support for JSR-175 in work
 Metadata support provided via Attributes
interface
 Amenable to mocking unlike JDK reflection and
Commons static methods
Metadata autoproxying
 Configuration of autoproxying based on metadata
attributes simplifies configuration
 Define custom attribute class
 Define Advisor with pointcut based on custom attribute
 Add Advisor in ApplicationContext with autoproxy
 Examples
 Transaction Attributes
 Security Attributes
 Pooling
 Mapping of controllers to URLs
Transactions
AOP Transactions
 Spring provides AOP support for declarative
transactions
 Delegates to a PlatformTransactionManager
instance
 DataSourceTransactionManager
 HibernateTransactionManager
 JdoTransactionManager
 JtaTransactionManager
Transaction Configuration
<bean id="sessionFactory"
class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="dataSource"><ref bean="dataSource"/></property>
<property name="mappingResources">
<list>
<value>com/../model/*.hbm.xml</value>
</list>
</property>
</bean>
<bean id="transactionManager”
class="org.springframework.orm.hibernate.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
Declarative Transactions
 Declarative transactional support can be added to
any bean by using TransactionProxyFactoryBean
 Similar to EJB, transaction attributes may be
defined on a per-method basis
 Also allows definition of pre- and post-
interceptors (e.g. for security)
Injecting Transaction Support
<bean id=“reservationService"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="target"><ref local=“reservationServiceTarget"/></property>
<property name="transactionAttributes">
<props>
<prop key=“reserveRoom*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
Declarative transaction support for single bean
Transaction Autoproxy
<bean id="autoproxy"
class="org...DefaultAdvisorAutoProxyCreator">
</bean>
<bean id="transactionAdvisor"
class="org...TransactionAttributeSourceAdvisor"
autowire="constructor" >
</bean>
<bean id="transactionInterceptor"
class="org...TransactionInterceptor"
autowire="byType">
</bean>
<bean id="transactionAttributeSource"
class="org...AttributesTransactionAttributeSource"
autowire="constructor">
</bean>
<bean id="attributes"
class="org...CommonsAttributes"
/>
Caches metadata
from classes
Generic autoproxy
support
Applies transaction
using transactionManager
Invokes interceptor
based on attributes
Data Access
Data Access
 DAO support provides pluggable framework for
persistence
 Currently supports JDBC, Hibernate, JDO, and
iBatis
 Defines consistent exception hierarchy (based on
RuntimeException)
 Provides abstract “Support” classes for each
technology
 Template methods define specific queries
Hibernate DAO Example
public class ReservationDaoImpl extends HibernateDaoSupport
implements ReservationDao {
public Reservation getReservation (Long orderId) {
return (Reservation)getHibernateTemplate().load(Reservation .class,
orderId);
}
public void saveReservation (Reservation r) {
getHibernateTemplate().saveOrUpdate(r);
}
public void remove(Reservation Reservation) {
getHibernateTemplate().delete(r);
}
Hibernate DAO (cont’d)
public Reservation[] findReservations(Room room) {
List list = getHibernateTemplate().find(
"from Reservation reservation “ +
“ where reservation.resource =? “ +
“ order by reservation.start",
instrument);
return (Reservation[]) list.toArray(new Reservation[list.size()]);
Hibernate DAO (cont’d)
public Reservation[] findReservations(final DateRange range) {
final HibernateTemplate template = getHibernateTemplate();
List list = (List) template.execute(new HibernateCallback() {
public Object doInHibernate(Session session) {
Query query = session.createQuery(
"from Reservation r “ +
“ where r.start > :rangeStart and r.start < :rangeEnd “);
query.setDate("rangeStart", range.getStartDate()
query.setDate("rangeEnd", range.getEndDate())
return query.list();
}
});
return (Reservation[]) list.toArray(new Reservation[list.size()]);
}
}
Hibernate Example
<bean id="sessionFactory"
class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="dataSource"><ref bean="dataSource"/></property>
<property name="mappingResources">
<list>
<value>com/jensenp/Reservation/Room.hbm.xml</value>
<value>com/jensenp/Reservation/Reservation.hbm.xml</value>
<value>com/jensenp/Reservation/Resource.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}
</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id=“reservationDao"
class="com.jensenp.Reservation.ReservationDaoImpl">
<property name="sessionFactory"><ref bean="sessionFactory"/>
</property>
</bean>
JDBC Support
 JDBCTemplate provides
 Translation of SQLExceptions to more meaningful
Spring Runtime exceptions
 Integrates thread-specific transactions
 MappingSQLQuery simplifies mapping of
ResultSets to Java objects
Web Framework
DispatcherServlet
 The DispatcherServlet is the Spring Front
Controller
 Initializes WebApplicationContext
 Uses /WEB-INF/[servlet-name]-servlet.xml by
default
 WebApplicationContext is bound into
ServletContext
DispatcherServlet Configuration
 HandlerMapping
 Routing of requests to handlers
 HandlerAdapter
 Adapts to handler interface. Default utilizes Controllers
 HandlerExceptionResolver
 Maps exceptions to error pages
 Similar to standard Servlet, but more flexible
 ViewResolver
 Maps symbolic name to view
Dispatcher Servlet Configuration
 MultipartResolver
 Handling of file upload
 LocaleResolver
 Default uses HTTP accept header, cookie, or
session
Controllers
 Controller interface defines one method
 ModelAndView handleRequest(HttpServletRequest
req, HttpServletResponse resp) throws Exception
 ModelAndView consists of a view identifier and
a Map of model data
Controller Implementations
 CommandControllers bind parameters to data
objects
 AbstractCommandController
 AbstractFormController
 SimpleFormController
 WizardFormController
Spring talk111204
Spring talk111204
Spring talk111204
Spring talk111204
Spring talk111204
Spring talk111204
Spring talk111204
Spring talk111204
Spring talk111204
Spring talk111204

Más contenido relacionado

La actualidad más candente

EJB et WS (Montreal JUG - 12 mai 2011)
EJB et WS (Montreal JUG - 12 mai 2011)EJB et WS (Montreal JUG - 12 mai 2011)
EJB et WS (Montreal JUG - 12 mai 2011)Montreal JUG
 
Different Types of Containers in Spring
Different Types of Containers in Spring Different Types of Containers in Spring
Different Types of Containers in Spring Sunil kumar Mohanty
 
Using Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformUsing Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformArun Gupta
 
On Processors, Compilers and @Configurations
On Processors, Compilers and @ConfigurationsOn Processors, Compilers and @Configurations
On Processors, Compilers and @ConfigurationsNetcetera
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSam Brannen
 
Contexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformContexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformBozhidar Bozhanov
 
Spring 3.1 in a Nutshell
Spring 3.1 in a NutshellSpring 3.1 in a Nutshell
Spring 3.1 in a NutshellSam Brannen
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guidePankaj Singh
 
Enterprise java beans(ejb)
Enterprise java beans(ejb)Enterprise java beans(ejb)
Enterprise java beans(ejb)vikram singh
 
Enterprise java beans(ejb) update 2
Enterprise java beans(ejb) update 2Enterprise java beans(ejb) update 2
Enterprise java beans(ejb) update 2vikram singh
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontendHeiko Hardt
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXIMC Institute
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2Techglyphs
 
Dependency injection with koin
Dependency injection with koinDependency injection with koin
Dependency injection with koinSean Tsai
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesHitesh-Java
 

La actualidad más candente (20)

EJB et WS (Montreal JUG - 12 mai 2011)
EJB et WS (Montreal JUG - 12 mai 2011)EJB et WS (Montreal JUG - 12 mai 2011)
EJB et WS (Montreal JUG - 12 mai 2011)
 
Spring core
Spring coreSpring core
Spring core
 
Different Types of Containers in Spring
Different Types of Containers in Spring Different Types of Containers in Spring
Different Types of Containers in Spring
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Using Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformUsing Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 Platform
 
On Processors, Compilers and @Configurations
On Processors, Compilers and @ConfigurationsOn Processors, Compilers and @Configurations
On Processors, Compilers and @Configurations
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
Contexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformContexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platform
 
Spring 3.1 in a Nutshell
Spring 3.1 in a NutshellSpring 3.1 in a Nutshell
Spring 3.1 in a Nutshell
 
EJB .
EJB .EJB .
EJB .
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 
Spring
SpringSpring
Spring
 
Enterprise java beans(ejb)
Enterprise java beans(ejb)Enterprise java beans(ejb)
Enterprise java beans(ejb)
 
Enterprise java beans(ejb) update 2
Enterprise java beans(ejb) update 2Enterprise java beans(ejb) update 2
Enterprise java beans(ejb) update 2
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontend
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
Javaee6 Overview
Javaee6 OverviewJavaee6 Overview
Javaee6 Overview
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2
 
Dependency injection with koin
Dependency injection with koinDependency injection with koin
Dependency injection with koin
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 

Similar a Spring talk111204

Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depthVinay Kumar
 
Spring training
Spring trainingSpring training
Spring trainingTechFerry
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAOAnushaNaidu
 
Spring training
Spring trainingSpring training
Spring trainingshah_d_p
 
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)Peter Antman
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Michał Orman
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise Group
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkRajind Ruparathna
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4than sare
 
Spring introduction
Spring introductionSpring introduction
Spring introductionLê Hảo
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdfDeoDuaNaoHet
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Zsang nguyen
 

Similar a Spring talk111204 (20)

Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Spring training
Spring trainingSpring training
Spring training
 
Spring
SpringSpring
Spring
 
Spring
SpringSpring
Spring
 
Spring
SpringSpring
Spring
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 
Spring training
Spring trainingSpring training
Spring training
 
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
CoffeeScript By Example
CoffeeScript By ExampleCoffeeScript By Example
CoffeeScript By Example
 
JBoss AS7 OSDC 2011
JBoss AS7 OSDC 2011JBoss AS7 OSDC 2011
JBoss AS7 OSDC 2011
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Z
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 

Más de s4al_com

Webservices
WebservicesWebservices
Webservicess4al_com
 
Orm and hibernate
Orm and hibernateOrm and hibernate
Orm and hibernates4al_com
 
Online gas booking project in java
Online gas booking project in javaOnline gas booking project in java
Online gas booking project in javas4al_com
 
Introduction to ejb and struts framework
Introduction to ejb and struts frameworkIntroduction to ejb and struts framework
Introduction to ejb and struts frameworks4al_com
 

Más de s4al_com (7)

Webservices
WebservicesWebservices
Webservices
 
Struts
StrutsStruts
Struts
 
Spring
SpringSpring
Spring
 
Orm and hibernate
Orm and hibernateOrm and hibernate
Orm and hibernate
 
Java
JavaJava
Java
 
Online gas booking project in java
Online gas booking project in javaOnline gas booking project in java
Online gas booking project in java
 
Introduction to ejb and struts framework
Introduction to ejb and struts frameworkIntroduction to ejb and struts framework
Introduction to ejb and struts framework
 

Último

Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.EnglishCEIPdeSigeiro
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesMohammad Hassany
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxDr. Santhosh Kumar. N
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17Celine George
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxKatherine Villaluna
 
NOTES OF DRUGS ACTING ON NERVOUS SYSTEM .pdf
NOTES OF DRUGS ACTING ON NERVOUS SYSTEM .pdfNOTES OF DRUGS ACTING ON NERVOUS SYSTEM .pdf
NOTES OF DRUGS ACTING ON NERVOUS SYSTEM .pdfSumit Tiwari
 
Latin American Revolutions, c. 1789-1830
Latin American Revolutions, c. 1789-1830Latin American Revolutions, c. 1789-1830
Latin American Revolutions, c. 1789-1830Dave Phillips
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationMJDuyan
 
How to Solve Singleton Error in the Odoo 17
How to Solve Singleton Error in the  Odoo 17How to Solve Singleton Error in the  Odoo 17
How to Solve Singleton Error in the Odoo 17Celine George
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfMohonDas
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphNetziValdelomar1
 
Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.raviapr7
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxraviapr7
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxEduSkills OECD
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfMohonDas
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxSaurabhParmar42
 
Quality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICEQuality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICESayali Powar
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17Celine George
 

Último (20)

Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.
 
Prelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quizPrelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quiz
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming Classes
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptx
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
 
NOTES OF DRUGS ACTING ON NERVOUS SYSTEM .pdf
NOTES OF DRUGS ACTING ON NERVOUS SYSTEM .pdfNOTES OF DRUGS ACTING ON NERVOUS SYSTEM .pdf
NOTES OF DRUGS ACTING ON NERVOUS SYSTEM .pdf
 
Latin American Revolutions, c. 1789-1830
Latin American Revolutions, c. 1789-1830Latin American Revolutions, c. 1789-1830
Latin American Revolutions, c. 1789-1830
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive Education
 
How to Solve Singleton Error in the Odoo 17
How to Solve Singleton Error in the  Odoo 17How to Solve Singleton Error in the  Odoo 17
How to Solve Singleton Error in the Odoo 17
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdf
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a Paragraph
 
Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptx
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdf
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptx
 
Quality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICEQuality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICE
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17
 

Spring talk111204

  • 2. Spring Overview  “Lightweight Container”  Very loosely coupled  Components widely reusable and separately packaged  Created by Rod Johnson  Based on “Expert one-on-one J2EE Design and Development”  Currently on version 1.1.1
  • 3. Why Use Spring?  Wiring of components (Dependency Injection)  Promotes/simplifies decoupling, design to interfaces, TDD  Declarative programming without J2EE  Easily configured aspects, esp. transaction support  Simplify use of popular technologies  Abstractions insulate application from specifics, eliminate redundant code, and handle common error conditions  Underlying technology specifics still accessible (closures)
  • 4. Why Use Spring?  Conversion of checked exceptions to unchecked  (Or is this a reason not to use it?)  Not an all-or-nothing solution  Extremely modular and flexible  Well designed  Easy to extend  Many reusable classes
  • 7. Spring Dependency Injection  Inversion of Control (IoC)  “Hollywood Principle”  Don't call me, I'll call you  “Container” resolves (injects) dependencies of components by setting implementation object (push)  As opposed to component instantiating or Service Locator pattern where component locates implementation (pull)  Martin Fowler calls Dependency Injection
  • 8. Dependency Injection Variants  Variations on dependency injection  Interface based (Avalon)  Constructor-based (PicoContainer, Spring)  Setter-based (Spring)  BeanFactory provides configuration framework to initialize and “wire” JavaBeans  org.springframework.beans and org.springframework.context  Typically use the XmlBeanFactory, employing XML configuration files
  • 9. Dependency Injection (cont'd)  BeanFactory configured components need have no Spring dependencies  Simple JavaBeans  Beans are singletons by default  Properties may be simple values or references to other beans  Built-in support for defining Lists, Maps, Sets, and Properties collection types.  Custom PropertyEditors may be defined to convert string values to other, arbitrary types.
  • 10. XmlBeanFactory Example  Property and constructor based IoC <bean id="exampleBean" class="examples.ExampleBean"> <property name="beanOne"><ref bean="anotherExampleBean"/></property> <property name="beanTwo"><ref bean="yetAnotherBean"/></property> <property name="integerProperty">1</property> </bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean"/> <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg><ref bean="anotherExampleBean"/></constructor-arg> <constructor-arg><ref bean="yetAnotherBean"/></constructor-arg> <constructor-arg><value>1</value></constructor-arg> </bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
  • 11. Bean Creation  Direct instantiation  <bean id=“beanId” class=“className”>  BeanFactory instantiation  Same syntax but class is subclass of BeanFactory  getObject() called to obtain Bean  Static Factory  <bean id=“beanId” class=“className" factory-method=" staticCreationMethod“>  Instance Factory Method  <bean id=“beanId” factory-bean=“existingBeanId" factory- method=“nonStaticCreationMethod">
  • 12. Bean Creation  Beans may be singletons or “prototypes”  Attribute singleton=“false” causes instantiation with each getBean() lookup  Singleton is default  XmlBeanFactory pre-instantiates singletons  May be overridden on per-instance basis by lazy- init=“true”  Beans may also be marked abstract, allowing reuse of attribute values through inheritance
  • 13. Autowiring Properties  Beans may be auto-wired (rather than using <ref>)  Per-bean attribute autowire  Explicit settings override  autowire=“name”  Bean identifier matches property name  autowire=“type”  Type matches other defined bean  autowire=”constructor”  Match constructor argument types  autowire=”autodetect”  Attempt by constructor, otherwise “type”
  • 14. Dependency Checking  Ensures properties are defined  Per-bean attribute dependency-check  None required by default  Verifies autowiring succeeded  “simple”  all but collaborators  “object”  collaborators only  “all”  Collaborators, primitive types, and collections
  • 15. Lifecycle Customization  Can define init method called after properties set  init-method=”<method-name>”  Can define destroy method as shutdown hook  destroy-method=”<method-name>”  May alternatively implement InitializingBean and/or DisposableBean  At cost of Spring dependency
  • 16. BeanFactory Miscellany  BeanFactoryAware interface provides BeanFactory for bean  setBeanFactory(BeanFactory)  BeanNameAware interface provides bean name  setBeanName(String)  FactoryBean for beans which are themselves factories  Object getObject()  Boolean isSingleton()  Class getObjectType()
  • 17. BeanFactory Usage InputStream is = new FileInputStream("beans.xml"); XmlBeanFactory factory = new XmlBeanFactory(is); MyBeanClass bean = (MyBeanClass)factory.getBean(“myBean”); ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); MyBeanClass bean = (MyBeanClass)ctx.getBean(“myBean”); OR
  • 18. ApplicationContext  Extends functionality of BeanFactory  Pre-instantiates singleton beans  Detects and registers BeanPostProcessors and BeanFactoryPostProcessors  Supports nesting of contexts  ApplicationListener and ApplicationEvents  Initialized and closed predefined  Custom may be created  MessageSource provides i18n messaging  <bean id=”messageSource” class=”...ResourceBundleMessageSource”/>  Contains list of bundle base names
  • 19. Web Initialization  Web applications may use ContextLoaderListener to initialize Spring <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> web.xml Automatically done by Spring DispatcherServlet
  • 20. Specialized Beans  MethodInvokingFactoryBean  Invokes method on registered beans or any static methods  Stores return value  SingletonBeanFactoryLocator and ContextSingletonBeanFactoryLocator  Useful for sharing BeanFactories  Eliminate duplication of beans in multiple similar factories or contexts
  • 21. ApplicationContext customization  Defined beans inheriting from BeanFactoryPostProcessor are detected and invoked  CustomEditorConfigurer  Registers custom PropertyEditors for converting configuration string values to specific types  AutoProxyCreators  Wrap beans in proxies based on various criteria (name, metadata, etc)  PropertyResourceConfigurer  Sets from property file and/or system properties
  • 22. ApplicationContext Example <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"><value>database.properties</value></property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${database.connection.driver_class}</value> </property> <property name="url"> <value>${database.connection.url}</value> </property> </bean>
  • 24. AOP Fundamentals  Aspect-oriented programming (AOP) provides for simplified application of cross-cutting concerns  Transaction management  Security  Logging  Auditing  Locking  AOP sometimes (partially) achieved via Decorators or Proxies  CORBA Portable Interceptors  Servlet Filters
  • 25. AOP Fundamentals  Aspect - Implementation of a cross-cutting concern.  Spring Advisors or Interceptors  Joinpoint - Execution point to target  Typically, methods  Advice - Action taken at a particular joinpoint.  Pointcut - A set of joinpoints specifying where advice should be applied (e.g. Regular expression)  Introduction/Mixin - Adding methods or fields to an advised class.  Weaving - Assembling aspects into advised objects.
  • 26. Spring AOP  Generally, applies aspects to beans using BeanFactory  Uses Dynamic Proxies if interface available otherwise CGLIB  CGLIB creates derived class which proxies requests  Bean class may not be final  Less capable than AspectJ  does not have field interception  only runtime weaving solution is available  Closer integration with AspectJ anticipated
  • 27. Spring Pointcuts  Pointcut applicability to a class may be evaluated statically or dynamically  Spring only creates proxies where necessary public interface Pointcut { ClassFilter getClassFilter(); MethodMatcher getMethodMatcher(); } public interface ClassFilter { boolean matches(Class clazz); }
  • 28. Pointcuts (cont'd) public interface MethodMatcher { boolean matches(Method m, Class targetClass); boolean isRuntime(); boolean matches(Method m, Class targetClass, Object[] args); }  Pointcut may be statically or dynamically evaluated based on isRuntime()  Abstract class StaticMethodMatcherPointcut requires override of 1st method only Only called if isRuntime() == true
  • 29. Pointcuts (cont'd)  Spring predefined pointcuts  In org.springframework.aop.support package  RegexpMethodPointcut  Union of multiple regular expressions  Uses Jakarta ORO package  ControlFlowPointcut  Similar to AspectJ cflow  Applied if call stack includes specific class and, optionally, method  UnionPointcut  Merges pointcuts
  • 30. Spring Advice  Can have per-class or per-instance Advice  Spring provides several Advice types  Around Advice  AOP Alliance compliant  Must call invocation.proceed() to call target public class MyAdvice implements AroundAdvice { Object invoke(MethodInvocation invocation) { // change arguments, start transaction, lock, etc. invocation.proceed(); // change return value, stop transaction, unlock,etc. } }
  • 31. Spring Advice  MethodBeforeAdvice  void before(Method m, Object[] args, Object target)  Cannot alter return type  ThrowsAdvice  Marker interface  Implementors define methods of form:  afterThrowing([Method], [args], [target], subclassOfThrowable)  AfterReturningAdvice  void afterReturning(Object returnValue, Method, m, Object[] args, Object target)  Cannot modify return value
  • 32. Spring Advice  IntroductionInterceptor provides ability to define mixins public class RollbackAdvice extends DelegatingIntroductionInterceptor implements RollbackSupport { Map map = new HashMap(); void rollback(Date date) { // rollback to state at given time } public Object invoke(MethodInvocation invocation) { // record change and time of change } }
  • 33. Injecting Advice <bean id=“meetingTarget" class=“ex.DefaultMeeting“ singleton=“false”> <property name=“topic">Spring</property> </bean> <bean id="myAdvisor" class=“ex.RollbackAdvice" singleton=”false”> </bean> <bean id="debugInterceptor" class="org.springframework.aop.interceptor.DebugInterceptor"> </bean>
  • 34. Injecting Advice (cont'd) <bean id=“meeting" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>ex.Meeting</value> </property> <property name="target"><ref local=“meetingTarget"/></property> <property name="interceptorNames"> <list> <value>myAdvisor</value> <value>debugInterceptor</value> </list> </property> </bean> Advisors applied in order All methods using CGLib if none defined
  • 35. Autoproxying  Autoproxy bean definitions automatically proxy selected beans.  BeanNameAutoProxyCreator  Adds listed advisors/interceptors to beans with names matching regular expression  DefaultAdvisorAutoProxyCreator  Generic autoproxy infrastructure support  Applies all advisors defined in the context to all beans, proxying appropriately
  • 36. Metadata support  Spring supports obtaining meta data Object attributes at class, method, and field level  Not yet argument level (as JSR-175)  Currently supports Jakarta Commons Attributes  Support for JSR-175 in work  Metadata support provided via Attributes interface  Amenable to mocking unlike JDK reflection and Commons static methods
  • 37. Metadata autoproxying  Configuration of autoproxying based on metadata attributes simplifies configuration  Define custom attribute class  Define Advisor with pointcut based on custom attribute  Add Advisor in ApplicationContext with autoproxy  Examples  Transaction Attributes  Security Attributes  Pooling  Mapping of controllers to URLs
  • 39. AOP Transactions  Spring provides AOP support for declarative transactions  Delegates to a PlatformTransactionManager instance  DataSourceTransactionManager  HibernateTransactionManager  JdoTransactionManager  JtaTransactionManager
  • 40. Transaction Configuration <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean"> <property name="dataSource"><ref bean="dataSource"/></property> <property name="mappingResources"> <list> <value>com/../model/*.hbm.xml</value> </list> </property> </bean> <bean id="transactionManager” class="org.springframework.orm.hibernate.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean>
  • 41. Declarative Transactions  Declarative transactional support can be added to any bean by using TransactionProxyFactoryBean  Similar to EJB, transaction attributes may be defined on a per-method basis  Also allows definition of pre- and post- interceptors (e.g. for security)
  • 42. Injecting Transaction Support <bean id=“reservationService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> <property name="target"><ref local=“reservationServiceTarget"/></property> <property name="transactionAttributes"> <props> <prop key=“reserveRoom*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> Declarative transaction support for single bean
  • 43. Transaction Autoproxy <bean id="autoproxy" class="org...DefaultAdvisorAutoProxyCreator"> </bean> <bean id="transactionAdvisor" class="org...TransactionAttributeSourceAdvisor" autowire="constructor" > </bean> <bean id="transactionInterceptor" class="org...TransactionInterceptor" autowire="byType"> </bean> <bean id="transactionAttributeSource" class="org...AttributesTransactionAttributeSource" autowire="constructor"> </bean> <bean id="attributes" class="org...CommonsAttributes" /> Caches metadata from classes Generic autoproxy support Applies transaction using transactionManager Invokes interceptor based on attributes
  • 45. Data Access  DAO support provides pluggable framework for persistence  Currently supports JDBC, Hibernate, JDO, and iBatis  Defines consistent exception hierarchy (based on RuntimeException)  Provides abstract “Support” classes for each technology  Template methods define specific queries
  • 46. Hibernate DAO Example public class ReservationDaoImpl extends HibernateDaoSupport implements ReservationDao { public Reservation getReservation (Long orderId) { return (Reservation)getHibernateTemplate().load(Reservation .class, orderId); } public void saveReservation (Reservation r) { getHibernateTemplate().saveOrUpdate(r); } public void remove(Reservation Reservation) { getHibernateTemplate().delete(r); }
  • 47. Hibernate DAO (cont’d) public Reservation[] findReservations(Room room) { List list = getHibernateTemplate().find( "from Reservation reservation “ + “ where reservation.resource =? “ + “ order by reservation.start", instrument); return (Reservation[]) list.toArray(new Reservation[list.size()]);
  • 48. Hibernate DAO (cont’d) public Reservation[] findReservations(final DateRange range) { final HibernateTemplate template = getHibernateTemplate(); List list = (List) template.execute(new HibernateCallback() { public Object doInHibernate(Session session) { Query query = session.createQuery( "from Reservation r “ + “ where r.start > :rangeStart and r.start < :rangeEnd “); query.setDate("rangeStart", range.getStartDate() query.setDate("rangeEnd", range.getEndDate()) return query.list(); } }); return (Reservation[]) list.toArray(new Reservation[list.size()]); } }
  • 49. Hibernate Example <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean"> <property name="dataSource"><ref bean="dataSource"/></property> <property name="mappingResources"> <list> <value>com/jensenp/Reservation/Room.hbm.xml</value> <value>com/jensenp/Reservation/Reservation.hbm.xml</value> <value>com/jensenp/Reservation/Resource.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto} </prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> </props> </property> </bean> <bean id=“reservationDao" class="com.jensenp.Reservation.ReservationDaoImpl"> <property name="sessionFactory"><ref bean="sessionFactory"/> </property> </bean>
  • 50. JDBC Support  JDBCTemplate provides  Translation of SQLExceptions to more meaningful Spring Runtime exceptions  Integrates thread-specific transactions  MappingSQLQuery simplifies mapping of ResultSets to Java objects
  • 52. DispatcherServlet  The DispatcherServlet is the Spring Front Controller  Initializes WebApplicationContext  Uses /WEB-INF/[servlet-name]-servlet.xml by default  WebApplicationContext is bound into ServletContext
  • 53. DispatcherServlet Configuration  HandlerMapping  Routing of requests to handlers  HandlerAdapter  Adapts to handler interface. Default utilizes Controllers  HandlerExceptionResolver  Maps exceptions to error pages  Similar to standard Servlet, but more flexible  ViewResolver  Maps symbolic name to view
  • 54. Dispatcher Servlet Configuration  MultipartResolver  Handling of file upload  LocaleResolver  Default uses HTTP accept header, cookie, or session
  • 55. Controllers  Controller interface defines one method  ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception  ModelAndView consists of a view identifier and a Map of model data
  • 56. Controller Implementations  CommandControllers bind parameters to data objects  AbstractCommandController  AbstractFormController  SimpleFormController  WizardFormController

Notas del editor

  1. Template closures JDBC support also provided