Presentation is loading. Please wait.

Presentation is loading. Please wait.

Spring Framework.

Similar presentations


Presentation on theme: "Spring Framework."— Presentation transcript:

1 Spring Framework

2 Spring Introduction

3 The Spring Framework Mission Statement
J2EE should be easier to use It's best to program to interfaces, rather than classes. Spring reduces the complexity cost of using interfaces to zero. JavaBeans offer a great way of configuring applications. OO design is more important than any implementation technology, such as J2EE. Checked exceptions are overused in Java. A framework shouldn't force you to catch exceptions you're unlikely to be able to recover from. Testability is essential, and a framework such as Spring should help make your code easier to test. Spring should be a pleasure to use Your application code should not depend on Spring APIs Spring should not compete with good existing solutions, but should foster integration. (For example, JDO and Hibernate are great O/R mapping solutions. We don't need to develop another one.

4 Sun's Best Practices... In 1998 Distributed Computing was the big buzz-word Sun made EJBs to compete with technologies like CORBA The specification was intrusive And the result is Sun's famous PetStore application with quite difficult architecture

5 EJB Issues If the Sun “Pet Store” is the best, we’re in trouble
Intrusive – Noisy Must be an EJBObject Must run within the container Rapid iterative code/debug/test cycles difficult If the Sun “Pet Store” is the best, we’re in trouble Too many different patterns Performs poorly Reliance on Entity Beans Too many different files needed to do simple things Dated Dynamic Proxies can replace the need for most container generated source code The emergence of Web Services has replaced RMI Most teams have accepted SLSB while rejecting Entity Beans Low developer productivity

6 What are Lightweight Frameworks?
Non-intrusive No container requirements Simplify Application Development Remove re-occurring pattern code Productivity friendly Unit test friendly Very Pluggable Usually Open Source Examples: Spring, Pico, Hivemind Hibernate, IBatis, Castor WebWork Quartz Sitemesh

7 What is Spring? At it’s core, Spring provides:
An Inversion of Control Container Also known as Dependency Injection (Fowler’s term) An AOP Framework Spring provides a proxy-based AOP framework You can alternatively integrate with AspectJ or AspectWerkz A Service Abstraction Layer Consistent integration with various standard and 3rd party APIs These together enable you to write powerful, scalable applications using POJOs.

8 Spring Overview from springframework.org
Note: Spring distribution comes as one big jar file and alternatively as a series of smaller jars broken out along the above lines (so you can include only what you need)

9 Spring introduction Spring allows us to decouple our software layers by injecting a component’s dependencies at runtime rather than having them declared at compile time via importing and instantiating classes. It uses the JavaBeans framework to wire up dependencies. Spring provides integration for J2EE services such as EJB, JDBC, JNDI, JMS, JTA. It also integrates several popular ORM toolkits such as Hibernate and JDO and assorted other services as well. Cosmo provides a similar Spring-based integration with JCR. One of the highly touted features is declarative transactions, which allows the developer to write transaction-unaware code and configure transactions in Spring config files. Spring is built on the principle of unchecked exception handling. This also reduces code dependencies between layers. Spring provides a granular exception hierarchy for data access operations and maps JDBC, EJB, and ORM exceptions to Spring exceptions so that applications can get better information about the error condition. With highly decoupled software layers and programming to interfaces, each layer is easier to test. Mock objects is a testing pattern that is very useful in this regard.

10 Spring introduction Layer Architecture Clear Architecture
Easy to track down bugs and implement new features Impact can’t be overstated Wiring of components “collaborators” very easy to do and understand Spring MVC Layer Complete flexibility in Views (JSTL, PDF, MS Excel…) Facilitates Team Development Vertical (Parallel development – Use Cases) Horizontal (leverage technical expertise)

