SlideShare a Scribd company logo
 “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
 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)
 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
 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
 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
 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.
 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"/>
 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">
 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
 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”
 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
 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
 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()
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
 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 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
 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
 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
<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>
 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
 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.
 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
 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);
}
 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
 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
 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.
}
}
 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
 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
}
}
<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>
<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
 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
 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
 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
 Spring provides AOP support for declarative
transactions
 Delegates to a PlatformTransactionManager
instance
◦ DataSourceTransactionManager
◦ HibernateTransactionManager
◦ JdoTransactionManager
◦ JtaTransactionManager
<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 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)
<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
<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
 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
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);
}
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()]);
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()]);
}
}
<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>
 JDBCTemplate provides
◦ Translation of SQLExceptions to more meaningful Spring
Runtime exceptions
◦ Integrates thread-specific transactions
 MappingSQLQuery simplifies mapping of
ResultSets to Java objects
 The DispatcherServlet is the Spring Front
Controller
 Initializes WebApplicationContext
 Uses /WEB-INF/[servlet-name]-servlet.xml by
default
 WebApplicationContext is bound into
ServletContext
 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
 MultipartResolver
◦ Handling of file upload
 LocaleResolver
◦ Default uses HTTP accept header, cookie, or session
 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
 CommandControllers bind parameters to data
objects
 AbstractCommandController
 AbstractFormController
 SimpleFormController
 WizardFormController

More Related Content

What's hot

Spring 3.1 in a Nutshell
Spring 3.1 in a NutshellSpring 3.1 in a Nutshell
Spring 3.1 in a Nutshell
Sam Brannen
 
Types of Dependency Injection in Spring
Types of Dependency Injection in SpringTypes of Dependency Injection in Spring
Types of Dependency Injection in Spring
Sunil kumar Mohanty
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
Antoine Rey
 
50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes
Antonio Goncalves
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
elliando dias
 
Whats New In Java Ee 6
Whats New In Java Ee 6Whats New In Java Ee 6
Whats New In Java Ee 6
Stephan Janssen
 
Javaee6 Overview
Javaee6 OverviewJavaee6 Overview
Javaee6 Overview
Carol McDonald
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
sourabh aggarwal
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
emanuelez
 
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
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
srmelody
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
bestonlinetrainers
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
Mohammad Faizan
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10min
Corneil du Plessis
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, maven
Fahad Golra
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
sourabh aggarwal
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
Pankaj Singh
 
Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望
javatwo2011
 

What's hot (20)

Spring 3.1 in a Nutshell
Spring 3.1 in a NutshellSpring 3.1 in a Nutshell
Spring 3.1 in a Nutshell
 
Types of Dependency Injection in Spring
Types of Dependency Injection in SpringTypes of Dependency Injection in Spring
Types of Dependency Injection in Spring
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
 
50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Whats New In Java Ee 6
Whats New In Java Ee 6Whats New In Java Ee 6
Whats New In Java Ee 6
 
Javaee6 Overview
Javaee6 OverviewJavaee6 Overview
Javaee6 Overview
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
 
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 dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10min
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, maven
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 
Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望
 

Viewers also liked

Comparing Java Web Frameworks
Comparing Java Web FrameworksComparing Java Web Frameworks
Comparing Java Web Frameworks
Matt Raible
 
Presentation Spring, Spring MVC
Presentation Spring, Spring MVCPresentation Spring, Spring MVC
Presentation Spring, Spring MVCNathaniel Richand
 
J2EE Introduction
J2EE IntroductionJ2EE Introduction
J2EE Introduction
Patroklos Papapetrou (Pat)
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
Dzmitry Naskou
 
Presentation Spring
Presentation SpringPresentation Spring
Presentation Spring
Nathaniel Richand
 
Workshop Spring - Session 1 - L'offre Spring et les bases
Workshop Spring  - Session 1 - L'offre Spring et les basesWorkshop Spring  - Session 1 - L'offre Spring et les bases
Workshop Spring - Session 1 - L'offre Spring et les bases
Antoine Rey
 
Support de cours Spring M.youssfi
Support de cours Spring  M.youssfiSupport de cours Spring  M.youssfi
Support de cours Spring M.youssfi
ENSET, Université Hassan II Casablanca
 

Viewers also liked (7)

Comparing Java Web Frameworks
Comparing Java Web FrameworksComparing Java Web Frameworks
Comparing Java Web Frameworks
 
Presentation Spring, Spring MVC
Presentation Spring, Spring MVCPresentation Spring, Spring MVC
Presentation Spring, Spring MVC
 
J2EE Introduction
J2EE IntroductionJ2EE Introduction
J2EE Introduction
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Presentation Spring
Presentation SpringPresentation Spring
Presentation Spring
 
Workshop Spring - Session 1 - L'offre Spring et les bases
Workshop Spring  - Session 1 - L'offre Spring et les basesWorkshop Spring  - Session 1 - L'offre Spring et les bases
Workshop Spring - Session 1 - L'offre Spring et les bases
 
Support de cours Spring M.youssfi
Support de cours Spring  M.youssfiSupport de cours Spring  M.youssfi
Support de cours Spring M.youssfi
 

Similar to Spring frame work

EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
Peter Antman
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
JBoss AS7 OSDC 2011
JBoss AS7 OSDC 2011JBoss AS7 OSDC 2011
JBoss AS7 OSDC 2011
Jason Shepherd
 
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
than sare
 
