Spring Paul Jensen Principal, Object Computing Inc.

Slides:



Advertisements
Similar presentations
AspectWerkz 2 - and the road to AspectJ 5 Jonas Bonér Senior Software Engineer BEA Systems.
Advertisements

Spring, Hibernate and Web Services 13 th September 2014.
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
Enterprise Application Development Sadegh Aliakbary An Introduction to Spring Framework www. JavaCup.ir.
Review Amit Shabtay. March 3rd, 2004 Object Oriented Design Course 2 Review What have we done during the course? Where to learn more? What is for the.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
© 2005, Cornell University. Rapid Application Development using the Kuali Architecture (Struts, Spring and OJB) A Case Study Bryan Hutchinson
The Spring Framework: A brief introduction to Inversion of Control James Brundege
Last Update: 5/15/061 Spring J2EE Framework Ram A. Rao May 15 th ‘05.
Intro to Spring CJUG - January What is Spring? “The Spring framework provides central transaction control of various objects.” This means that any.
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
Spring Framework Adam Waldal Senior Consultant. About me..  OPI is a leader in J2EE consulting with Relationships with BEA, IBM, Tibco, and many other.
Intermediate Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
Spring Framework. Spring Overview Spring is an open source layered Java/J2EE application framework Created by Rod Johnson Based on book “Expert one-on-one.
Spring Overview, Application demo -Midhila Paineni 09/23/2011 Spring Overview, Application demo9/8/20151.
Spring. Spring Overview Spring Container Concepts Spring and AOP Spring and Data Access Managing Transactions and Resources Remoting and Accessing Enterprise.
BEST PRACTICES - Java By Configuration Use global-forwards/results Helps to avoid duplicate jsp files and redundancy forward mapping.
The Spring Framework Training Get to know Spring Framework Rohit Prabhakar
Introduction to the Spring Framework Rajesh. Spring Mission Statement J2EE should be easier to use OO design is more important than any implementation.
Copyright © 2012 Accenture All Rights Reserved.Copyright © 2012 Accenture All Rights Reserved. Accenture, its logo, and High Performance Delivered are.
Copyright (C) 2009 by Abdelmonaim Remani. All rights reserved. By Abdelmonaim Remani Polymathic-coder.com Silicon Valley Code.
OpusCollege and the use of Spring and iBatis
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Understanding the Bean Lifecycle An.
Spring core v3.x Prepared by: Nhan Le. History v3.0 Spring Expression Language Java based bean metadata v3.1 Cache Abstraction Bean Definition Profile.
Opus College - overview. OpusCollege - background First project: ICT Capacity Building Mozambican Higher Education Institutions Partners: RUG Groningen,
Spring Framework. Spring Overview Spring is an open source layered Java/J2EE application framework Created by Rod Johnson Based on book “Expert one-on-one.
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
Spring Training 17/09/ Dependency Injection.
Creative Commons Attribution- NonCommercial-ShareAlike 2.5 License Sakai Programmer's Café Sakai Montreal CRIM Workshop Introduction to Spring Framework,
A Presentation By V AIBHAV S AHARAN Web-enHanced Information Management COMS E6125.
Chapter 8 Object Design Reuse and Patterns. Object Design Object design is the process of adding details to the requirements analysis and making implementation.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Forms with Spring MVC Handling Form.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring Remoting Simplifying.
Struts Framework Anna Paščenko. What is Struts?  An open source framework for building Java web applications.
AspectJ – AOP for Java Tom Janofsky. Instructor at Penn State Abington Consultant with Chariot Solutions JUG Member.
INTEGRATION OF BACKBONE.JS WITH SPRING 3.1. Agenda New Features and Enhancements in Spring 3.1 What is Backbone.js and why I should use it Spring 3.1.
Object-Oriented Programming Chapter Chapter
Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009.
Object Oriented Programming
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Spring and DWR Frameworks for Rich Web Enterprise Application Thomas Wiradikusuma Presentation to the 20 th.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
1 Spring Framework April, 2012 Lam Ho Lam To. © 2010 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 2 1.Spring Overview 2.Framework.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring AOP – Part 2 Advanced Aspect-Oriented.
Aspect Oriented Programming Adlux Consultancy Services Pvt Ltd
Kansas City Java User’s Group Jason W. Bedell July 12, 2006
问题 Code scattering Blocks of duplicated code Blocks of complementary code, and different modules implementing complementary parts of the concern Code.
Comparison of Different AOP Approaches Presented by: Xiaojing Wang.
Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009.
Spring Framework BT Team 25/02/ Spring A lightweight framework that addresses each tier in a Web application. Presentation layer – An MVC framework.
Spring JDBC Dima Ionut Daniel. Contents What is Spring JDBC? Overview Spring JDBC Core SQL Exceptions Database Connection Batch Operations Handling BLOB/CLOB.
The Chain of Responsibility Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Singleton Academy, Pune. Course syllabus Singleton Academy Pune – Course Syllabus1.
L’origine dei mali: le dipendenze tra componenti Stefano Leli 14° Workshop DotNetMarche Venerdì 16 aprile
Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions and Spring MVC Buenos Aires, June 2009.
Creative Commons Attribution- NonCommercial-ShareAlike 2.5 License Sakai Programmer's Café Sakai Montreal CRIM Workshop Introduction to Spring Framework.
Leveraging ColdSpring to build a robust Flex applications Chris Scott, Cynergy Systems.
J2EE Lecture 6: Spring – IoC and Dependency Injection
CS520 Web Programming Spring – Inversion of Control
By Ru Shen Department of Computer Science UAlbany, 2008
Intro to Spring CJUG - January 2013.
AVG 24th 2015 ADVANCED c# - part 1.
Java Programming Language
Introduction to Spring Framework and Dependency Injection
JAsCo an Aspect-Oriented approach tailored for
Developing and testing enterprise Java applications
CS520 Web Programming Spring – Aspect Oriented Programming
Leveraging ColdSpring To Make Better Applications
Aspect Oriented Programming
Presentation transcript:

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) Promotes/simplifies decoupling, design to interfaces, TDD Declarative programming without J2EE Easily configured aspects, esp. transaction support Simplify use of popular technologies Abstractions insulate application from specifics, eliminate redundant code, and handle common error conditions Underlying technology specifics still accessible (closures)

