Framework Concepts. Gpower Software 1 - 2 The enterprise challenge.

Slides:



Advertisements
Similar presentations
Introduction to the Spring Framework
Advertisements

Aspect Oriented Programming. AOP Contents 1 Overview 2 Terminology 3 The Problem 4 The Solution 4 Join point models 5 Implementation 6 Terminology Review.
Spring, Hibernate and Web Services 13 th September 2014.
G O B E Y O N D C O N V E N T I O N WORF: Developing DB2 UDB based Web Services on a Websphere Application Server Kris Van Thillo, ABIS Training & Consulting.
Technical Architectures
Hibernate 1. Introduction ORM goal: Take advantage of the things SQL databases do well, without leaving the Java language of objects and classes. ORM.
© 2005, Cornell University. Rapid Application Development using the Kuali Architecture (Struts, Spring and OJB) A Case Study Bryan Hutchinson
Software Engineering Module 1 -Components Teaching unit 3 – Advanced development Ernesto Damiani Free University of Bozen - Bolzano Lesson 2 – Components.
ASP.NET Programming with C# and SQL Server First Edition
Last Update: 5/15/061 Spring J2EE Framework Ram A. Rao May 15 th ‘05.
An Introduction to Hibernate Matt Secoske
Struts 2.0 an Overview ( )
UNIT-V The MVC architecture and Struts Framework.
Java Frameworks Indy Java Users Group January 29, 2003.
JDBC Session 5 Tonight: Data Access Patterns 1.J2EE Architecture & Design Patterns 2.The Data Access Tier 3.Data Access Patterns –DataAccessObject (DAO)
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
UPortal Developers MIT August 2004 Persistence Strategy for uPortal 3 Mike DeSimone the r-smart group
Agenda What is Hibernate Spring Integration Questions Overview
Introduction to the Spring Framework Rajesh. Spring Mission Statement J2EE should be easier to use OO design is more important than any implementation.
What is Architecture  Architecture is a subjective thing, a shared understanding of a system’s design by the expert developers on a project  In the.
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
Enterprise JavaBeans. What is EJB? l An EJB is a specialized, non-visual JavaBean that runs on a server. l EJB technology supports application development.
EJB Framework.  As we know, EJB is the center of the J2EE architecture that provides a sturdy framework for building enterprise applications. The major.
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.
Hibernate Query Language Make SQL be object oriented – Classes and properties instead of tables and columns – Polymorphism – Associations – Much less verbose.
SAMANVITHA RAMAYANAM 18 TH FEBRUARY 2010 CPE 691 LAYERED APPLICATION.
Object/Relational Mapping with Hibernate Practical ORM.
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.
Creative Commons Attribution- NonCommercial-ShareAlike 2.5 License Sakai Programmer's Café Sakai Montreal CRIM Workshop Introduction to Spring Framework,
Introduction to Web Dimitar Nenchev Ivan Nakov
A Presentation By V AIBHAV S AHARAN Web-enHanced Information Management COMS E6125.
Hibernate Introduction - 1 Present by Eric Yu. BeanSoft | 2 Content Understanding object/relational persistence Introduction Architecture The core interfaces.
Object-Relational Mapping with Hibernate Brian Sam-Bodden Principal Partner Integrallis Software, LLC. August 1 - 5, 2005.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring Remoting Simplifying.
Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
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.
1 Copyright © 2004, Oracle. All rights reserved. Oracle Application Development Framework.
Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.
Presentation.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
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.
Component Patterns – Architecture and Applications with EJB copyright © 2001, MATHEMA AG Component Patterns Architecture and Applications with EJB Markus.
Chapter 18 Object Database Management Systems. Outline Motivation for object database management Object-oriented principles Architectures for object database.
Java Programming: Advanced Topics 1 Enterprise JavaBeans Chapter 14.
Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Spring Framework BT Team 25/02/ Spring A lightweight framework that addresses each tier in a Web application. Presentation layer – An MVC framework.
Introduction – ORM, Helloworld Application
Spring JDBC Dima Ionut Daniel. Contents What is Spring JDBC? Overview Spring JDBC Core SQL Exceptions Database Connection Batch Operations Handling BLOB/CLOB.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
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.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
Creative Commons Attribution- NonCommercial-ShareAlike 2.5 License Sakai Programmer's Café Sakai Montreal CRIM Workshop Introduction to Spring Framework.
Hibernate Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
Leveraging ColdSpring to build a robust Flex applications Chris Scott, Cynergy Systems.
J2EE Platform Overview (Application Architecture)
J2EE Lecture 6: Spring – IoC and Dependency Injection
MPCS – Advanced java Programming
Object/Relational Mapping with Hibernate
JavaServer Faces: The Fundamentals
Introduction to Spring Framework and Dependency Injection
Developing and testing enterprise Java applications
Leveraging ColdSpring To Make Better Applications
Presentation transcript:

Framework Concepts

Gpower Software The enterprise challenge

Gpower Software How can you meet the enterprise challenges? Use a Flexible Foundation Use Open and Extensible Client Interfaces Leverage Legacy systems and data Adopt Component based solutions Database Flexible foundation Business Application

