Java Spring Framework and Inversion of Control November 13, 2010 Donaby Henton.

Slides:



Advertisements
Similar presentations
5 Copyright © 2005, Oracle. All rights reserved. Accessing the Database with Servlets.
Advertisements

Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
Raptor Technical Details. Outline Workshop structured by Raptor workflow – Raptor Event model. – ICA log file parsing – ICA/MUA event storage – ICA event.
4. Object-Oriented Programming Procedural programming Structs and objects Object-oriented programming Concepts and terminology Related keywords.
Apache Struts Technology
Spring, Hibernate and Web Services 13 th September 2014.
Fast Track to ColdFusion 9. Getting Started with ColdFusion Understanding Dynamic Web Pages ColdFusion Benchmark Introducing the ColdFusion Language Introducing.
A Guide to Oracle9i1 Introduction To Forms Builder Chapter 5.
Object Relational Mapping. What does ORM do? Maps Object Model to Relational Model. Resolve impedance mismatch. Resolve mapping of scalar and non-scalar.
Modules, Hierarchy Charts, and Documentation
ASP.NET Programming with C# and SQL Server First Edition
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
C++ fundamentals.
The Spring Framework: A brief introduction to Inversion of Control James Brundege
Struts 2.0 an Overview ( )
UNIT-V The MVC architecture and Struts Framework.
Lecture 2 - Struts ENTERPRISE JAVA. 2 Contents  Servlet Deployment  Servlet Filters  Model View Controllers  Struts  Dependency Injection.
CVSQL 2 The Design. System Overview System Components CVSQL Server –Three network interfaces –Modular data source provider framework –Decoupled SQL parsing.
©Ian Sommerville 2004Software Engineering, 7th edition. Chapter 18 Slide 1 Software Reuse 2.
Dependency Injection and Model-View-Controller. Overview Inversion of Control Model-View-Controller.
Object Oriented Software Development
Design Patterns Discussion of pages: xi-11 Sections: Preface, Forward, Chapter
Java Frameworks Indy Java Users Group January 29, 2003.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
JSP Standard Tag Library
The Design Discipline.
CHAPTER 9 DATABASE MANAGEMENT © Prepared By: Razif Razali.
Java Beans.
UPortal Developers MIT August 2004 Persistence Strategy for uPortal 3 Mike DeSimone the r-smart group
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
Database Programming in Java Corresponds with Chapter 32, 33.
Designing For Testability. Incorporate design features that facilitate testing Include features to: –Support test automation at all levels (unit, integration,
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
Product Feeds. What is a Product? In marketing terms, a product is an item, service or idea that is for sale Examples are: A flight with set dates and.
Design Patterns Phil Smith 28 th November Design Patterns There are many ways to produce content via Servlets and JSPs Understanding the good, the.
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.
© 2006 IBM Corporation IBM WebSphere Portlet Factory Architecture.
9 Chapter Nine Compiled Web Server Programs. 9 Chapter Objectives Learn about Common Gateway Interface (CGI) Create CGI programs that generate dynamic.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Anti Orgla, Nortal AS Spring Framework
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Struts J2EE web application framework “ Model 2 ” Model View Controller Controller Servlet Key features XML metadata Struts taglib Simplified form validation.
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.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
Creative Commons Attribution- NonCommercial-ShareAlike 2.5 License Sakai Programmer's Café Sakai Montreal CRIM Workshop Introduction to Spring Framework,
Introduction CS 3358 Data Structures. What is Computer Science? Computer Science is the study of algorithms, including their  Formal and mathematical.
A Presentation By V AIBHAV S AHARAN Web-enHanced Information Management COMS E6125.
Object Oriented Software Development
Creating competitive advantage Copyright © 2003 Enterprise Java Beans Presenter: Wickramanayake HMKSK Version:0.1 Last Updated:
KEW Definitions Document Type The Document Type defines the routing definition and other properties for a set of documents. Each document is an instance.
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.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
© 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.
Preface IIntroduction Objectives I-2 Course Overview I-3 1Oracle Application Development Framework Objectives 1-2 J2EE Platform 1-3 Benefits of the J2EE.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
Advanced Object-oriented Design Patterns Creational Design Patterns.
McGraw-Hill/Irwin © 2008 The McGraw-Hill Companies, All Rights Reserved Chapter 7 Storing Organizational Information - Databases.
JDBC Java and Databases. SWC – JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
Google Code Libraries Dima Ionut Daniel. Contents What is Google Code? LDAPBeans Object-ldap-mapping Ldap-ODM Bug4j jOOR Rapa jongo Conclusion Bibliography.
Integrating and Extending Workflow 8 AA301 Carl Sykes Ed Heaney.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Design and Maintenance of Web Applications in J2EE
What’s changed in the Shibboleth 1.2 Origin
ITEC 3220A Using and Designing Database Systems
Introduction to Data Structure
Designing For Testability
Chapter 8 - Design Strategies
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Presentation transcript:

Java Spring Framework and Inversion of Control November 13, 2010 Donaby Henton

Software Goals Lower cost ▫Overall cost of software maintenance Code reuse Speed of deployment Reduce errors Flexible response for future needs

Things we do for those goals Code reviews Design patterns Other examples of best practice ▫Error trapping ▫Logging strategies Frameworks ▫J2EE ▫JSF, Struts….. ▫Spring

‘Behavioral’ Model of Coding Who ▫Classes/Objects What ▫Messages, information, data flow ▫Function calls ▫Code Use Connections ▫Messages flow via connections ▫The relation of one object to another ▫Configuration of code

‘Behavioral’ Model of Coding Object A Object B Object C Object A ‘uses’ B and C

‘Behavioral’ Model of Coding Object A Object B Object C Object A ‘uses’ B and C Composition Inheritance

Object Dependencies Objects use other objects ▫Creates relationships (composition, inheritance) These dependencies/relationships: ▫Determined at compile time ▫Determined at run time Pull methods for dependencies ▫Direct instantiation ▫Factory ▫Service Lookup

Object Dependencies Push methods for dependencies ▫Outside container “pushes” the relations at run time onto the object (Spring) Overall: ▫Need to wire up the relationships of objects ▫Objects combine to do work ▫Need to be aware of separating configuration of code from use of code

public void doDBAction() throws SQLException { Connection conn = null; Properties connectionProps = new Properties(); connectionProps.put("user", "user"); connectionProps.put("password", conn = DriverManager. getConnection("jdbc:mysql://localhost:3306/", connectionProps); //TODO: // use connection for some actions Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("SELECT * FROM ORDERS"); }

public void doDBAction() throws SQLException { Connection conn = null; Properties connectionProps = new Properties(); connectionProps.put("user", "user"); connectionProps.put("password", conn = DriverManager. getConnection("jdbc:mysql://localhost:3306/", connectionProps); //TODO: // use connection for some actions Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("SELECT * FROM ORDERS"); } Configuration

public void doDBAction() throws SQLException { Connection conn = null; Properties connectionProps = new Properties(); connectionProps.put("user", "user"); connectionProps.put("password", conn = DriverManager. getConnection("jdbc:mysql://localhost:3306/", connectionProps); //TODO: // use connection for some actions Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("SELECT * FROM ORDERS"); } Configuration Use

Configuration and Use In this example, these are in one class Difficult to change ▫Code change for each different database you want to connect to ▫Hard coded configuration ▫Properties files, JNDI will help  But still the user of the code has to have knowledge of the configuration of the code

public void doDBAction() throws SQLException { Connection conn = getDataSource().getConnection(); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("SELECT * FROM ORDERS"); }

Configuration and Use Now the class code does not configure ▫Assumes that configuration has been done ahead of time ▫Simply calls getDataSource.getConnection() Advantages of this assumption ▫The configuration could be done at run time  Test  Production But who will do the configuration?

Another Example Class External Web Service Database 1.Download orders via Web Service 2.Process and format for db write 3.Write to database 4.Handle transactions (e.g. what if db write fails?) As shown, the class must know all about the db and web service Monolithic code Not flexible

Another Example Using Composition Class External Web Service Database OrderService DBService

Another Example Using Composition Class External Web Service Database OrderService DBService Web service download object

Another Example Using Composition Class External Web Service Database OrderService DBService Tranformation Code

Another Example Using Composition Class External Web Service Database OrderService DBService Composition partitions the relations of components Order Service and DB Service are instance variables of the main class Database Object

Advantages Code is partitioned so changing one part doesn’t modify another ▫Different web service ▫Different web service libraries (Axis, CXF) ▫Different db methods Class code will see the services as an interface ▫Code to interface not implementation Class code does not configure the relations it just uses them

Dependency Injection Order Service and Db Service are dependencies for the class The class code only knows the services via their interface, no knowledge of internal details But how does the class get these services? Do we have to create a class for each combination of webservice and db we can think of?

Spring to the Rescue In our examples, we need a run time method of filling in the services We need an ‘outside referee’ that is concerned about configuration of code, NOT the use of code A factory design pattern that generalizes the creation of objects and their component parts Takes care of these relations

Spring to the Rescue Uses a configuration file in which you name concrete "beans" for the interfaces. "Wire" the application together by stating which beans are dependent on each other. Instantiate a Spring object called an ApplicationContext. This is a type of bean factory that will instantiate requested beans

Spring to the Rescue Configuration file is xml ▫Can also figure using code ▫Spring 2.5 and up provides for annotations The xml file is the home to configuration, but not code use Injects dependencies via ▫Get/set ▫Constructors ▫Factory method

Spring Example

Spring Example Config file <beans xmlns=" xmlns:xsi=" xsi:schemaLocation=" <bean class="com.dhenton9000.orders.persistence.PersistenceServiceImpl" id="dbInsertService"> <bean class="com.dhenton9000.orders.ws.WebServiceOrderImpl" id="wsOrdersService"> <bean id="setterDownloader" class="com.dhenton9000.orders.OrderDownloader"> <bean id="constructorDownloader" class="com.dhenton9000.orders.OrderDownloader">

Spring Terminology Bean tag refers to a class ▫Must specify full class name ▫Unique id (used for ref attribute) Properties are java bean properties ▫Setter must exist Property tag attribute can be ▫Ref: reference to another defined bean ▫Value: primitive, e.g. String or int 

Spring Terminology Container ▫Application Context This is a Static factory that uses xml config to ▫Create the beans ▫Apply the relationships (“wiring”) Can get at the container via static factory ▫ClassPathXmlApplicationContext

Spring Example Config file <beans xmlns=" xmlns:xsi=" xsi:schemaLocation=" <bean class="com.dhenton9000.orders.persistence.PersistenceServiceImpl" id="dbInsertService"> <bean class="com.dhenton9000.orders.ws.WebServiceOrderImpl" id="wsOrdersService"> <bean id="setterDownloader" class="com.dhenton9000.orders.OrderDownloader"> <bean id="constructorDownloader" class="com.dhenton9000.orders.OrderDownloader"> Ref refers to another bean The other bean

Spring Example Config file (con’t) root localhost 3306 businessdb

Spring Example main method

Spring Example (OrderDownloader) The services are interfaces

Spring Example (OrderDownloader) The services are interfaces This code only knows the interface

Spring Example (OrderDownloader) The services are interfaces This code only knows the interface Filled In By Spring

Spring Example (PeristenceServiceImpl) Injected via Spring

Spring Example (PeristenceServiceImpl) Injected via Spring <bean class="com.dhenton9000.orders.persistence.PersistenceServiceImpl" id="dbInsertService"> Spring bean

Spring Example Config file (con’t) root localhost 3306 businessdb

Spring fills in the blanks Class External Web Service Database OrderService DBService Also configures the DB Service via the data source

Advantages Final ‘wiring’ at runtime ▫Can be configured for test vs. production with a simple change in the dataSourceBean spring entry  Nothing else has to change ▫Creates segments where change in one service doesn’t effect the others ▫Divide and conquer:  Code for use  XML config for configuration

Advantages Consuming code knows only the interface ▫Swapping a new implementation is done via the xml file Helps foster ‘code to interface not implementation’ This allows for easy mock implementations when testing

Disadvantages Xml file can get complicated ▫Import capability can help Life cycle ▫Does Spring only create one copy of a bean on startup?  scope=singleton (create on startup)  scope=prototype (on each request) ▫Thread safety

Other Spring capabilities Application Contexts ▫classpath based ▫File based Beans can be created from static factories ▫Older code that uses factories Autowiring ▫Will scan classpath for matches ▫Removes need for xml config in simple cases

Spring So Far Separate configuration from code use Code to interfaces vs. implementations Allow for flexible runtime configuration Beans can be configured with beans that are then in turn configured allowing for quite complex relationships

Example: Spring and Design Patterns Using Spring to Support Design Patterns Spring is about Configuration Design patterns are often about the relationships of objects to one another A good match

EBay Inventory Attributes Mason Shoe Company ▫Sells items on Ebay ▫Alternative channel  Web sites  Catalogs  Phone orders Need to categorize our items ▫Must match EBay's designated categories ▫Map internal categories/data to EBay categories

EBay Inventory Attributes Take a POJO representing a row in a record set ▫Mason internal representation of attributes Map POJO attributes to CXF class used for web service submission Mapping ▫Dependent on type of shoe (men's, women's, boys…) ▫Each type will have different attribute lists ▫Some of those attributes are the same for each type (condition attribute is always “new”) ▫Some are different (men's sizes vs. women’s)

EBay Inventory Attributes Attributes are name value pairs EBay has mandatory attributes which they determine ▫Provides for some uniformity ▫Also mandate the name of the attribute Also allows for arbitrary attributes that sellers can add to improve communication with buyers In our case some internal items for our use

EBay Shoe Types Gender MaleChildBoysAdultMen'sFemaleChildGirlsAdultWomen'sUnisexChild Kid’s Unisex AdultUnisex

Women's Attributes Condition USSizeWomens MainColor WidthWomens Weight HeelHeight Brand Color Gender BaseStyle Material MasonClass ShoeStyle Style Type2 SubShoeStyle ParentColor DateAdded DateModified UserId Status Style2

Men's Attributes Condition USSizeMens MainColor WidthMens Weight Brand Color Gender BaseStyle Material MasonClass ShoeStyle SubShoeStyle ParentColor DateAdded DateModified UserId Status Type2 Style2 Style

Attribute Calculation Types Constants ▫Condition: “New in Box” Simple Look ups ▫Hashmap with mason internal as key, EBay value as result Simple Calculations ▫Width is formatted from internal mason representation Complex Short Circuit Logic Sieves Must also track the precise name of the attribute

Attribute Calculations For each POJO rObj in ResultSet create WS submission object wsObj select processor (men’s, women's, girls….) For each attr in processor’s attribute collection attr.configureAttribute(wsObj, rObj) End for End For

Spring Collection of Processors

Spring Processor

Sample Attribute Items

Design Pattern In Use (Strategy) An object controls which of a family of methods is called. Each method is in its' own class that extends a common base class. ▫ Spring sets up the collection of methods ▫Calculations don’t depend on each other so just loop through Spring allows mix match and swap ▫reuse

Attribute Processing Summary Spring allows the assembly of task hierarchy ▫AttributeProcessor Collection  Attribute processor  Individual attributes Defined at runtime Meta data all in one place Design patterns are often about configuration which can be done in Spring config files

Spring Summary Spring allows the assembly of task hierarchy ▫AttributeProcessor Collection  Attribute processor  Individual attributes Defined at runtime Meta data all in one place Design patterns are often about configuration which can be done in Spring config files

CSE (Comparison Shopping Engines) Regular information about our products Essentially our inventory updated daily ▫Image urls to our web sites ▫Prices ▫Other Data Used for competitive advantage, generating traffic to our websites

CSE (Comparison Shopping Engines) Sent by Mason to various providers ▫Amazon ▫Ebay ▫Google ▫Commission Junction Require Different Formats ▫CSV ▫Pipe delimited ▫XML

CSE (Comparison Shopping Engines) SQL1 SQL2 SQL3 Different divisions Different feed requirements Many queries are similar Output1 Output2 Output3 Different formats same data Same data, different formats Mix of data and formats

CSE SQL Input Using Ibatis Allows composition of sql by parts Mix and match ▫Try for as much reuse as possible Outputs POJOs for each row Bottom Line ▫Sql is messy ▫When done we have a POJO to represent a row

CSE Feed File Output Need to take a POJO and send it to multiple file formats For CSV, pipe delimited, tab delimited Use Spring and the strategy design pattern An object represents each column in the feeds objects can be reused for feeds that have common columns

CSE Feed File Output Create csvFileObj For each POJO rowObj fileRow = csvFileObj.createNextRow(); for each colObj in columnCollection v = colObj.getValue(rowObj) fileRow.write(v) end for

CSE Column Collection Every column class derives from an abstract class Derived classes must provide definition of getValue Provides for polymorphism This is a form of the strategy design pattern The loop has no knowledge of the different types Defers action to the individuals items

CSE Column Collection Using Spring the collection can be created at runtime Different column collections for different feeds ▫Can reuse an entire collection ▫Can reuse individual columns  A date timestamp generator for example So different sources can use the same column collection Same source can use different column collections to get at different feed output