Why Use Spring? Conversion of checked exceptions to unchecked (Or is this a reason not to use it?) Not an all-or-nothing solution Extremely modular and flexible Well designed Easy to extend Many reusable classes

Spring Framework

Spring Application

Spring Dependency Injection Inversion of Control (IoC) “Hollywood Principle” Don't call me, I'll call you “Container” resolves (injects) dependencies of components by setting implementation object (push) As opposed to component instantiating or Service Locator pattern where component locates implementation (pull) Martin Fowler calls Dependency Injection

Dependency Injection Variants Variations on dependency injection Interface based (Avalon) Constructor-based (PicoContainer, Spring) Setter-based (Spring) BeanFactory provides configuration framework to initialize and “wire” JavaBeans org.springframework.beans and org.springframework.context Typically use the XmlBeanFactory, employing XML configuration files

Dependency Injection (cont'd) BeanFactory configured components need have no Spring dependencies Simple JavaBeans Beans are singletons by default Properties may be simple values or references to other beans Built-in support for defining Lists, Maps, Sets, and Properties collection types. Custom PropertyEditors may be defined to convert string values to other, arbitrary types.

XmlBeanFactory Example Property and constructor based IoC 1 1

Bean Creation Direct instantiation BeanFactory instantiation Same syntax but class is subclass of BeanFactory getObject() called to obtain Bean Static Factory Instance Factory Method

Bean Creation Beans may be singletons or “prototypes” Attribute singleton=“false” causes instantiation with each getBean() lookup Singleton is default XmlBeanFactory pre-instantiates singletons May be overridden on per-instance basis by lazy- init=“true” Beans may also be marked abstract, allowing reuse of attribute values through inheritance

Autowiring Properties Beans may be auto-wired (rather than using ) Per-bean attribute autowire Explicit settings override autowire=“name” Bean identifier matches property name autowire=“type” Type matches other defined bean autowire=”constructor” Match constructor argument types autowire=”autodetect” Attempt by constructor, otherwise “type”

Dependency Checking Ensures properties are defined Per-bean attribute dependency-check None required by default Verifies autowiring succeeded “simple” all but collaborators “object” collaborators only “all” Collaborators, primitive types, and collections

Lifecycle Customization Can define init method called after properties set init-method=” ” Can define destroy method as shutdown hook destroy-method=” ” May alternatively implement InitializingBean and/or DisposableBean At cost of Spring dependency

BeanFactory Miscellany BeanFactoryAware interface provides BeanFactory for bean setBeanFactory(BeanFactory) BeanNameAware interface provides bean name setBeanName(String) FactoryBean for beans which are themselves factories Object getObject() Boolean isSingleton() Class getObjectType()

BeanFactory Usage InputStream is = new FileInputStream("beans.xml"); XmlBeanFactory factory = new XmlBeanFactory(is); MyBeanClass bean = (MyBeanClass)factory.getBean(“myBean”); ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); MyBeanClass bean = (MyBeanClass)ctx.getBean(“myBean”); OR