11 Advantages of Spring Architecture
Lifecycle – responsible for managing all your app components, particularly those in the middle tier container sees components through well-defined lifecycle: initialization(), destruction() Dependencies - Spring handles injecting dependent components without a component knowing where they came from (IoC) Config information - Spring provides one consistent way of configuring everything, separate configuration from application logic, varying configuration. In J2EE (e.g. EJB) it is easy to become dependent on container and deployment environment, proliferation of pointless classes (locators/delegates); Spring eliminates them. Cross-cutting behaivior (resource management is cross-cutting concern, easy to copy-and-paste everywhere) Portable (can use server-side in web/ejb app, client-side in swing app, business logic is completely portable)

12 Spring - Solutions Solutions address major J2EE problem areas:
Web application development (MVC) Enterprise Java Beans (EJB, JNDI) Database access (JDBC, iBatis, ORM) Transaction management (JTA, Hibernate, JDBC) Remote access (Web Services, RMI) Each solution builds on the core architecture Solutions foster integration, they do not re-invent the wheel

13 Before Spring After Spring
Proprietary, buggy configuration code Proliferation of Singletons, Service Locators (glue code) Copy-and-paste code (boilerplate, not relevant to business object), ugly exception handling Tied by invasive infrastructure (EJB/JNDI), application server Testing? For some components only end-to-end tests are realistic. One elegant way of configuring everything Dependency Injection – components are handed only what they need Cohesive, reusable business logic (clear separation of concerns) No dependency on infrastructure APIs or container Easy, comprehensive testing Sad Euphoric!

14 Spring MVC Source: June 10, 2005

15 Spring Application Context

16 Spring Application Context
Container which controls components ApplicationContext ctx = new FileSystemXmlApplicationContext("config.xml"); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml", "applicationContext-part2.xml"} ); W którymś miejscu aplikacji należy stworzyć kontekst aplikacji (kontener), który przejmie na siebie zarządzanie wszystkimi komponentami i zapewni im wymagane usługi (np. transakcje)

17 How to configure <?xml version="1.0" encoding="UTF-8"?>
<beans> <bean id= "component1" class= "package.Class1"> ... </bean> <bean name= "component2,alias1" class= "package.Class2"> </beans>

18 Configuring Components
Singleton/prototype (non-singleton) Setter/constructor dependency injection Autowire: no, byName, byType, constructor, autodetect Dependency-check: none, simple, object, all Init-method, destroy-method Lazy-init

19 Examples of configuration
public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public ExampleBean(AnotherBean beanOne) { this.beanOne = beanOne; } public void setBeanTwo(YetAnotherBean beanTwo) { this.beanTwo = beanTwo; } public void setIntegerProperty(int i) { this.i = i; } } <bean id="exampleBean" class="examples.ExampleBean" singleton="false"> <constructor-arg><ref bean="anotherExampleBean"/></constructor-arg> <property name="beanTwo"><ref local="yetAnotherBean"/></property> <property name="integerProperty"><value>1</value></property> </bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean” lazy-load=”true”/>

20 Inversion of Control

21 IoC Types Three basic types Type I Type II Type III
Interface Injection Your service or component implement a specific interface Much like EJBs Type II Method Injection Dependent objects are provided to the object by methods Based on JavaBeans constructs Ordering of method calls may not be achievable Type III Constructor Injection Dependent objects are provided to the object by constructors Large constructor argument lists

22 Basic JavaBean Pattern
Include a “getter” and “setter” method for each field class MyBean { private int counter; public int getCounter() { return counter; } public void setCounter(int counter) { this.counter = counter; } }

23 BeanFactories XML-based component deployment
Create object graphs and configure data Inversion of Control (Dependency Injection) The bean’s fully- qualified classname The bean’s ID <beans> <bean id=“widgetService” class=“com.zabada.base.WidgetService”> <property name=“poolSize”> <!—-property value here--> </property> </bean> </beans> Maps to a setPoolSize() call

24 Property Values for BeanFactories (continued)
The real magic comes in when you can set a property on a bean that refers to another bean in the configuration: <bean name=“widgetService” class=“com.zabada.base.WidgetServiceImpl”> <property name=“widgetDAO”> <ref bean=“myWidgetDAO”/> </property> </bean> calls setWidgetDAO(myWidgetDAO) where myWidgetDAO is another bean defined in the configuration This is the basic concept of Inversion of Control

25 Inversion of Control (IoC)
Rather than locating needed resources, application components provide setters through which resources are passed in during initialization Example: our DataAccessObject class provides a setDataSource() method, which is called from the Init class. In Spring Framework, this pattern is used extensively, and initialization is usually done through configuration file rather than application code.

26 Inversion of control Design pattern (Wzorzec projektowy) on top of which components are functioning in a container Components and classes supply certain functionality Containers create concrete instances of the components, filling their fields and maintaining their life-cycle Komponenty - nie należy wprowadzać zmian w ich kodzie źródłowym, powinny być konfigurowalne.

27 IoC - Sample We would like that MovieLister knew only about the interface, but how to create a working instance of MovieListener?

28 IoC - Sample public interface MovieFinder { List findAll(); }
class MovieLister... private MovieFinder finder; public MovieLister() { finder = new ColonDelimitedMovieFinder("movies1.txt"); } public Movie[ ] moviesDirectedBy(String arg) { List 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()]);

29 IoC - Sample

30 IoC - Sample class MovieLister... private MovieFinder finder;
public void setFinder(MovieFinder finder) { this.finder = finder; } class ColonMovieFinder... public void setFilename(String filename) { this.filename = filename;

31 IoC - Sample <beans>
<bean id="MovieLister" class="package.MovieLister"> <property name="finder"> <ref local="MovieFinder"/> </property> </bean> <bean id="MovieFinder" class="package.ColonMovieFinder"> <property name="filename"> <value>movies1.txt</value> </beans> public void testSpringContainer() { ApplicationContext ctx = new FileSystemXmlApplicationContext("config.xml"); MovieLister movieLister = (MovieLister) ctx.getBean("MovieLister"); Movie[ ] movies = movieLister.moviesDirectedBy("Sergio Leone"); }

32 Testability Implications and Refactoring

33 Importance of Loose Coupling with Spring
Adopting Spring is easier when architecture is loosely coupled Consistent transaction boundaries/entry points Spring adds more value with testing. Control injection No boundaries makes things a lot harder

34 Application Framework
High Level of Coupling Products Application Framework External Providers Data Access Very tight coupling across the entire application Interaction complexity is extremely high. Unit testing is hard to do, if not impossible. Impossible out of the container. One code change could potentially affect multiple areas of the code. The application is very brittle, and development takes much longer than in a layered architecture. More than a few developers and they will start stepping on each other.

35 Structuring a system into layers has a number of important benefits:
Spring Interceptors (AOP)/Interface Biz Services Very Loose Coupling – layers talk only to those directly above and below them Interface Products Application Framework Interface Spring Interceptors (AOP)/Interface Workflow External Providers Spring Interceptors (AOP)/Interface Data Access Structuring a system into layers has a number of important benefits: Understand a single layer as a coherent whole without knowing about the other layers Substitute layers with alternative implementation of the same basic services Significantly reduce complexity of code interactions Simplify unit testing – test each layer separately Much more rapid development

36 Looking at a Layer – Façade Pattern
After Refactor Before Refactor Application Logic Spring Audit Interceptors Application Logic External Provider Layer Service1 Service2 Service3 Service4 Service1 Service2 Service3 Service4 Refactor Enabled Application Logic Mock External Provider Layer Mock Mock Mock Mock

37 Loose Coupling w/ Business Interface Pattern
Having code in EJBs makes unit testing extremely difficult since everything has to be run in an application server. Moved all business logic out of Stateless and Message Driven EJBs into plain old java objects (POJO). EJB is solely used for transaction and thread management. This makes testing the business logic much easier since we can write all of our tests out of the container.

38 Practical Refactoring to Spring Framework
Start with bean wiring (Inversion of Control) Beans that are Spring wired are very easy to apply AOP The more injection, the more you can mock Spring can be used for test data retrieval One of Spring’s goal is to make existing technologies easier. Spring is not Hibernate, Hibernate is not Spring. Ability to change behavior without changing code is an important point and benefit of Spring (i.e. datasource configuration, transaction manager, our entire web service layer) Re-factor into layers first, then add Spring and Hibernate Layering also creates boundaries Tradeoff between run-time flexibility and run-time configuration validation Changing one property in the database allows us to change entire layers

39 Practical Refactoring to Spring Framework
Entire code base can be tested out of container except for EJB  EJB calls Code is much more maintainable Re-factoring is much easier with baseline of unit tests in place Inversion of control helps immensely in mocking out external service layer calls Testing becomes much easier meaning more likely to happen Teams able to scale with less code contention

40 Spring MVC

41 Model-View-Controller

42 MVC for Web Event – HTTP request from client
Controller – Custom Spring Controller Class View – JSP script Model – Java Beans Model is passed to the server-side View which is returned to the client

43 About Spring MVC Comes with the Spring distribution
Well integrated with the rest of Spring Very extensible

44 Quick Spring Refresher
Write dependencies as setters Link up dependencies in XML file The Spring Framework will instantiate and call setters to hook it all together <bean id=“dateFormat" class=“java.text.SimpleDateFormat"> <constructor-arg value=“dd MMM yyyy”/> </bean> <bean id=“myBean" class=“com.platinumSolutions.stuff.SomeClass"> <property name=“dateFormat” ref=“dateFormat”/>

45 Spring MVC Basics All calls go through the DispatcherServlet
Config file is *-servlet.xml by default MVC: instances of the following: M – Model: a Java Map V – View: org.springframework.web.servlet.View C – Controller: org.springframework.web.servlet.mvc.Controller

46 Spring MVC Configuration
The configurable pieces of Spring MVC: org.springframework.web.servlet.HandlerMapping what controller to call given a URL org.springframework.web.servlet.ViewResolver how to determine what view to show org.springframework.web.servlet.LocaleResolver how to determine internationalization org.springframework.web.multipart.MultipartResolver how to handle files org.springframework.web.servlet.HandlerExceptionResolver what to do with an Exception org.springframework.web.servlet.ThemeResolver where to get css, images, pages from org.springframework.web.servlet.HandlerAdapter wrapper around the controller (or servlet)

47 Spring MVC A (simplified) sequence diagram:

48 Handling the request with a HandlerMapping
Given a URL, figures out what Controller to use: SimpleUrlHandlerMapping define mappings with Map or Properties BeanNameUrlHandlerMapping bean names have same names as URL CommonsPathMapHandlerMapping use Commons Attributes to determine mapping

49 Selecting a view with a ViewResolver
Given a view name, figures out what View to use: BeanNameViewResolver Spring beans happen to have the same name UrlBasedViewResolver view name maps to a URL (like a filename) ResourceBundleViewResolver look up the View in a resource file XmlViewResolver uses XML file to determine mappings FreeMarkerViewResolver UrlResourceViewResolver preset for FreeMarkerView InternalResourceViewResolver UrlResourceViewResolver preset for InternalResourceView VelocityViewResolver UrlResourceViewResolver preset for VelocityView

50 Different Views Plenty of Views are packaged with Spring MVC: JstlView
map to a JSP page RedirectView Perform an HTTP Redirect TilesView, TilesJstlView integration with tiles VelocityLayoutView, VelocityToolboxView, VelocityView Integration with the Velocity templating tool FreeMarkerView use the FreeMarker templating tool JasperReportsView, JasperReportsMultiFormatView, JasperReportsMultiFormatView, JasperReportsPdfView, JasperReportsXlsView Support for Jasper Reports

51 Localization The locale may be chosen manually, selected by the browser, or fixed AcceptHeaderLocaleResolver - use the HTTP accept-header to determine the locale CookieLocalResolver - set the chosen locale in a cookie FixedLocaleResolver - always use a fixed locale (set in the config file) SessionLocaleResolver - store the chosen locale in the session The spring tag <spring:message> picks the resource Define the bean messageSource with a MessageSource to set the resources: StaticMessageSource - set messages within the object ResourceMessageBundleMessageSource - load messages from .properties files ReloadableResourceMessageBundleMessageSource - same as above, but reloads! (others)

52 Other Provided Controllers
Spring MVC includes lots of Controllers to extend from: AbstractController basic controller, knows about caching, turning on/off get/set/post/head ParameterizableViewController always go to the same view UrlFileNameViewController parses the URL to return a view ( -> foo) SimpleFormController for form handling, hooks for attaching commands, validator AbstractWizardFormController easy wizard controller ServletWrappingController delegates to a servlet

53 Handling Forms Set the Command (just a bean)
Set a Validator if needed (extend org.springframework.validation.Validator) Set destination views (form, success, failure, error) By default, uses GET/POST to determine whether it needs to load the form or process it

54 Wizards Similar to Forms, but needs to validate along the way
One Controller handles multiple pages Process at the end Cancel anywhere along the line

55 Interceptor Some HandlerMappings allow you to call an interceptor before the controller Useful for checking for session timeout, adding things to the request/session Kind of like AOP, but for Controllers

56 ExceptionHandler Spring philosophy says that most Exceptions should not be caught ExceptionHandler determines what to do if an Exception is thrown through the Controller

57 Themes Totally change look and feel of your application in one step!
Lets you point to different css, jsp, images

58 Conclusion Spring MVC offers Lots of flexibility
Straightforward design Leverages Spring injection

59 Spring DAO

60 Data Access Object (DAO)
Used to hide persistence implementation details from Model elements

61 DAO Sequence

62 Spring Solutions: DAO JDBC
DAO Pattern – abstracts particular persistence mechanism Offers much simpler programming model than raw JDBC No more try/catch/finally blocks No more leaked connections Meaningful exception hierarchy Spring auto-detects database and knows what ORA-917 means No more vendor code lookups More portable code Stored procedure support Ideal for the places Hibernate doesn’t go

63 Spring Solutions: DAO ORM
Manages Hibernate sessions No more ThreadLocal sessions Sessions are managed by Spring declarative transaction management HibernateTemplate makes common operations easy Consistent exception hierarchy Runtime exceptions (Gavin King now believes Hibernate should have opted for unchecked exceptions) Mixed use of Hibernate and JDBC within the same transaction JDO support

64 JDBC Template DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver"); dataSource.setUsername("scott"); dataSource.setPassword("tiger"); JdbcTemplate jt = new JdbcTemplate(dataSource); jt.execute("create table mytable (id integer, name varchar(100))"); int count = jt.queryForInt("select count(*) from mytable"); String name = (String) jt.queryForObject("select name from mytable", String.class); List rows = jt.queryForList("select * from mytable"); jt.update("update mytable set name = ? where id = ?", new Object[ ] {name, new Integer(id)}); dataSource najlepiej wziąć prosto z Application Contexta Nie ma potrzeby przechwytywania wyjątków, pisania mrowią konstrukcji try...catch...finally – JT się już tym zajmie. W Springu jest też funkcjonalność do wywoływania procedur wbudowanych w bazy danych, a także do prymitywnego mapowania obiekt<->encja.

65 Hibernate Template HibernateTemplate ht = new HibernateTemplate(sessionFactory); final String name = "Nivea soap"; Product product = (Product)ht.execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { return session.find( "from com.mycompany.Product product where product.name=?", name, Hibernate.STRING).get(0); } );

66 Refactoring for Spring DAO
Lazy loading – a must have (session per transaction) Collections Class Level Notice that left outer joins are slow Checked Exceptions Remember the first level cache If re-factoring, create DAO layer first and get code coverage to ~ 100% Automatic dirty-checking is a ‘must have’ (session per transaction) Write generic finder methods instead of one finder method for each possible combination Bi-directional relationship problems Consistent patterns are very important for a DAO layer: exception handling, transaction mgmt, finder methods, etc Hiberate SessionFactory.getCurrentSession() method. It allows application developers to delegate tracking of current sessions to Hibernate itself. Currently, the getCurrentSession() method is only available if you are using Hibernate within a JTA environment.

67 Spring AOP

68 Aspect Oriented Programming
AOP Support Straight forward implementation based on dynamic proxies Declarative transaction management notifications in workflow Audit trail Event publishing Refreshing reference data Application warning messages Also logging, synchronization, work monitoring, debugging

69 Spring Core: IoC+AOP Synergy
Powerful AOP framework Built on Spring IoC for easy configuration Out-of-the-box aspects address common concerns Empowers modularization of cross-cutting concerns

70 Example: Transaction configuration via Spring AOP
Uses Spring’s transaction manager Service implementations are automatically replaced with proxy implementations Simple transaction support for all service interfaces Single location to define all transaction supporting services

71 AOP Sample - Transactions
<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager"> <! > </bean> <bean id="matchAllWithPropReq" class="org.springframework.transaction.interceptor.MatchAlwaysTransactionAttributeSource"> <bean id="matchAllTxInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionManager"><ref bean="transactionManager"/></property> <property name="transactionAttributeSource"><ref bean="matchAllWithPropReq"/></property> <bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="interceptorNames"> <list><idref local="matchAllTxInterceptor"/></list> </property> <property name="beanNames"> <list><value>*Dao</value></list> <bean id="dailyReportDao" class="com.mycompany.myproject.dao.hibernate.DailyReportDaoImpl">

72 Example - StatelessSessionProxyFactoryBean
How does it work? Creates a dynamic AOP proxy Implements your POJO business interface A single interceptor intercepts each method invocation Creates and invokes the target EJB transparently Re-throws any unrecoverable exceptions as unchecked Chains of interceptors can be easily configured Example: Performance monitor interceptor, then invoke EJB.

73 Spring Core: AOP Example: PerformanceMonitor + EJBInvoker <bean id=“monitoredEjb” class=“spring.aop.ProxyFactoryBean”/> <property name=“proxyInterfaces”> <value>com.mycompany.MyBusinessInterface</value> </property> <property name=“interceptorNames”> <list> <value>performanceMonitor</value> <value>ejbInvoker</value> </list> </bean> <bean id=“performanceMonitor” class=“samples.PerformanceMonitorInterceptor”/> <bean id=“ejbInvoker” class=“spring.ejb.RemoteStatelessSessionBeanInvoker”> <property name=“jndiName”>myEjb</property> Now we can measure how slow remote method calls on EJBs really are… with no change required in application code!

74 Spring Core: AOP Example - TransactionProxyFactoryBean
Wraps a POJO in a transactional proxy Methods to advise are fully configurable How does it work? Interceptor intercepts each method invocation If the method is marked transactional: Create or reuse a transaction appropriately Commit or rollback based on configuration policy

75 Spring Core: AOP Example: TransactionProxyFactoryBean <bean id=“transactionalService” class=“spring.TransactionProxyFactoryBean”/> <property name=“target”> <ref bean=“myBankingService”/> </property> <property name=“transactionManager”> <ref bean=“localTransactionManager”/> <property name="transactionAttributes"> <props> <prop key=“transfer*">PROPAGATION_REQUIRED</prop> <prop key=“withdraw">PROPAGATION_REQUIRED</prop> <prop key=“deposit”>PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </bean> Why is this a great thing? EJB forces use to use JTA/JNDI – full dependency on container Spring gives you all the transacational power and configurable transaction management support – so you can use local transaction managers (single data source) for small applications but scale to JTA managed transactions for large ones. To do so is a minor configuration tweak!!! Now I can have pluggable, declarative transactions without the overhead of an EJB container… again, with no change required in application code! 

76 Spring Core AOP: Getting Fancy
Auto-proxy facility Automatically proxy beans matching a criteria Source-level metadata Markup configuration as .NET-style attributes Concise alternative to XML Keeps configuration metadata close to where it applies As with auto proxying in general, the main point of using BeanNameAutoProxyCreator is to apply the same configuration consistently to multiple objects, and with minimal volume of configuration. For example, maybe I want to apply a debugInterceptor to all objects ending in “*action”. It is a popular choice for applying declarative transactions to multiple objects. The source-level metadata allows you to specify configuration as .NET style attributes – at runtime, the infrastructure will then automatically create proxies based on what is marked up. For example, if you mark a method as transacational “REQUIRED” – using a the auto proxy facility, you’ll automatically have a proxy created that knows to make that method transacational when invoked.

77 AOP Description AOP decomposes a system into aspects or concerns, rather than objects. An example of a concern in an application would be logging, security, or transaction management. Often in OO systems there is code bloat and duplication from such concerns - something wrong with the solution. There are cases where OO does not provide a clean solution. AOP is capable of using either dynamic proxies or dynamic bytecode generation with CGLIB. This is also used in Hibernate. Spring, AspectJ, Nanning

78 AOP Crosscutting Without AOP With AOP

79 AOP in Spring Spring implements AOP in the same consistent way it deals with bean definitions in a BeanFactory. Transactions for JDBC <!-- Transaction manager for a single JDBC DataSource --> <!-- (see dataAccessContext-jta.xml for an alternative) --> <bean id="transactionManager" class="org.sf.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"><ref local="dataSource"/></property> </bean> Transactions for JTA <!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource) --> <!-- Necessary here due to the need for distributed transactions across two databases --> <!-- (see dataAccessContext-local.xml for an alternative) --> <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/> Transaction Interceptor

80 AOP in Spring Definitions:
Aspect - An application wide concern that is often duplicated in many classes, that could be implemented before, after, or upon failure across a group of methods. Join Point - Well-defined points in the program flow. Spring allows method interception: when a method is called the framework can attach functionality. Pointcut - Description of the collection of methods for which advice is to be applied Advice – the block of code that runs based on the pointcut definition Introduction - Adding methods or properties to a class with advice. AOP Proxy - Surrogate object that invokes advice and advises the invoked class Weaving – can be done at runtime or compile time. Inserts the advice (crosscutting concerns) into the code (core concerns).

81 Declarative Transactions with AOP
Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, iBATIS Database Layer and JDO. Provides a simpler, easier to use, API for programmatic transaction management than most of these transaction APIs Integrates with the Spring data access abstraction Supports Spring declarative transaction management <!-- Transactional proxy for the JPetStore primary business object --> <bean id="petStore" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"><ref bean="transactionManager"/></property> <property name="target"><ref local="petStoreTarget"/></property> <property name="transactionAttributes"> <props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> <!-- Uncomment the following in order to enable mail sending aspect --> <!-- <property name="postInterceptors"> <list> <ref local=" Advisor"/> </list> -->

82 TransactionManager Abstraction
Spring Transaction Strategy Interface: public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException; void commit(TransactionStatus status) throws TransactionException; void rollback(TransactionStatus status) throws TransactionException; } JDBC - <bean id="transactionManager“ class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"><ref local="dataSource"/></property> </bean> JTA - <bean id="transactionManager“ class="org.springframework.transaction.jta.JtaTransactionManager"/> Hibernate - <bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager"> <property name="sessionFactory"><ref local="sessionFactory"/></property>

83 Spring Core: Metadata Example
Markup a method as transactional public interface BankingService { /** * Transfers funds from one account to another. * * TransactionDefinition.PROPAGATION_REQUIRED); * */ public void transfer(...) throws InsufficientFundsException; } Basically what happens is the autoproxy service will look to apply create proxies based when they match a certain “advisor” criteria, which determines when certain “advice” – AOP behaivior – should apply. For example, when a new banking service is created, the auto proxy facilitate will look for a matching advisor, and will find one capable of returning whether a given method is transacational by querying the attributes metadata API. If attributes exist for the service, which in this case they do, the proxy is created with the appropriate advice configuration from the attributes source. The auto-proxy facility will automatically detect these attributes and create transactional AOP proxies which enforce them! 

84 AspectJ integration Coming in Spring 1.1 (August)
Particularly relevant to WebSphere users given IBM’s backing for AspectJ Integrates AspectJ aspects into Spring IoC Configure and parameterize aspects in a consistent way Will allow the use of the AspectJ pointcut expression language to target Spring advice Can mix Spring and AspectJ aspects within a consistent architectural model

85 Refactoring to Spring AOP
Start with just the IoC and build from there Be careful with the autowire – changes in Interfaces and refactoring can change autowire rules AOP supports proxying of classes via interface and via CGLib Interfaces are recommended to reduce coupling CGLib is available to support legacy code or 3rd party code Methods marked as “final” can not be advised Dynamic Pointcuts (ControlFlowPointcuts) can be slow so try to avoid them Avoid applying Advise to fine grained objects Use autoproxing when you want system wide advice

86 Remoting

87 Remoting Binary protocols XML-based protocols EJB, RMI
Hessian (binary protocol, uses HTTP, projected by Caucho) Spring's HTTP invoker (uses Java's standard serialization) XML-based protocols Burlap (similar to Hessian; uses XML) Web Services, Apache Axis (SOAP) JAX RPC

88 RMI – sample (business objects)
public class Account implements Serializable { private String name; public String getName(); public void setName(String name) { this.name = name; } public interface AccountService { public void insertAccount(Account acc); public List getAccounts(String name); public class AccountServiceImpl implements AccountService { public void insertAccount(Account acc) { } public List getAccounts(String name) { }

89 RMI sample (server) rmi://HOST:1199/AccountService
<bean id="accountService" class="example.AccountServiceImpl"/> <bean class="org.springframework.remoting.rmi.RmiServiceExporter"> <property name="serviceName"><value>AccountService</value></property> <property name="service"><ref bean="accountService"/></property> <property name="serviceInterface"> <value>example.AccountService</value> </property> <property name="registryPort"><value>1199</value></property> </bean> rmi://HOST:1199/AccountService

90 RMI – sample (client) public class ClientSimpleObject {
private AccountService accountService; public void setAccountService(AccountService accountService) { this.accountService = accountService; } <bean class="example.ClientSimpleObject"> <property name="accountService"><ref bean="accountService"/></property> </bean> <bean id="accountService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"> <property name="serviceUrl"><value>rmi://HOST:1199/AccountService</value></property> <property name="serviceInterface"><value>example.AccountService</value></property>

91 References

92 Resources Websites To Integrate your existing web-app with a Spring middle tier: Struts: Web Work: Tapestry:

93 Spring Related Tools and Add-Ons
ACEGI Security - comprehensive security services for the Spring Framework Spring IDE - graphical user interface for the configuration files used by the Spring Framework Spring BeanDoc - tool that facilitates documentation and graphing of Spring bean factories and application context files XDoclet Spring Tags - support for generating Spring XML config files from annotations in Java classes (you could also use JDK1.5 annotations to achieve this) Spring Web Flow - for web applications with demanding page flow requirements AppFuse Not really a tool or add-on, but AppFuse is Matt Raible's project to jumpstart your Java web projects. It uses Spring at it's core and studying it is a great way to learn about Spring. Spring Framework .NET – Spring Clone for the Dark Side.

94 Web Sites & Books The Official Spring Reference Manual Introduction to Spring by Rod Johnson Spring in Action by Craig Walls and Ryan Breidenbach Pro Spring by Rob Harrop and Jan Machacek J2EE Without EJB by Rod Johnson and Juergen Holler Expert One-on-One J2EE Design and Development by Rod Johnson Spring: A Developers Notebook by Bruce Tate and Justin Gehtland Better, Faster, Lighter Java by Bruce Tate and Justin Gehtland Spring Live by Matt Raible Professional Java Development with the Spring Framework by many of the core Spring developers: Coming in July 2005

95 References Jason Careira’s Blog: Hibernate in Action by Gavin King and Christian Bauer J2EE Development without EJB by Rod Johnson


Download ppt "Spring Framework."

Similar presentations


Ads by Google