Sei sulla pagina 1di 44

13 Spring Framework

Usa Sammapun

Motivation
Business needs software system to run their business Flexibility Extensibility Reusability Java libraries provide only infrastructures to develop system Most business software has very similar high-level architecture Three-tier architecture
01418471 Software Design and Development .
2

Three-tier Architecture

Middle tier

image from http://en.wikipedia.org/wiki/Multitier_architecture

01418471 Software Design and Development .

Spring Framework
Framework : Libraries of classes Facilitating database connectivity, transaction management, faulttolerance, modular systems Promote exibility, extensibility, reusability Container : Object manager Create objects (beans) according to your specication Provide interface for accessing these objects These objects are normally composed to build a business solution
01418471 Software Design and Development .
4

JavaBeans
Classes conforming to a specic standard JavaBeans (java.beans.*) Intra-process In Java SE Enterprise JavaBeans (EJBs) (javax.ejb.*) Inter-process In Java EE
01418471 Software Design and Development .
5

Java SE and Java EE


Java Standard Edition (Java SE) Provides a basic programming platform Provides basic libraries (java.lang, java.io, java.beans, etc.) Java Enterprise Edition (Java EE) More libraries to facilitate software development in an enterprise Provides support for distributed and modular software Includes technologies : Enterprise JavaBeans, servlets, web services Libraries javax.ejb, javax.jms, javax.resources, etc.
01418471 Software Design and Development .
6

Spring Framework
Reduce dependencies among objects Promote using interface rather than implementation Inversion of Control (IoC) Lightweight Most classes can be independent of Spring Separation of responsibility Aspect-oriented programming
01418471 Software Design and Development .
7

Inversion of Control (IoC)


Control is inverted from where it used to be Example: User Interface: Before: console - application controls UI Now: GUI - (swing) framework controls UI MovieLister
01418471 Software Design and Development .

Source: http://martinfowler.com/articles/injection.html 8

MovieLister example (1)


class MovieLister... ... public Movie[] moviesDirectedBy(String arg) { List<Movie> allMovies = finder.findAll(); for (Iterator it = allMovies.iterator(); it.hasNext();) { Movie movie = (Movie) it.next(); if (!movie.getDirector().equals(arg)) it.remove(); } return (Movie[]) allMovies.toArray( new Movie[allMovies.size()]); } ...
01418471 Software Design and Development .

Source: http://martinfowler.com/articles/injection.html 9

MovieLister example (2)