ApplicationContext Extends functionality of BeanFactory Pre-instantiates singleton beans Detects and registers BeanPostProcessors and BeanFactoryPostProcessors Supports nesting of contexts ApplicationListener and ApplicationEvents Initialized and closed predefined Custom may be created MessageSource provides i18n messaging Contains list of bundle base names

Web Initialization Web applications may use ContextLoaderListener to initialize Spring contextConfigLocation /WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml org.springframework.web.context.ContextLoaderListener web.xml Automatically done by Spring DispatcherServlet

Specialized Beans MethodInvokingFactoryBean Invokes method on registered beans or any static methods Stores return value SingletonBeanFactoryLocator and ContextSingletonBeanFactoryLocator Useful for sharing BeanFactories Eliminate duplication of beans in multiple similar factories or contexts

ApplicationContext customization Defined beans inheriting from BeanFactoryPostProcessor are detected and invoked CustomEditorConfigurer Registers custom PropertyEditors for converting configuration string values to specific types AutoProxyCreators Wrap beans in proxies based on various criteria (name, metadata, etc) PropertyResourceConfigurer Sets from property file and/or system properties

ApplicationContext Example <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> database.properties <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> ${database.connection.driver_class} ${database.connection.url}

Spring AOP

AOP Fundamentals Aspect-oriented programming (AOP) provides for simplified application of cross-cutting concerns Transaction management Security Logging Auditing Locking AOP sometimes (partially) achieved via Decorators or Proxies CORBA Portable Interceptors Servlet Filters

AOP Fundamentals Aspect - Implementation of a cross-cutting concern. Spring Advisors or Interceptors Joinpoint - Execution point to target Typically, methods Advice - Action taken at a particular joinpoint. Pointcut - A set of joinpoints specifying where advice should be applied (e.g. Regular expression) Introduction/Mixin - Adding methods or fields to an advised class. Weaving - Assembling aspects into advised objects.

Spring AOP Generally, applies aspects to beans using BeanFactory Uses Dynamic Proxies if interface available otherwise CGLIB CGLIB creates derived class which proxies requests Bean class may not be final Less capable than AspectJ does not have field interception only runtime weaving solution is available Closer integration with AspectJ anticipated

Spring Pointcuts Pointcut applicability to a class may be evaluated statically or dynamically Spring only creates proxies where necessary public interface Pointcut { ClassFilter getClassFilter(); MethodMatcher getMethodMatcher(); } public interface ClassFilter { boolean matches(Class clazz); }