Gpower Software Business Application Customized Products Re-usable Components Beans ID engine calculation J2EE Server Application Framework Assembly on a Common platform Component based solutions Automotive industry Software business

Gpower Software What is a framework? A framework is a set of prefabricated software building blocks that programmers can use, extend, or customize for specific computing solutions By Taligent’s definition A framework is a set of prefabricated software building blocks that programmers can use, extend, or customize for specific computing solutions By Taligent’s definition With framework-oriented programming, software development is one step closer towards a factory mode of operation J2EE Server Application Framework Business Application

Gpower Software What should a framework achieve? An application framework will help to: Define the guidelines for building components Define how all the components should fit together Define the guidelines for managing change Ensure consistency of code Focus developers on business logic An application framework will help to: Define the guidelines for building components Define how all the components should fit together Define the guidelines for managing change Ensure consistency of code Focus developers on business logic

Gpower Software Business Functions 0 Small Scale Application development Large Scale Application Development With Framework Time/Effort Man days Without Framework X 3X Framework reduces development time Integration Design Requirement Coding Integration Design Requirement Coding

Gpower Software Statistics from Java World report Framework reduces development time Requirement Design Integration Without Framework *Development Time (months) 6-9 Months Integration Design 3-5 Months With Framework Requirement Coding

Hibernate

Gpower Software Why object/relational mapping? Solving the mismatch with tools Basic Hibernate features Hibernate Query Options Detached Objects Hibernate Introduction

Gpower Software The Structural Mismatch.  Java types vs. SQL datatypes  user-defined types (UDT) are in SQL:1999  current products are proprietary  Type inheritance  no common inheritance model  Entity relationships. Hibernate Introduction

Gpower Software “Modern” ORM Solutions  Transparent Persistence (POJO/JavaBeans)  Persistent/transient instances  Automatic Dirty Checking  Transitive Persistence  Lazy Fetching  Outer Join Fetching  Runtime SQL Generation  Three Basic Inheritance Mapping Strategies Hibernate Introduction

Gpower Software Why ORM  Structural mapping more robust  Less error-prone code  Optimized performance all the time  Vendor independence Hibernate Introduction

Gpower Software What do RDBs do well?  Work with large amounts of data  Searching, sorting  Work with sets of data  Joining, aggregating  Sharing  Concurrency (Transactions)  Many applications  Integrity  Constraints  Transaction isolation Hibernate Introduction

Gpower Software What do RDBs do badly?  Modeling  No polymorphism  Fine grained models are difficult  Business logic  Stored procedures really bad Hibernate Introduction

Gpower Software The Goal  Take advantage of those things that relational databases do well  Without leaving the language of objects / classes Hibernate Introduction

Gpower Software Hibernate  Opensource (LGPL)  Mature  Popular (15,000 downloads/month)  Custom API  Will be core of JBoss CMP 2.0 engine Hibernate Introduction

Gpower Software Features  Persistence for POJOs (JavaBeans)  Flexible and intuitive mapping  Support for fine-grained object models  Powerful, high performance queries  Dual-Layer Caching Architecture (HDLCA)  Toolset for roundtrip development  Support for detached persistent objects Hibernate Introduction

Gpower Software Hibernate High Level Architecture

Gpower Software Hibernate Full Cream Architecture

Gpower Software Conception SessionFactory –A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider Session –A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC connection. Factory for Transaction. Persistent Objects and Collections –Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, Transient Objects and Collections –Instances of persistent classes that are not currently associated with a Session. Transaction –A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases.

Gpower Software Example Hibernate Mapping

Gpower Software Persistent Class  JavaBean specification (or POJOs)  No-arg constructor  Accessor methods for properties  Collection property is an interface  Identifier property Hibernate Mapping public class AuctionItem { private Long _id; private Set _bids; private Bid _successfulBid private String _description; public Long getId() { return _id; } private void setId(Long id) { _id = id; } public String getDescription() { return _description; } public void setDescription(String desc) { _description=desc; } … }

Gpower Software XML Mapping  Readable metadata  Column/table mappings  Surrogate key generation strategy  Collection metadata  Fetching strategies Hibernate Mapping <set name=“bids” cascade=“all” lazy=“true”>

Gpower Software  Class <class name="ClassName" table="tableName" discriminator-value="discriminator_value" mutable="true|false" schema="owner" proxy="ProxyInterface" dynamic-update="true|false" dynamic-insert="true|false" select-before-update="true|false" polymorphism="implicit|explicit" where="arbitrary sql where condition" persister="PersisterClass" batch-size="N" optimistic-lock="none|version|dirty|all" lazy="true|false" /> Basic O/R Mapping

Gpower Software  ID <id name="propertyName" type="typename" column="column_name" unsaved-value="any|none|null|id_value" access="field|property|ClassName"> Generator: Increment, sequence, hilo, seqhilo, uuid.hex, native, assigned, foreign Basic O/R Mapping

Gpower Software  Composite-id <composite-id name="propertyName" class="ClassName" unsaved-value="any|none" access="field|property|ClassName"> Basic O/R Mapping