public interface MovieFinder { List findAll(); } class MovieLister... private MovieFinder finder; public MovieLister() { finder = new CSVMovieFinder("movies1.txt"); } public Movie[] moviesDirectedBy(String arg) { List<Movie> allMovies = finder.findAll(); ...

01418471 Software Design and Development .

Source: http://martinfowler.com/articles/injection.html 10

MovieLister dependencies
MovieLister has a following dependency

If used by others with different a MovieLister implementation This dependency should not be hardwired within the program Depend only on the interface but still need to get to the object ?
01418471 Software Design and Development .

Source: http://martinfowler.com/articles/injection.html 11

MovieLister example
Or even if we push the object instantiation up to the caller / factory the caller / factory still depends on a MovieFinder implementation
class MovieLister ... private MovieFinder finder; public MovieLister(MovieFinder finder) { this.finder = finder; } ... class MovieEngine ... public MovieLister(MovieFinder finder) { MovieFinderfinder = new CSVMovieFinder("movies1.txt"); MovieLister lister = new MovieLister(finder)

01418471 Software Design and Development .

Source: http://martinfowler.com/articles/injection.html 12

Inversion of Control / Dependency Injection


Inversion of control (CI) Too generic term Dependency Injection (DI) Specically in the context of assembling dependencies between objects

01418471 Software Design and Development .

Source: http://martinfowler.com/articles/injection.html 13 http://dictionary.cambridge.org/

Dependency Injection
Use a separate object, an assembler, to create desired objects

01418471 Software Design and Development .

Source: http://martinfowler.com/articles/injection.html 14

Different forms of Dependency Injection


1. Constructor Injection 2. Setter Injection 3. Interface Injection

01418471 Software Design and Development .

Source: http://martinfowler.com/articles/injection.html 15

IoC/DI in Spring
Core : IoC Container Manage object within Spring Separate object creation and object execution Developers describe how to create objects (vis xml cong le) Without creating it yourself (no need for new keywords) To reduce dependency between components Thus, decoupling components
01418471 Software Design and Development .
16

Constructor Injection (1)


public class CSVMovieFinder implements MovieFinder { } private String filename; public CSVMovieFinder(String filename) { this.filename = filename; } @Override public List<Movie> findAll() { List<Movie> movies = new ArrayList<Movie>(); // code that read csv file and create Movie object from files data return movies; }

01418471 Software Design and Development .

17

Constructor Injection (2)


public class MovieLister { } private MovieFinder finder; public MovieLister(MovieFinder finder) { this.finder = finder; } public Movie[] moviesDirectedBy(String arg) { // code that return all movies directed by the given parameter ... }

01418471 Software Design and Development .

18

Constructor Injection (3)


import org.springframework.beans.factory.xml.*; import org.springframework.core.io.*; public class MovieTester { } public static void main(String[] args) throws Exception { } XmlBeanFactory bf = new XmlBeanFactory( new ClassPathResource("movie-con-inject.xml")); MovieLister lister = (MovieLister) bf.getBean("lister"); Movie[] ronHoward = lister.moviesDirectedBy("Ron Howard"); for (Movie movieRH : ronHoward) { System.out.println(movieRH.getName()); }

01418471 Software Design and Development .

19

Constructor Injection (4)


<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="csv-finder" class="springlesson.movie.CSVMovieFinder"> <constructor-arg value="movies1.txt"/> </bean> <bean id="lister" class="springlesson.movie.MovieLister"> <constructor-arg ref="csv-finder"/> </bean> </beans>

01418471 Software Design and Development .

20

Constructor Injection (4)


<?xml version="1.0" encoding="UTF-8"?> <beans

xml document standard

xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="csv-finder" class="springlesson.movie.CSVMovieFinder"> <constructor-arg value="movies1.txt"/> </bean> <bean id="lister" class="springlesson.movie.MovieLister"> <constructor-arg ref="csv-finder"/> </bean> </beans>

01418471 Software Design and Development .

20

Constructor Injection (4)


<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="csv-finder" class="springlesson.movie.CSVMovieFinder"> <constructor-arg value="movies1.txt"/> </bean> <bean id="lister" class="springlesson.movie.MovieLister"> <constructor-arg ref="csv-finder"/> </bean> </beans>

01418471 Software Design and Development .

20

Constructor Injection (4)


<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="csv-finder" class="springlesson.movie.CSVMovieFinder"> <constructor-arg value="movies1.txt"/> </bean> <bean id="lister" class="springlesson.movie.MovieLister"> <constructor-arg ref="csv-finder"/> </bean> </beans>

schema for Spring XML

01418471 Software Design and Development .

20

Constructor Injection (4)


<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="csv-finder" class="springlesson.movie.CSVMovieFinder"> <constructor-arg value="movies1.txt"/> </bean> <bean id="lister" class="springlesson.movie.MovieLister"> <constructor-arg ref="csv-finder"/> </bean> </beans>

01418471 Software Design and Development .

20

Constructor Injection (4)


<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="csv-finder" class="springlesson.movie.CSVMovieFinder"> <constructor-arg value="movies1.txt"/> </bean> <bean id="lister" class="springlesson.movie.MovieLister"> <constructor-arg ref="csv-finder"/> </bean> </beans>

01418471 Software Design and Development .

bean creation specication

20

Setter Injection (1)


public class CSVMovieFinder implements MovieFinder { } private String filename; public void setFilename(String filename) { this.filename = filename; } @Override public List<Movie> findAll() { List<Movie> movies = new ArrayList<Movie>(); // code that read csv file and create Movie object from files data return movies; }

01418471 Software Design and Development .

21

Setter Injection (2)


public class MovieLister { } private MovieFinder finder; public void setFinder(MovieFinder finder) { this.finder = finder; } public Movie[] moviesDirectedBy(String arg) { // code that return all movies directed by the given parameter ... }

01418471 Software Design and Development .

22

Setter Injection (3)


<bean id="csv-finder" class="springlesson.movie.CSVMovieFinder"> <property name="filename" value="movies1.txt"/> </bean> <bean id="lister" class="springlesson.movie.MovieLister"> <property name="finder" value="csv-finder"/> </bean>

01418471 Software Design and Development .

23

Spring Framework

Image from http://static.springsource.org/spring/docs/2.5.x/reference/introduction.html


01418471 Software Design and Development .
24

Data Access Object (DAO)


Data Access Object (DAO) JDBC abstraction layer Hide complexity of JDBC programming Object-Relational Mapping (ORM) Integration with ORM APIs such as Hibernate Aspect-Oriented Programming (AOP) Provides support for aspect-oriented programming
01418471 Software Design and Development .
25

Bean Factory
Very generic implementation of the Factory design pattern Used to create any beans by giving its name Core of IoC and dependency injection (DI) Similar concepts Application Context Just like bean factory but has more features
01418471 Software Design and Development .
26

Setting properties (1)


<bean id="fileReader" class="broker.FileProductReader"> <property name="productFile" value="financial-product-with-commod.csv"/> <property name="holdingFile" value="product-holding.csv"/> <property name="productTypeMap"> <props> <prop key="FX">broker.Currency</prop> <prop key="STOCK">broker.Stock</prop> <prop key="COMMOD">broker.Commodity</prop> </props> </property> </bean>

01418471 Software Design and Development .

27

Setting properties (2)


public class FileProductReader implements ProductReader { private String productFile; private String holdingFile; private Properties productTypeMap; public void setProductFile(String productFile) { this.productFile = productFile; } public void setHoldingFile(String holdingFile) { this.holdingFile = holdingFile; } public void setProductTypeMap(Properties map) { this.productTypeMap = map; }

01418471 Software Design and Development .

28

Setting properties (3)


@Override public HashMap<String, FinancialProduct> getProducts() { ... for (String line = in.readLine(); line != null; line = in.readLine()) { String[] data = line.split(","); String type = data[4]; String className = productTypeMap.getProperty(type); } FinancialProduct prod = (FinancialProduct) Class.forName(className).newInstance(); prod.setSymbol(data[0]); prod.setName(data[1]); prod.setDescription(data[2]); prod.setPrice(Double.parseDouble(data[3])); products.put(prod.getSymbol(), prod); } ...

01418471 Software Design and Development .

29

RMI (Remote Method Invocation)


The same concept as RPC (remote procedure calls) Class can use an object that locates at another location Java provides java.rmi package Good : More convenient than sending objects via Socket Bad : Need to understand rmi concept and programming patterns Spring provides an easier way to use rmi than naive JavaSE implementation

01418471 Software Design and Development .

30

RMI : Server side (1)


public class BrokerServer { public static void main(String[] args) throws Exception { ApplicationContext bf = new ClassPathXmlApplicationContext("broker-server-config.xml"); } System.out.println("Server is ready.");

01418471 Software Design and Development .

31

RMI : Server side (2)


public class BrokerManagerImp implements BrokerManager { private ProductReader prodReader; private HashMap<String,FinancialProduct> products; private double numTransaction; public void setUp() { products = prodReader.getProducts(); } public void setProdReader(ProductReader prodReader) { this.prodReader = prodReader; }

01418471 Software Design and Development .

32

RMI : Server side (3)


@Override public double sell(String symbol, double quantity) { numTransaction++; FinancialProduct fProd = products.get(symbol); return fProd.sell(quantity); } @Override public double buy(String symbol, double quantity) { numTransaction++; FinancialProduct fProd = products.get(symbol); return fProd.buy(quantity); } @Override public double getNumTransaction() { return numTransaction; } 33

01418471 Software Design and Development .

RMI : Server side (4)


public interface BrokerManager { double sell(String symbol, double quantity); double buy(String symbol, double quantity); double getNumTransaction(); }

01418471 Software Design and Development .

34

RMI : Server side (5)


<bean id="manager" class="server.BrokerManagerImp" init-method="setUp"> <property name="prodReader" ref="fileReader"/> </bean> <bean id="fileReader" class="server.FileProductReader"> <property name="productFile" value="financial-product-with-commod.csv"/> <property name="holdingFile" value="product-holding.csv"/> <property name="productTypeMap"> <props> <prop key="FX">server.Currency</prop> <prop key="STOCK">server.Stock</prop> <prop key="COMMOD">server.Commodity</prop> </props> </property> </bean>

01418471 Software Design and Development .

35

RMI : Server side (6) : RMI


<bean class="org.springframework.remoting.rmi.RmiServiceExporter"> <property name="service" ref="manager"/> <property name="serviceName" value="BrokerService"/> <property name="serviceInterface" value="server.BrokerManager"/> <property name="registryPort" value="1099"/> </bean>

01418471 Software Design and Development .

36

RMI : Client side (1)


public class BrokerClientConsole { BrokerManager manager; public BrokerClientConsole() { XmlBeanFactory bf = new XmlBeanFactory( new ClassPathResource("broker-client-config.xml")); manager = (BrokerManager) bf.getBean("brokerservice"); } public void run() { Scanner scanner = new Scanner(System.in); while (true) { System.out.println("---------------------------------"); System.out.println(" Enter action : "); ......

01418471 Software Design and Development .

37

RMI : Client side (2)


...... double amount = 0; if (action.equalsIgnoreCase("S")) amount = manager.sell(symbol, quantity); else if (action.equalsIgnoreCase("B")) amount = manager.buy(symbol, quantity); ......

} }

01418471 Software Design and Development .

38

RMI : Client side (3) : RMI


<bean id="brokerservice" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"> <property name="serviceUrl" value="rmi://localhost/BrokerService" /> <property name="serviceInterface" value="client.BrokerManager" /> </bean>

01418471 Software Design and Development .

39

Potrebbero piacerti anche