close

Вход

Забыли?

вход по аккаунту

?

Spring - Object Computing, Inc.

код для вставкиСкачать
Spring
Paul Jensen
Principal, Object Computing Inc.
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)
пЃ®
пЃ®
Declarative programming without J2EE
пЃ®
пЃ®
Promotes/simplifies decoupling, design to interfaces, TDD
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
пЃ®
пЃ®
Not an all-or-nothing solution
пЃ®
пЃ®
(Or is this a reason not to use it?)
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
пЃ®
пЃ®
пЃ®
пЃ®
BeanFactory provides configuration framework to
initialize and “wire” JavaBeans
пЃ®
пЃ®
Interface based (Avalon)
Constructor-based (PicoContainer, Spring)
Setter-based (Spring)
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
пЃ®
пЃ®
BeanFactory instantiation
пЃ®
пЃ®
пЃ®
Same syntax but class is subclass of BeanFactory
getObject() called to obtain Bean
Static Factory
пЃ®
пЃ®
<bean id=“beanId” class=“className”>
<bean id=“beanId” class=“className" factory-method="
staticCreationMethod“>
Instance Factory Method
пЃ®
<bean id=“beanId” factory-bean=“existingBeanId" factorymethod=“nonStaticCreationMethod">
Bean Creation
пЃ®
Beans may be singletons or “prototypes”
пЃ®
пЃ®
пЃ®
XmlBeanFactory pre-instantiates singletons
пЃ®
пЃ®
Attribute singleton=“false” causes instantiation
with each getBean() lookup
Singleton is default
May be overridden on per-instance basis by lazyinit=“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>)
пЃ®
пЃ®
пЃ®
autowire=“name”
пЃ®
пЃ®
Type matches other defined bean
autowire=”constructor”
пЃ®
пЃ®
Bean identifier matches property name
autowire=“type”
пЃ®
пЃ®
Per-bean attribute autowire
Explicit settings override
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
пЃ®
пЃ®
Can define destroy method as shutdown hook
пЃ®
пЃ®
init-method=”<method-name>”
destroy-method=”<method-name>”
May alternatively implement InitializingBean
and/or DisposableBean
пЃ®
At cost of Spring dependency
BeanFactory Miscellany
пЃ®
BeanFactoryAware interface provides BeanFactory for
bean
пЃ®
пЃ®
BeanNameAware interface provides bean name
пЃ®
пЃ®
setBeanFactory(BeanFactory)
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”);
OR
ApplicationContext ctx = new
ClassPathXmlApplicationContext("beans.xml");
MyBeanClass bean = (MyBeanClass)ctx.getBean(“myBean”);
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
web.xml
<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>
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)
пЃ®
пЃ®
Pointcut may be statically or dynamically
evaluated based on isRuntime()
Abstract class StaticMethodMatcherPointcut
requires override of 1st method only
public interface MethodMatcher {
boolean matches(Method m, Class targetClass);
boolean isRuntime();
boolean matches(Method m, Class targetClass, Object[] args);
}
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">
All methods
<value>ex.Meeting</value>
using CGLib
</property>
if none defined
<property name="target"><ref local=“meetingTarget"/></property>
<property name="interceptorNames">
<list>
<value>myAdvisor</value>
<value>debugInterceptor</value>
</list>
</property>
</bean>
Advisors applied in order
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 postinterceptors (e.g. for security)
Injecting Transaction Support
Declarative transaction support for single bean
<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>
Transaction Autoproxy
<bean id="autoproxy"
class="org...DefaultAdvisorAutoProxyCreator">
</bean>
<bean id="transactionAdvisor"
class="org...TransactionAttributeSourceAdvisor"
autowire="constructor" >
</bean>
Generic autoproxy
support
Invokes interceptor
based on attributes
<bean id="transactionInterceptor"
class="org...TransactionInterceptor"
autowire="byType">
</bean>
Applies transaction
using transactionManager
<bean id="transactionAttributeSource"
class="org...AttributesTransactionAttributeSource"
autowire="constructor">
</bean>
Caches metadata
from classes
<bean id="attributes"
class="org...CommonsAttributes"
/>
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
пЃ®
пЃ®
HandlerAdapter
пЃ®
пЃ®
Adapts to handler interface. Default utilizes Controllers
HandlerExceptionResolver
пЃ®
пЃ®
пЃ®
Routing of requests to handlers
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
References
пЃ®
пЃ®
пЃ®
пЃ®
Spring’s homepage: http://www.springframework.org
“Introducing the Spring Framework” by Rod Johnson:
http://theserverside.com/news/thread.jsp?thread_id=21893
“Inversion of control containers and dependency injection” by
Martin Fowler:
http://www.martinfowler.com/articles/injection.html
AOP Alliance: http://aopalliance.sourceforge.net
Документ
Категория
Презентации
Просмотров
15
Размер файла
252 Кб
Теги
1/--страниц
Пожаловаться на содержимое документа