Gpower Software  Property <property name="propertyName" column="column_name" type="typename" update="true|false" insert="true|false" formula="arbitrary SQL expression" access="field|property|ClassName" /> Basic O/R Mapping

Gpower Software  Many to one <many-to-one name="propertyName" column="column_name" class="ClassName" cascade="all|none|save-update|delete" outer-join="true|false|auto" update="true|false" insert="true|false" property-ref="propertyNameFromAssociatedClass" access="field|property|ClassName" unique="true|false" />  One to one <one-to-one name="propertyName" class="ClassName" cascade="all|none|save-update|delete" constrained="true|false" outer-join="true|false|auto" property-ref="propertyNameFromAssociatedClass" access="field|property|ClassName" /> Basic O/R Mapping

Gpower Software  Collection (,,,, ) <map name="propertyName" table="table_name" schema="schema_name" lazy="true|false" inverse="true|false" cascade="all|none|save-update|delete|all-delete-orphan" sort="unsorted|natural|comparatorClass" order-by="column_name asc|desc" where="arbitrary sql where condition" outer-join="true|false|auto" batch-size="N" access="field|property|ClassName" > Basic O/R Mapping

Gpower Software  Many-to-many <many-to-many column="column_name" class="ClassName" outer-join="true|false|auto" /> Basic O/R Mapping

Gpower Software  Transient Objects Objects instantiated using the new operator aren’t immediately persistent. Their state is transient, which means they aren’t associated with any database table row, and so their state is lost as soon as they’re dereferenced.  Persist Objects A persistent instance is any instance with a database identity. Persistent instances are associated with the persistence manager. Persistent instances are always associated with a Session and are transactional  Detached Objects Instances lose their association with the persistence manager when you close() the Session. We refer to these objects as detached, indicating that their state is no longer guaranteed to be synchronized with database state; they’re no longer under the management of Hibernate. Object state

Gpower Software Object Lifecycle

Gpower Software Typical Usage Session sess = factory.openSession(); Transaction tx = null; try { tx = sess.beginTransaction(); // do some work... tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e; } finally { sess.close(); }

Gpower Software  Automatic dirty object checking  Retrieve an AuctionItem and change description Session session = sessionFactory.openSession(); Transaction tx = s.beginTransaction(); AuctionItem item = (AuctionItem) session.get(ActionItem.class, itemId); item.setDescription(newDescription); tx.commit(); session.close(); Hibernate Introduction

Gpower Software  Transitive Persistence  Retrieve an AuctionItem and create a new persistent Bid Bid bid = new Bid(); bid.setAmount(bidAmount); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); AuctionItem item = (AuctionItem) session.get(ActionItem.class, itemId); bid.setItem(item); item.getBids().add(bid); tx.commit(); session.close(); Hibernate Introduction

Gpower Software  Detached objects  Retrieve an AuctionItem and change the description: Session session = sf.openSession(); Transaction tx = session.beginTransaction(); AuctionItem item = (AuctionItem) session.get(ActionItem.class, itemId); tx.commit(); session.close(); item.setDescription(newDescription); Session session2 = sf.openSession(); Transaction tx = session2.beginTransaction(); session2.update(item); tx.commit(); session2.close(); Hibernate Introduction

Gpower Software Hibernate query options  Hibernate Query Language (HQL)  “ minimal ” object-oriented dialect of ANSI SQL  Criteria Queries  Extensible framework for expressing query criteria as objects  Includes “ query by example ”  Native SQL queries  Direct passthrough with automatic mapping  Named SQL queries in metadata Hibernate Introduction

Gpower Software Hibernate Query Language  Make SQL be object oriented  Classes and properties instead of tables and columns  Polymorphism  Associations  Much less verbose than SQL  Full support for relational operations  Inner/outer/full joins, cartesian products  Projection  Aggregation (max, avg) and grouping  Ordering  Subqueries  SQL function calls Hibernate Introduction

Gpower Software HQL Example  Simple from AuctionItem i.e. get all the AuctionItems: List allAuctions = session.createQuery( “ from AuctionItem ” ).list();  More realistic example select item from AuctionItem item join item.bids bid where item.description like ‘ hibernate% ’ and bid.amount > 100 i.e. get all the AuctionItems with a Bid worth > 100 and description that begins with “ hibernate ” Hibernate Introduction

Gpower Software Criteria Queries List auctionItems = session.createCriteria(AuctionItem.class).setFetchMode( “ bids ”, FetchMode.EAGER).add( Expression.like( “ description ”, description) ).createCriteria( “ successfulBid ” ).add( Expression.gt( “ amount ”, minAmount) ).list(); Equivalent HQL: from AuctionItem item left join fetch item.bids where item.description like :description and item.successfulbid.amount > :minAmount Hibernate Introduction

