close

Вход

Забыли?

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

?

Spring - SRaviSankar

код для вставкиСкачать
Spring
пЃ®
пЃ®
пЃ®
пЃ®
пЃ®
пЃ®
пЃ®
пЃ®
пЃ®
Spring Overview
Spring Container Concepts
Spring and AOP
Spring and Data Access
Managing Transactions and Resources
Remoting and Accessing Enterprise Services
Spring Web Framework
Integrating with Struts
DAO and LDAP support
Spring Overview
пЃ®
Spring is a Lightweight Application Framework
пЃ®
Spring Promotes loose coupling through Inversion
of Control (IoC)
пЃ®
Spring comes with rich support for
Aspect-Oriented Programming.
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
пЃ® Declarative programming without J2EE
пЃ® Easily configured aspects, esp. transaction
support
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
Architectural benefits
пЃ®
пЃ®
пЃ®
Spring can effectively organize your middle tier objects, whether
or not you choose to use EJB.
Spring's configuration management services can be used in any
architectural layer, in whatever runtime environment.
Spring can use AOP to deliver declarative transaction
management without using an EJB container.
Architectural benefits
пЃ®
пЃ®
Spring provides a consistent framework for data access, whether
using JDBC or an O/R mapping product such as TopLink,
Hibernate
Spring provides a consistent, simple programming model in
many areas JDBC, JMS, JavaMail, JNDI and many other
important API’s.
Spring Framework
пЃ®
The Spring framework is a layered architecture
consisting of seven well-defined modules. The
Spring modules are built on top of the core
container, which defines how beans are created,
configured and managed.
Spring Framework
Spring Framework
Core container
Provides the essential functionality of the Spring
framework.
Primary component of the core container is the
BeanFactory, an implementation of the Factory
pattern.
BeanFactory applies the Inversion of Control (IOC)
pattern to separate an application's configuration and
dependency specification from the actual application code.
Spring Framework
Spring context
Spring context is a configuration file that provides context
information to the Spring framework. The Spring context
includes enterprise services such as JNDI, EJB, e-mail,
validation, and scheduling functionality.
Spring Framework
Spring AOP
The Spring AOP integrates aspect-oriented functionality
directly into the Spring framework.
Provides transaction management services for objects
in any Spring-based application.
Incorporates declarative transaction management
capabilities into applications without relying on EJB
components.
Spring Framework
Spring DAO
пЃ®
пЃ®
пЃ®
Spring JDBC DAO abstraction layer offers exception hierarchy for
managing the exception handling and error messages thrown by
different database vendors.
The exception hierarchy simplifies error handling and greatly
reduces the amount of exception code you need to write, such
as opening and closing connections.
Spring DAO's JDBC-oriented exceptions comply to its generic
DAO exception hierarchy.
Spring Framework
Spring ORM
The Spring framework plugs into several ORM
frameworks to provide its Object Relational tool,
including JDO and Hibernate.
All of these comply to Spring's generic transaction
and DAO exception hierarchies.
Spring Framework
Spring Web module
The Web context module builds on top of the application context
module, providing contexts for Web-based applications.
The Web module also eases the tasks of handling multi-part
requests and binding request parameters to domain objects.
Spring MVC framework
The Model-View-Controller (MVC) framework
featured MVC implementation for building Web
applications.
The MVC framework is highly configurable via
strategy interfaces and accommodates numerous
view technologies including JSP, Velocity, Tiles and
iText.
Aspect Oriented Programming
Aspect-oriented programming, or AOP, is a
programming technique that allows programmers to
modularize crosscutting concerns, or behavior that
cuts across the typical divisions of responsibility,
such as logging and transaction management.
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”);
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 (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.
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">
Autowiring Properties
пЃ®
пЃ®
Beans may be auto-wired (rather than using
<ref>)
пЃ®
Per-bean attribute autowire
пЃ®
Explicit settings override
autowire=“name”
пЃ®
пЃ®
autowire=“type”
пЃ®
пЃ®
Type matches other defined bean
autowire=”constructor”
пЃ®
пЃ®
Bean identifier matches property name
Match constructor argument types
autowire=”autodetect”
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
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
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
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>
Generic autoproxy
support
<bean id="transactionAdvisor"
class="org...TransactionAttributeSourceAdvisor"
autowire="constructor" >
</bean>
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>
<bean id="attributes"
class="org...CommonsAttributes"
/>
Caches metadata
from classes
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
DAO Support
The Data Access Object (DAO) support
in Spring is primarily aimed at making it
easy to work with data access
technologies like JDBC, Hibernate or
JDO in a standardized way.
DAO Support
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"
lazy-init="default" autowire="default" dependency-check="default">
<property name="jndiName">
<value>com.bt.bbv.r1oss</value>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
lazy-init="default" autowire="default" dependency-check="default">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
</beans>
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
Integration with Struts
пЃ®
<plug-in
пЃ®
</plug-in>
className="org.springframework.web.struts.ContextLoaderPlug
In"> <set-property property="contextConfigLocation"
value="/WEB-INF/spring/core/spring-advice.xml,/WEBINF/spring/core/spring-dao.xml,/WEBINF/spring/core/spring-email.xml,/WEBINF/spring/core/spring-services.xml,/WEBINF/spring/core/spring-tasks.xml,/WEBINF/spring/core/spring-webservices.xml" />
Integration with Struts
пЃ®
пЃ®
пЃ®
<bean id="CispWebService" class="com.bt.bbv.core.util.webservices.WebServiceProxyFactoryBean">
</property>- <property name="servicePrefix">
<value>CISP</value>
пЃ®
</property> <property name="wsdlDocumentUrl">
пЃ®
<value>classpath:com/btexact/cisp/api/CispApiEJB.wsdl</value>
пЃ®
пЃ®
пЃ®
пЃ®
пЃ®
</property>- <property name="serviceInterface">
<value>com.bt.bbv.core.service.cisp.webservice.CispApiEJBPort</value>
<property name="serviceName"><value>CispApiEJB</value>
</property> <property name="portName"> <value>CispApiEJBPort</value>
</property> <property
name="portInterface"><value>com.btexact.cisp.api.CispApiEJBPort</value></property>
</bean>
Integration with LDAP
пЃ®
пЃ®
<public class TraditionalPersonDaoImpl implements PersonDao {
public List getAllPersonNames() {
пЃ®
Hashtable env = new Hashtable();
пЃ®
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
пЃ®
env.put(Context.PROVIDER_URL, "ldap://localhost:389/dc=example,dc=com");
пЃ®
DirContext ctx = new InitialDirContext(env);
}
пЃ®
catch (NamingException e) {
пЃ®
throw new RuntimeException(e);
пЃ®
пЃ®
}
Integration with EJB
<bean id="myComponent“
class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBea
n">
пЃ®
<property name="jndiName" value="ejb/myBean"/> <property
name="businessInterface" value="com.mycom.MyComponent"/> </bean>
References
пЃ®
пЃ®
пЃ®
пЃ®
Spring’s homepage: http://www.springframework.org
“Introducing the Spring Framework” by Rod Johnson:
http://theserverside.com/news/thread.jsp?thread_id=2
1893
“Inversion of control containers and dependency
injection” by Martin Fowler:
http://www.martinfowler.com/articles/injection.html
AOP Alliance: http://aopalliance.sourceforge.net
Документ
Категория
Презентации
Просмотров
18
Размер файла
162 Кб
Теги
1/--страниц
Пожаловаться на содержимое документа