Spring training
Spring trainingSpring training
Spring training
TechFerry
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introduction
Ondrej Mihályi
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
CoffeeScript By Example
CoffeeScript By ExampleCoffeeScript By Example
CoffeeScript By Example
Christopher Bartling
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
David McCarter
 
Spring framework
Spring frameworkSpring framework
Spring framework
Ajit Koti
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
Suman Sourav
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
wiradikusuma
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
Gunith Devasurendra
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
Appster1
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
Appster1
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2
Sam Brannen
 
Java EE 8 security and JSON binding API
Java EE 8 security and JSON binding APIJava EE 8 security and JSON binding API
Java EE 8 security and JSON binding API
Alex Theedom
 
Spring overview
Spring overviewSpring overview
Spring overview
Dhaval Shah
 
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
 
Eclipse MicroProfile: Accelerating the adoption of Java Microservices
Eclipse MicroProfile: Accelerating the adoption of Java MicroservicesEclipse MicroProfile: Accelerating the adoption of Java Microservices
Eclipse MicroProfile: Accelerating the adoption of Java Microservices
Dev_Events
 

Similar to Spring frame work (20)

EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
JBoss AS7 OSDC 2011
JBoss AS7 OSDC 2011JBoss AS7 OSDC 2011
JBoss AS7 OSDC 2011
 
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 training
Spring trainingSpring training
Spring training
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introduction
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
CoffeeScript By Example
CoffeeScript By ExampleCoffeeScript By Example
CoffeeScript By Example
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2
 
Java EE 8 security and JSON binding API
Java EE 8 security and JSON binding APIJava EE 8 security and JSON binding API
Java EE 8 security and JSON binding API
 
Spring overview
Spring overviewSpring overview
Spring overview
 
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)
 
Eclipse MicroProfile: Accelerating the adoption of Java Microservices
Eclipse MicroProfile: Accelerating the adoption of Java MicroservicesEclipse MicroProfile: Accelerating the adoption of Java Microservices
Eclipse MicroProfile: Accelerating the adoption of Java Microservices
 

More from husnara mohammad

Ajax
AjaxAjax
Log4e
Log4eLog4e
Jsp intro
Jsp introJsp intro
Jsp intro
husnara mohammad
 
Hibernate
HibernateHibernate
Hibernate
husnara mohammad
 
J2EE
J2EEJ2EE
Java intro
Java introJava intro
Java intro
husnara mohammad
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
husnara mohammad
 
Asp dot net
Asp dot netAsp dot net
Asp dot net
husnara mohammad
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
husnara mohammad
 
Selenium
SeleniumSelenium
Sql introduction
Sql introductionSql introduction
Sql introduction
husnara mohammad
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
husnara mohammad
 
C++ basics
C++ basicsC++ basics
C++ basics
husnara mohammad
 
Ajax basic intro
Ajax basic introAjax basic intro
Ajax basic intro
husnara mohammad
 
Backbone js
Backbone jsBackbone js
Backbone js
husnara mohammad
 
Web attacks
Web attacksWeb attacks
Web attacks
husnara mohammad
 

More from husnara mohammad (16)

Ajax
AjaxAjax
Ajax
 
Log4e
Log4eLog4e
Log4e
 
Jsp intro
Jsp introJsp intro
Jsp intro
 
Hibernate
HibernateHibernate
Hibernate
 
J2EE
J2EEJ2EE
J2EE
 
Java intro
Java introJava intro
Java intro
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
Asp dot net
Asp dot netAsp dot net
Asp dot net
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
Selenium
SeleniumSelenium
Selenium
 
Sql introduction
Sql introductionSql introduction
Sql introduction
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
C++ basics
C++ basicsC++ basics
C++ basics
 
Ajax basic intro
Ajax basic introAjax basic intro
Ajax basic intro
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Web attacks
Web attacksWeb attacks
Web attacks
 

Recently uploaded

Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 

Recently uploaded (20)

Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 

Spring frame work

  • 1.
  • 2.  “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.  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.  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
  • 5.
  • 6.
  • 7.  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.  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.  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.  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.  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.  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.  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.  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.  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.  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. 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.  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 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.  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.  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. <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>
  • 23.
  • 24.  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.  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.  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.  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.  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
  • 29.  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.  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.  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.  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. <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. <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.  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.  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.  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
  • 38.
  • 39.  Spring provides AOP support for declarative transactions  Delegates to a PlatformTransactionManager instance ◦ DataSourceTransactionManager ◦ HibernateTransactionManager ◦ JdoTransactionManager ◦ JtaTransactionManager
  • 40. <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 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. <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. <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
  • 44.
  • 45.  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. 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. 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. 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. <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.  JDBCTemplate provides ◦ Translation of SQLExceptions to more meaningful Spring Runtime exceptions ◦ Integrates thread-specific transactions  MappingSQLQuery simplifies mapping of ResultSets to Java objects
  • 51.
  • 52.  The DispatcherServlet is the Spring Front Controller  Initializes WebApplicationContext  Uses /WEB-INF/[servlet-name]-servlet.xml by default  WebApplicationContext is bound into ServletContext
  • 53.  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.  MultipartResolver ◦ Handling of file upload  LocaleResolver ◦ Default uses HTTP accept header, cookie, or session
  • 55.  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.  CommandControllers bind parameters to data objects  AbstractCommandController  AbstractFormController  SimpleFormController  WizardFormController

Editor's Notes

  1. Template closures JDBC support also provided