Gpower Software Example Queries AuctionItem item = new AuctionItem(); item.setDescription( “ hib ” ); Bid bid = new Bid(); bid.setAmount(1.0); List auctionItems = session.createCriteria(AuctionItem.class).add( Example.create(item).enableLike(MatchMode.START) ).createCriteria( “ bids ” ).add( Example.create(bid) ).list(); Equivalent HQL: from AuctionItem item join item.bids bid where item.description like ‘ hib% ’ and bid.amount > 1.0 Hibernate Introduction

Gpower Software Fine-grained persistence  Fine-grained object models are good  greater code reuse  easier to understand  More typesafe  Better encapsulation  Hibernate defines  Entities (lifecycle and relationships)  Values (no identity, “ embedded ” state) Hibernate Introduction

Gpower Software Composing Objects  Address of a User  Address depends on User Hibernate Introduction

Gpower Software Layer Communication  The presentation layer is decoupled from the service layer and business logic: Hibernate Introduction Presentation Layer Service Layer Domain Objects Remote?DTO?

Gpower Software DTOs are Evil  “ Useless ” extra LOC  Not objects (no behavior)  Parallel class hierarchies smell  Shotgun change smell Solution: detached object support Hibernate Introduction

Gpower Software Detached Object Support  For applications using servlets + session beans  You don ’ t need to select a row when you only want to update it!  You don ’ t need DTOs anymore!  You may serialize objects to the web tier, then serialize them back to the EJB tier in the next request  Hibernate lets you selectively reassociate a subgraph! (essential for performance) Hibernate Introduction

Gpower Software FeatureReview Transparent PersistenceBad Persistent/transient instancesBad Automatic Dirty CheckingGood Transitive PersistenceBad Lazy FetchingGood Outer Join FetchingAverage Runtime SQL GenerationAverage Three Basic Inheritance Mapping Strategies Bad Hibernate Introduction  CMP VS Hibernate

Spring Framework Core

Gpower Software A clear separation of application component responsibility. –Presentation layer Concentrates on request/response actions Handles UI rendering from a model. Contains formatting logic and non-business related validation logic. Handles exceptions thrown from other layers –Persistence layer Used to communicate with a persistence store such as a relational database. Provides a query language Possible O/R mapping capabilities JDBC, Hibernate, iBATIS, JDO, Entity Beans, etc. –Domain layer Contains business objects that are used across above layers. Contain complex relationships between other domain objects May be rich in business logic May have ORM mappings Domain objects should only have dependencies on other domain objects Application Layering

Gpower Software Application Layering (cont) –Service layer Gateway to expose business logic to the outside world Manages ‘container level services’ such as transactions, security, data access logic, and manipulates domain objects Not well defined in many applications today or tightly coupled in an inappropriate layer.

Gpower Software Proposed Web App Layering

Gpower Software Presentation/Business/Persistence Struts+Spring+Hibernate Struts + Spring + EJB JavaServer Faces + Spring + iBATIS Spring + Spring + JDO Flex + Spring + Hibernate Struts + Spring + JDBC You decide… More Application Layering Combinations

Gpower Software Sun’s traditional solution to middle tier business logic Specification that did not always work as projected in real applications. EJBs are less portable than POJO based architectures. Inconsistencies by vendors make EJBs break the “write once, run anywhere” rule. Fosters over-engineering in most cases Entity Beans – very limiting compared to alternatives such as Hibernate. Performance with POJOs are much faster then EJBs. EJBs run in a heavy container Your code becomes coupled to EJB API. We need to redefine what J2EE means… EJB (<=2.x) in the Service Layer

Gpower Software A lightweight framework that addresses each tier in a Web application. –Presentation layer – An MVC framework that is most similar to Struts but is more powerful and easy to use. –Business layer – Lightweight IoC container and AOP support (including built in aspects) –Persistence layer – DAO template support for popular ORMs and JDBC Simplifies persistence frameworks and JDBC Complimentary: Not a replacement for a persistence framework Helps organize your middle tier and handle typical J2EE plumbing problems. Reduces code and speeds up development Current Version is 1.1 Spring

Gpower Software Spring (continued) Do I have to use all components of Spring? Spring is a non-invasive and portable framework that allows you to introduce as much or as little as you want to your application. Promotes decoupling and reusability POJO Based Allows developers to focus more on reused business logic and less on plumbing problems. Reduces or alleviates code littering, ad hoc singletons, factories, service locators and multiple configuration files. Removes common code issues like leaking connections and more. Built in aspects such as transaction management Most business objects in Spring apps do not depend on the Spring framework.

Gpower Software Enables you to stop polluting code No more custom singleton objects –Beans are defined in a centralized configuration file No more custom factory object to build and/or locate other objects DAO simplification –Consistent CRUD –Data access templates –No more copy-paste try/catch/finally blocks –No more passing Connection objects between methods –No more leaked connections POJO Based Refactoring experience with Spring Spring Benefits

Gpower Software Spring Features

Gpower Software Spring middle-tier using a third-party web framework

Gpower Software Remoting usage scenario

Gpower Software EJBs - Wrapping existing POJOs

Gpower Software IoC container –Setter based and constructor based dependency injection –Portable across application servers –Promotes good use of OO practices such as programming to interfaces. –Beans managed by an IoC container are reusable and decoupled from business logic AOP –Spring uses Dynamic AOP Proxy objects to provide cross-cutting services –Reusable components –Aopalliance support today –Integrates with the IoC container –AspectJ support in Spring 1.1 Spring IoC + AOP

Gpower Software Inversion of Control/Dependency Injection –Beans do not depend on framework –Container injects the dependencies Spring lightweight container –Configure and manage beans IoC/Dependency Injection

Gpower Software Dependency injection –Beans define their dependencies through constructor arguments or properties –The container provides the injection at runtime “Don’t talk to strangers” Also known as the Hollywood principle – “don’t call me I will call you” Decouples object creators and locators from application logic Easy to maintain and reuse Testing is easier Inversion of Control

Gpower Software Inversion of Control Girl want a boy friend 三种方式: 1 青梅竹马; 2 亲友介绍; 3 父母包办

Gpower Software Inversion of Control 青梅竹马 public class Girl { void kiss(){ Boy boy = new Boy(); }

Gpower Software Inversion of Control 亲友介绍 public class Girl { void kiss(){ Boy boy = BoyFactory.createBoy(); }

Gpower Software Inversion of Control 父母包办 public class Girl { void kiss(Boy boy){ // kiss boy boy.kiss(); }

Gpower Software Inversion of Control

Gpower Software Inversion of Control (Type 0) public class Girl implements Servicable { private Kissable kissable; public Girl() { kissable = new Boy(); } public void kissYourKissable() { kissable.kiss(); }

Gpower Software Inversion of Control (Type 1) public class Girl implements Servicable { Kissable kissable; public void service(ServiceManager mgr) { kissable = (Kissable) mgr.lookup(“kissable”); } public void kissYourKissable() { kissable.kiss(); } …

Gpower Software Inversion of Control (Type 2) public class Girl { private Kissable kissable; public void setKissable(Kissable kissable) { this.kissable = kissable; } public void kissYourKissable() { kissable.kiss(); }

Gpower Software Inversion of Control (Type 3) public class Girl { private Kissable kissable; public Girl(Kissable kissable) { this.kissable = kissable; } public void kissYourKissable() { kissable.kiss(); } PicoContainer container = new DefaultPicoContainer(); container.registerComponentImplementation(Boy.class); container.registerComponentImplementation(Girl.class); Girl girl = (Girl) container.getComponentInstance(Girl.class); girl.kissYourKissable();

Gpower Software Spring Bean Definition The bean class is the actual implementation of the bean being described by the BeanFactory. Bean examples – DAO, DataSource, Transaction Manager, Persistence Managers, Service objects, etc Spring config contains implementation classes while your code should program to interfaces. Bean behaviors include: –Singleton or prototype –Autowiring –Initialization and destruction methods init-method destroy-method Beans can be configured to have property values set. –Can read simple values, collections, maps, references to other beans, etc.

Gpower Software Simple Spring Bean Example 10 public class OrderBean implements IOrderBean{ … public void setMinimumAmountToProcess(double d){ this. minimumAmountToProcess = d; } public void setOrderDAO(IOrderDAO odao){ this.orderDAO = odao; } }

Gpower Software Spring BeanFactory BeanFactory is core to the Spring framework –Lightweight container that loads bean definitions and manages your beans. –Configured declaratively using an XML file, or files, that determine how beans can be referenced and wired together. –Knows how to serve and manage a singleton or prototype defined bean –Responsible for lifecycle methods. –Injects dependencies into defined beans when served

Gpower Software XMLBeanFactory Beanfactory Implementation Beans Definition

Gpower Software Usage Example InputStream input = new FileInputStream("beans.xml"); BeanFactory factory = new XmlBeanFactory(input); ExampleBean eb = (ExampleBean)factory.getBean("exampleBean"); ExampleBeanTwo eb2 = (ExampleBeanTwo)factory.getBean("anotherExample"); throw NoSuchBeanDefinitionException ExampleBean eb = (ExampleBean)factory.getBean("exampleBean", ExampleBean.class); throw BeanNotOfRequiredTypeException

Gpower Software Bean creation Via constructor – Via static factory method – Via instance factory method –... –

Gpower Software Singleton or Non-singleton(prototype) <bean id="exampleBean" class="examples.ExampleBean" singleton="false"/> <bean name="yetAnotherExample" class="examples.ExampleBeanTwo" singleton="true"/>

Gpower Software Bean collaborators public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; public void setBeanOne(AnotherBean b) { beanOne = b; } public void setBeanTwo(YetAnotherBean b) { beanTwo = b; } }

Gpower Software Bean Properties public class ExampleBean { private String s; private int i; public void setStringProperty(String s) { this.s = s; } public void setIntegerProperty(int i) { this.i = i; } } Hi! 1

Gpower Software Property Editor Convert String to objects Implement java.beans.PropertyEditor –getValue()/setValue(),getAsText()/setAsText() Standard Java –Bool, Byte, Color, Double, Float, Font, Int, Long, Short, String Standard Spring –Class, File, Locale, Properties, StringArray, URL Custom Spring –CustomBoolean, CustomDate, CustomNumber,StringTrimmer

Gpower Software Standard Property Editor Examples – 7 – 0.25 – true – 0,255,0 java.awt.Color is initialized with RGB values

Gpower Software Custom Property Editor Date Example DateFormat fmt = new SimpleDateFormat("d/M/yyyy"); CustomDateEditor dateEditor = new CustomDateEditor(fmt, false); beanFactory.registerCustomEditor(java.util.Date.class, dateEditor); 19/2/2004 StringTrimmer Example StringTrimmerEditor trimmer = new StringTrimmerEditor(true); beanFactory.registerCustomEditor(java.lang.String.class, trimmer); hello

Gpower Software Java.util.Properties Property Example foo=1 bar=2 baz=

Gpower Software Java.util.List Set … List Example a list element

Gpower Software Bean Factory for IOC Type 3 1 public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public ExampleBean(AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) { this.beanOne = anotherBean; this.beanTwo = yetAnotherBean; this.i = i; }

Gpower Software Bean lifecycle Beans can be initialized by the factory before it first use public class ExampleBean { public void init() { // do some initialization work } <bean id="exampleBean" class="eg.ExampleBean" init-method="init"/>

Gpower Software Bean lifecycle Beans can be cleaned up when not used anymore public class ExampleBean { public void cleanup() { // do some destruction work } <bean id="exampleBean" class="eg.ExampleBean" destroy-method="cleanup"/>

Gpower Software PropertyPlaceholderConfigurer Merge properties from an external Properties file <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> ${jdbc.driverClassName} ${jdbc.url} ${jdbc.username} ${jdbc.password} jdbc.driverClassName=org.hsqldb.jdbcDriver jdbc.url=jdbc:hsqldb:hsql://production:9002 jdbc.username=sa jdbc.password=root Jdbc.properties

Gpower Software PropertyPlaceholderConfigurer Installing Configurer InputStream input = new FileInputStream("beans.xml"); XmlBeanFactory factory = new XmlBeanFactory(input); Properties props = new Properties(); props.load(new FileInputStream("jdbc.properties")); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.setProperties(props); cfg.postProcessBeanFactory(factory); DataSource ds = (DataSource)factory.getBean("dataSource");

Gpower Software Advanced Features Autowiring Dependency checking BeanWrapper InitializingBean/DisposableBean BeanFactoryAware/BeanNameAware

Gpower Software Spring ApplicationContext A Spring ApplicationContext allows you to get access to the objects that are configured in a BeanFactory in a framework manner. ApplicationContext extends BeanFactory –Adds services such as international messaging capabilities. –Add the ability to load file resources in a generic fashion. Several ways to configure a context: –XMLWebApplicationContext – Configuration for a web application. –ClassPathXMLApplicationContext – standalone XML application context –FileSystemXmlApplicationContext Allows you to avoid writing Service Locators

Gpower Software Configuring an XMLWebApplicationContext contextConfigLocation /WEB-INF/applicationContext.xml org.springframework.web.context.ContextLoaderListen er

Gpower Software Configuring an XMLWebApplicationContext contextConfigLocation /WEB-INF/applicationContext.xml context org.springframework.web.context.ContextLoaderServle t 1

Gpower Software AOP Complements OO programming Core business concerns vs. Crosscutting enterprise concerns Usages –Persistent –Transaction Management –Security –Logging –Debugging

Gpower Software AOP Concepts Aspect –Modularization of a concern Join point –Point during the execution of a program Advice –Action taken at a particular joinpoint Pointcut – Set of joinpoints when an advice should fire Introduction –Adding methiods of fields to an advised class. Target object –Object containing the joinpoint. Weaving –Assembling aspects to create an advised object.

Gpower Software AOP

Gpower Software Pointcut Set of joinpoints specifying when an advice should fire public interface Pointcut { ClassFilter getClassFilter(); MethodMatcher getMethodMatcher(); } public interface ClassFilter { boolean matches(Class clazz); } public interface MethodMatcher { boolean matches(Method m, Class targetClass); boolean matches(Method m, Class targetClass, Object[] args); boolean isRuntime(); } Restricts the pointcut to a given set of target classes Restricts the pointcut to a given set of target classes

Gpower Software Pointcut implementations Regexp <bean id="gettersAndSettersPointcut" class="org.springframework.aop.support.RegexpMethodPointcut">.*\.get.*.*\.set.*

Gpower Software Advices Action taken at a particular joinpoint public interface MethodInterceptor extends Interceptor { Object invoke(MethodInvocation invocation) throws Throwable; } Example public class DebugInterceptor implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println(">> " + invocation); // before Object rval = invocation.proceed(); System.out.println("<< Invocation returned"); // after return rval; } Spring implements an advice with an interceptor chain around the jointpoint Spring implements an advice with an interceptor chain around the jointpoint

Gpower Software Advice types Around advice –The previous advice Before advuce Throws advice After returning advice Introduction advice

Gpower Software Spring Advisors PointcutAdvisor= Pointcut + Advice. Each Built-in advice has a advisor Example <bean id="gettersAndSettersAdvisor" class="...aop.support.RegexpMethodPointcutAroundAdvisor">.*\.get.*.*\.set.*

Gpower Software ProxyFactory With a ProxyFactory you get advised objects –You can define pointcuts and advices that will be applied –It returns an interceptor as a proxy object –It uses Java Dynamic Proxy or CGLIB2 It can proxy interfaces or classes Creating AOP proxies programmatically ProxyFactory factory = new ProxyFactory(myBusinessInterfaceImpl); factory.addInterceptor(myMethodInterceptor); factory.addAdvisor(myAdvisor); MyBusinessInterface b = (MyBusinessInterface)factory.getProxy();

Gpower Software ProxyFactoryBean Used to get proxies for beans The bean to be proxied Tony 51 PersonImpl implements Person interface

Gpower Software ProxyFactoryBean The interceptors/advisors Something The proxy eg.Person myAdvisor debugInterceptor

Gpower Software ProxyFactoryBean Using the bean –Clients should get the person bean instead of personTarget –Can be accessed in the application context or programmatically Person person = (Person) factory.getBean("person");

Gpower Software ProxyFactoryBean If you need to proxy a class instead of an interafce –Set the property proxyTargetClass to true, instead of proxyInterfaces –Proxy will extend the target class Constructed by CGLIB true myAdvisor debugInterceptor

Gpower Software AutoProxy Automatic proxy creation –Just declare the targets –Selected beans will be automatically proxied No need to use a ProxyFactoryBean for each target bean

Gpower Software BeanNameAutoProxyCreator Select targets by bean name... <bean id="beanNameProxyCreator" class="...aop.framework.autoproxy.BeanNameAutoProxyCreator"> employee* myInterceptor

Gpower Software AdvisorAutoProxyCreator Automatic applies advisors in context to beans –Each dvisor has a pointcut and an advice –If a pointcut applies to a bean it will be intercepted by the advice Useful to apply the same advice consistently to many business objects Impossible to get an un-advised object

Gpower Software AdvisorAutoProxyCreator Example <bean id="getterDebugAdvisor" class="...aop.support.RegexpMethodPointcutAdvisor">.*\.get.* <bean id="autoProxyCreator" class="...aop.framework.autoproxy.AdvisorAutoProxyCreator"> true This advisor applies debugInterceptor to all get methods of any class This advisor applies debugInterceptor to all get methods of any class

Gpower Software AOP Weaving

Spring Framework Integration

Gpower Software Mail Creating message Simpl Message msg = new Simpl Message(); msg.setCc(new String[] msg.setBcc(new String[] msg.setSubject("my subject"); msg.setText("my text");

Gpower Software Mail->MessageSender Defining a message sender <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> smtp.mail.org joe abc123 Sending the message MailSender sender = (MailSender) ctx.getBean("mailSender"); sender.send(msg);

Gpower Software Scheduling Built in support for –Java 2 Timer Timer TimerTask –Quartz Schedulers JobDetails Triggers

Gpower Software Scheduling->Timer Task The task that we want to run public class MyTask extends TimerTask { public void run() { // do something } <bean id="myTask" class="...scheduling.timer.ScheduledTimerTask"> Java bean that wraps a scheduled java.util.TimerTask Java bean that wraps a scheduled java.util.TimerTask

Gpower Software Scheduling->TimerFactoryBean Creating the schedule <bean id="scheduler" class="...scheduling.timer.TimerFactoryBean"> The Timer starts at bean creation time Creates a java.util.Timer object

Gpower Software JDBC Make JDBC easier to use and less error prone Framework handles the creation and release resources Framework takes care of all exception handling

Gpower Software JDBC->JdbcTemplate Execute SQL Queries, update statements or stored procedure calls Iteration over ResultSets and extraction of returned parameter values Example DataSource ds = DataSourceUtils.getDataSourceFromJndi("MyDS"); JdbcTemplate jdbc = new JdbcTemplate(ds); jdbc.execute("drop table TEMP"); jdbc.update("update EMPLOYEE set FIRSTNME=? where LASTNAME=?", new String[] {"JOE", "LEE"});

Gpower Software JDBC->JdbcTemplate Queries, using convenience methods int maxAge = jdbc.queryForInt("select max(AGE) from EMPLOYEE"); String name = (String)jdbc.queryForObject( "select FIRSTNME from EMPLOYEE where LASTNAME='LEE'", String.class); List employees = jdbc.queryForList( "select EMPNO, FIRSTNME, LASTNAME from EMPLOYEE"); Returns an ArrayList (one entry for each row) of HashMaps (one entry for each column using the column name as the key) Returns an ArrayList (one entry for each row) of HashMaps (one entry for each column using the column name as the key)

Gpower Software JDBC->JdbcTemplate Queries, using callback method final List employees = new LinkedList(); jdbc.query("select EMPNO, FIRSTNME, LASTNAME from EMPLOYEE", new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { Employee e = new Employee(); e.setEmpNo(rs.getString(1)); e.setFirstName(rs.getString(2)); e.setLastName(rs.getString(3)); employees.add(e); } ); employees list will be populated with Employee objects

Gpower Software Hibernate Define a DataSource and an Hibernate SessionFactory... employee.hbm.xml....DB2Dialect

Gpower Software HibernateTemplate Create HibernateTemplate SessionFactory sessionFactory = (SessionFactory) ctx.getBean("sessionFactory"); HibernateTemplate hibernate = new HibernateTemplate(sessionFactory); Load and update Employee e = (Employee) hibernate.load(Employee.class, "000330"); e.setFirstName("BOB"); hibernate.update(e);

Gpower Software HibernateTemplate Queries, using convenience methods List employees = hibernate.find("from app.Employee"); List list = hibernate.find( "from app.Employee e where e.lastName=?", "LEE", Hibernate.STRING); List list = hibernate.find( "from app.Employee e where e.lastName=? and e.firstName=?", new String[] { "BOB", "LEE" }, new Type[] {Hibernate.STRING, Hibernate.STRING });

Gpower Software HibernateTemplate Queries, using callback methods List list = (List) hibernate.execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { List result = session.find("from app.Employee"); / / do some further stuff with the result list return result; } );

Gpower Software Transactions What is Distributed Transaction?  Transaction spans more than one resource  Transaction Manager as the coordinator Distributed Transaction Manager Local Transaction Manager Resource Manager Database Resource Manager Messaging Server

Gpower Software Spring Solution Use the same programming model for global or local transactions Transaction management can be –Programmatic –Declarative Four transaction managers available –DataSourceTransactionManager –HibernateTransactionManager –JdoTransactionManager –JtaTransactionManager

Gpower Software Examples Defining a JtaTransactionManager MyDS <bean id="transactionManager" class="...transaction.jta.JtaTransactionManager"/>

Gpower Software Examples Defining a HibernateTransactionManager <bean id="sessionFactory" class="...orm.hibernate.LocalSessionFactoryBean">... <bean id="transactionManager" class="...orm.hibernate.HibernateTransactionManager">

Gpower Software Declarative transactions No need of TransactionTemplate Implemented using Spring AOP Simliar to EJB CMT –You specify transaction behaviour (or lack of it) down to individual methods

Gpower Software <bean id=“mySessionFactory" class= “org.springframework.orm.hibernate.LocalSessionFactoryBean“> com/matrix/bo/Order.hbm.xml com/matrix/bo/OrderLineItem.hbm.xml net.sf.hibernate.dialect.DB2Dialect DB2ADMIN false /WEB-INF/proxool.xml spring Wiring your Persistence Layer

Gpower Software <bean id=“myTransactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager"> Wiring your Transaction Management

Gpower Software <bean id=“orderService" class="org.springframework.transaction. interceptor.TransactionProxyFactoryBean"> PROPAGATION_REQUIRED,readOnly,-OrderException PROPAGATION_REQUIRED,-OrderMinimumAmountException PROPAGATION_REQUIRED,-OrderException Wiring a Service Object

Gpower Software public class OrderServiceSpringImpl implements IOrderService { private IOrderDAO orderDAO; // service methods… public void setOrderDAO(IOrderDAO orderDAO) { this.orderDAO = orderDAO; } Defining a Target to Proxy

Gpower Software Wiring a Service Object (cont’)

Gpower Software Final Result

Gpower Software Spring has it’s own exception handling hierarchy for DAO logic. No more copy and pasting redundant exception logic! Exceptions from JDBC, or a supported ORM, are wrapped up into an appropriate, and consistent, DataAccessException and thrown. This allows you to decouple exceptions in your business logic. These exceptions are treated as unchecked exceptions that you can handle in your business tier if needed. No need to try/catch in your DAO. Define your own exception translation by subclassing classes such as SQLErrorCodeSQLExceptionTranslator Consistent Exception Handling

Gpower Software Traditional J2EE development with EJB will become more POJO based with EJB 3.0 Lightweight IoC container support will become more popular Future versions of J2EE will resemble frameworks like Spring and Hibernate for business logic and persistence logic respectively. –EJB 3.0 ~ (Spring + Hibernate) AOP is gaining momentum as an alternative to providing enterprise services Annotations will be helpful for applying AOP advice – J2SE 1.5 IoC + AOP is a great non-invasive combination. If you are considering EJB Spring will make an easier migration path Future Trends and Predictions

Gpower Software AOP Proxies

Gpower Software Spring+Hibernate Entity Enginee

Gpower Software Examples –ContentService 内容服务接口 继承 EntityService –ContentServiceImpl 内容服务接口实现 继承 EntityServiceImpl ,实现 ContentService 接口 –ContentDao 内容实体操作 继承 EntityDao –ContentDaoImpl 内容实体操作实现 继承 EntityDaoImpl ,实现 ContentDao 接 口 Entity Enginee

Gpower Software Examples com.gpower.services.content.dao.ContentDao hibernateInterceptor contentDaoTarget Entity Enginee

Gpower Software Examples PROPAGATION_SUPPORTS PROPAGATION_REQUIRED Entity Enginee