Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Framework Concepts. Gpower Software 1 - 2 The enterprise challenge."— Presentation transcript:

1 Framework Concepts

2 Gpower Software 1 - 2 The enterprise challenge

3 Gpower Software 1 - 3 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

4 Gpower Software 1 - 4 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

5 Gpower Software 1 - 5 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

6 Gpower Software 1 - 6 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

7 Gpower Software 1 - 7 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

8 Gpower Software 1 - 8 - 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

9 Hibernate

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

11 Gpower Software 1 - 11 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

12 Gpower Software 1 - 12 “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

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

14 Gpower Software 1 - 14 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

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

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

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

18 Gpower Software 1 - 18 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

19 Gpower Software 1 - 19 Hibernate High Level Architecture

20 Gpower Software 1 - 20 Hibernate Full Cream Architecture

21 Gpower Software 1 - 21 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.

22 Gpower Software 1 - 22 Example Hibernate Mapping

23 Gpower Software 1 - 23 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; } … }

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

25 Gpower Software 1 - 25  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

26 Gpower Software 1 - 26  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

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

28 Gpower Software 1 - 28  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

29 Gpower Software 1 - 29  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

30 Gpower Software 1 - 30  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

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

32 Gpower Software 1 - 32  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

33 Gpower Software 1 - 33 Object Lifecycle

34 Gpower Software 1 - 34 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(); }

35 Gpower Software 1 - 35  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

36 Gpower Software 1 - 36  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

37 Gpower Software 1 - 37  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

38 Gpower Software 1 - 38 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

39 Gpower Software 1 - 39 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

40 Gpower Software 1 - 40 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

41 Gpower Software 1 - 41 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

42 Gpower Software 1 - 42 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

43 Gpower Software 1 - 43 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

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

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

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

47 Gpower Software 1 - 47 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

48 Gpower Software 1 - 48 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

49 Spring Framework Core

50 Gpower Software 1 - 50 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

51 Gpower Software 1 - 51 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.

52 Gpower Software 1 - 52 Proposed Web App Layering

53 Gpower Software 1 - 53 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

54 Gpower Software 1 - 54 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

55 Gpower Software 1 - 55 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

56 Gpower Software 1 - 56 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.

57 Gpower Software 1 - 57 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

58 Gpower Software 1 - 58 Spring Features

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

60 Gpower Software 1 - 60 Remoting usage scenario

61 Gpower Software 1 - 61 EJBs - Wrapping existing POJOs

62 Gpower Software 1 - 62 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

63 Gpower Software 1 - 63 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

64 Gpower Software 1 - 64 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

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

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

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

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

69 Gpower Software 1 - 69 Inversion of Control

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

71 Gpower Software 1 - 71 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(); } …

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

73 Gpower Software 1 - 73 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();

74 Gpower Software 1 - 74 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.

75 Gpower Software 1 - 75 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; } }

76 Gpower Software 1 - 76 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

77 Gpower Software 1 - 77 XMLBeanFactory Beanfactory Implementation Beans Definition

78 Gpower Software 1 - 78 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

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

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

81 Gpower Software 1 - 81 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; } }

82 Gpower Software 1 - 82 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

83 Gpower Software 1 - 83 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

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

85 Gpower Software 1 - 85 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

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

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

88 Gpower Software 1 - 88 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; }

89 Gpower Software 1 - 89 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"/>

90 Gpower Software 1 - 90 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"/>

91 Gpower Software 1 - 91 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

92 Gpower Software 1 - 92 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");

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

94 Gpower Software 1 - 94 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

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

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

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

98 Gpower Software 1 - 98 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.

99 Gpower Software 1 - 99 AOP

100 Gpower Software 1 - 100 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

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

102 Gpower Software 1 - 102 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

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

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

105 Gpower Software 1 - 105 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();

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

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

108 Gpower Software 1 - 108 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");

109 Gpower Software 1 - 109 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

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

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

112 Gpower Software 1 - 112 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

113 Gpower Software 1 - 113 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

114 Gpower Software 1 - 114 AOP Weaving

115 Spring Framework Integration

116 Gpower Software 1 - 116 Mail Creating message SimpleMailMessage msg = new SimpleMailMessage(); msg.setFrom("me@mail.org"); msg.setTo("you@mail.org"); msg.setCc(new String[] {"he@mail.org", "she@mail.org"}); msg.setBcc(new String[] {"us@mail.org", "them@mail.org"}); msg.setSubject("my subject"); msg.setText("my text");

117 Gpower Software 1 - 117 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);

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

119 Gpower Software 1 - 119 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"> 60000 1000 Java bean that wraps a scheduled java.util.TimerTask Java bean that wraps a scheduled java.util.TimerTask

120 Gpower Software 1 - 120 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

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

122 Gpower Software 1 - 122 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"});

123 Gpower Software 1 - 123 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)

124 Gpower Software 1 - 124 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

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

126 Gpower Software 1 - 126 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);

127 Gpower Software 1 - 127 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 });

128 Gpower Software 1 - 128 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; } );

129 Gpower Software 1 - 129 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

130 Gpower Software 1 - 130 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

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

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

133 Gpower Software 1 - 133 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

134 Gpower Software 1 - 134 <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

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

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

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

138 Gpower Software 1 - 138 Wiring a Service Object (cont’)

139 Gpower Software 1 - 139 Final Result

140 Gpower Software 1 - 140 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

141 Gpower Software 1 - 141 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 3.0 - Spring will make an easier migration path Future Trends and Predictions

142 Gpower Software 1 - 142 AOP Proxies

143 Gpower Software 1 - 143 Spring+Hibernate Entity Enginee

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

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

146 Gpower Software 1 - 146 Examples PROPAGATION_SUPPORTS PROPAGATION_REQUIRED Entity Enginee


Download ppt "Framework Concepts. Gpower Software 1 - 2 The enterprise challenge."

Similar presentations


Ads by Google