Pointcuts (cont'd) public interface MethodMatcher { boolean matches(Method m, Class targetClass); boolean isRuntime(); boolean matches(Method m, Class targetClass, Object[] args); } Pointcut may be statically or dynamically evaluated based on isRuntime() Abstract class StaticMethodMatcherPointcut requires override of 1 st method only Only called if isRuntime() == true

Pointcuts (cont'd) Spring predefined pointcuts In org.springframework.aop.support package RegexpMethodPointcut Union of multiple regular expressions Uses Jakarta ORO package ControlFlowPointcut Similar to AspectJ cflow Applied if call stack includes specific class and, optionally, method UnionPointcut Merges pointcuts

Spring Advice Can have per-class or per-instance Advice Spring provides several Advice types Around Advice AOP Alliance compliant Must call invocation.proceed() to call target public class MyAdvice implements AroundAdvice { Object invoke(MethodInvocation invocation) { // change arguments, start transaction, lock, etc. invocation.proceed(); // change return value, stop transaction, unlock,etc. }

Spring Advice MethodBeforeAdvice void before(Method m, Object[] args, Object target) Cannot alter return type ThrowsAdvice Marker interface Implementors define methods of form: afterThrowing([Method], [args], [target], subclassOfThrowable) AfterReturningAdvice void afterReturning(Object returnValue, Method, m, Object[] args, Object target) Cannot modify return value

Spring Advice IntroductionInterceptor provides ability to define mixins public class RollbackAdvice extends DelegatingIntroductionInterceptor implements RollbackSupport { Map map = new HashMap(); void rollback(Date date) { // rollback to state at given time } public Object invoke(MethodInvocation invocation) { // record change and time of change }

Injecting Advice <bean id=“meetingTarget" class=“ex.DefaultMeeting“ singleton=“false”> Spring <bean id="myAdvisor" class=“ex.RollbackAdvice" singleton=”false”> <bean id="debugInterceptor" class="org.springframework.aop.interceptor.DebugInterceptor">

Injecting Advice (cont'd) <bean id=“meeting" class="org.springframework.aop.framework.ProxyFactoryBean"> ex.Meeting myAdvisor debugInterceptor Advisors applied in order All methods using CGLib if none defined

Autoproxying Autoproxy bean definitions automatically proxy selected beans. BeanNameAutoProxyCreator Adds listed advisors/interceptors to beans with names matching regular expression DefaultAdvisorAutoProxyCreator Generic autoproxy infrastructure support Applies all advisors defined in the context to all beans, proxying appropriately

Metadata support Spring supports obtaining meta data Object attributes at class, method, and field level Not yet argument level (as JSR-175) Currently supports Jakarta Commons Attributes Support for JSR-175 in work Metadata support provided via Attributes interface Amenable to mocking unlike JDK reflection and Commons static methods

Metadata autoproxying Configuration of autoproxying based on metadata attributes simplifies configuration Define custom attribute class Define Advisor with pointcut based on custom attribute Add Advisor in ApplicationContext with autoproxy Examples Transaction Attributes Security Attributes Pooling Mapping of controllers to URLs

Transactions

AOP Transactions Spring provides AOP support for declarative transactions Delegates to a PlatformTransactionManager instance DataSourceTransactionManager HibernateTransactionManager JdoTransactionManager JtaTransactionManager

Transaction Configuration <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean"> com/../model/*.hbm.xml <bean id="transactionManager” class="org.springframework.orm.hibernate.HibernateTransactionManager">

Declarative Transactions Declarative transactional support can be added to any bean by using TransactionProxyFactoryBean Similar to EJB, transaction attributes may be defined on a per-method basis Also allows definition of pre- and post- interceptors (e.g. for security)

Injecting Transaction Support <bean id=“reservationService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> PROPAGATION_REQUIRED PROPAGATION_REQUIRED,readOnly Declarative transaction support for single bean

Transaction Autoproxy < bean id="autoproxy" class="org...DefaultAdvisorAutoProxyCreator"> <bean id="transactionAdvisor" class="org...TransactionAttributeSourceAdvisor" autowire="constructor" > <bean id="transactionInterceptor" class="org...TransactionInterceptor" autowire="byType"> <bean id="transactionAttributeSource" class="org...AttributesTransactionAttributeSource" autowire="constructor"> <bean id="attributes" class="org...CommonsAttributes" /> Caches metadata from classes Generic autoproxy support Applies transaction using transactionManager Invokes interceptor based on attributes

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 com/jensenp/Reservation/Room.hbm.xml com/jensenp/Reservation/Reservation.hbm.xml com/jensenp/Reservation/Resource.hbm.xml ${hibernate.dialect} ${hibernate.hbm2ddl.auto} ${hibernate.show_sql} <bean id=“reservationDao" class="com.jensenp.Reservation.ReservationDaoImpl">

JDBC Support JDBCTemplate provides Translation of SQLExceptions to more meaningful Spring Runtime exceptions Integrates thread-specific transactions MappingSQLQuery simplifies mapping of ResultSets to Java objects

Web Framework

DispatcherServlet The DispatcherServlet is the Spring Front Controller Initializes WebApplicationContext Uses /WEB-INF/[servlet-name]-servlet.xml by default WebApplicationContext is bound into ServletContext

DispatcherServlet Configuration HandlerMapping Routing of requests to handlers HandlerAdapter Adapts to handler interface. Default utilizes Controllers HandlerExceptionResolver Maps exceptions to error pages Similar to standard Servlet, but more flexible ViewResolver Maps symbolic name to view

Dispatcher Servlet Configuration MultipartResolver Handling of file upload LocaleResolver Default uses HTTP accept header, cookie, or session

Controllers Controller interface defines one method ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception ModelAndView consists of a view identifier and a Map of model data

Controller Implementations CommandControllers bind parameters to data objects AbstractCommandController AbstractFormController SimpleFormController WizardFormController

References Spring’s homepage: “Introducing the Spring Framework” by Rod Johnson: “Inversion of control containers and dependency injection” by Martin Fowler: AOP Alliance: