Spring Framework Spring Introduction The Spring Framework Mission

  • Slides: 95
Download presentation
Spring Framework

Spring Framework

Spring Introduction

Spring Introduction

The Spring Framework Mission Statement • • • J 2 EE should be easier

The Spring Framework Mission Statement • • • J 2 EE 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. Java. Beans offer a great way of configuring applications. OO design is more important than any implementation technology, such as J 2 EE. 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.

Sun's Best Practices. . . • In 1998 Distributed Computing was the big buzzword

Sun's Best Practices. . . • In 1998 Distributed Computing was the big buzzword • Sun made EJBs to compete with technologies like CORBA • The specification was intrusive • And the result is Sun's famous Pet. Store application with quite difficult architecture

EJB Issues • Intrusive – Noisy – Must be an EJBObject – Must run

EJB Issues • 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

What are Lightweight Frameworks? • • • Non-intrusive No container requirements Simplify Application Development

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 Web. Work Quartz Sitemesh

What is Spring? At it’s core, Spring provides: • An Inversion of Control Container

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 Aspect. J or Aspect. Werkz • A Service Abstraction Layer – Consistent integration with various standard and 3 rd party APIs These together enable you to write powerful, scalable applications using POJOs.

Spring Overview from springframework. org Note: Spring distribution comes as one big jar file

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)

Spring introduction • Spring allows us to decouple our software layers by injecting a

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 Java. Beans framework to wire up dependencies. • Spring provides integration for J 2 EE 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.

Spring introduction • • Layer Architecture – Clear Architecture – Easy to track down

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)

Advantages of Spring Architecture Lifecycle – responsible for managing all your app components, particularly

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 (Io. C) Config information - Spring provides one consistent way of configuring everything, separate configuration from application logic, varying configuration. In J 2 EE (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)

Spring - Solutions • Solutions address major J 2 EE problem areas: – –

Spring - Solutions • Solutions address major J 2 EE problem areas: – – – Web application development (MVC) Enterprise Java Beans (EJB, JNDI) Database access (JDBC, i. Batis, 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

Before Spring After Spring • Proprietary, buggy configuration code • Proliferation of Singletons, Service

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!

Spring MVC Source: http: //www. manageability. org/polls/what_web_framework June 10, 2005

Spring MVC Source: http: //www. manageability. org/polls/what_web_framework June 10, 2005

Spring Application Context

Spring Application Context

Spring Application Context • Container which controls components Application. Context ctx = new File.

Spring Application Context • Container which controls components Application. Context ctx = new File. System. Xml. Application. Context("config. xml"); Class. Path. Xml. Application. Context ctx = new Class. Path. Xml. Application. Context( new String[] {"application. Context. xml", "application. Context-part 2. xml"} );

How to configure <? xml version="1. 0" encoding="UTF-8"? > <beans> <bean id= "component 1"

How to configure <? xml version="1. 0" encoding="UTF-8"? > <beans> <bean id= "component 1" class= "package. Class 1">. . . </bean> <bean name= "component 2, alias 1" class= "package. Class 2">. . . </beans>

Configuring Components • • • Singleton/prototype (non-singleton) Setter/constructor dependency injection Autowire: no, by. Name,

Configuring Components • • • Singleton/prototype (non-singleton) Setter/constructor dependency injection Autowire: no, by. Name, by. Type, constructor, autodetect Dependency-check: none, simple, object, all Init-method, destroy-method Lazy-init

Examples of configuration public class Example. Bean { private Another. Bean bean. One; private

Examples of configuration public class Example. Bean { private Another. Bean bean. One; private Yet. Another. Bean bean. Two; private int i; public Example. Bean(Another. Bean bean. One) { this. bean. One = bean. One; } public void set. Bean. Two(Yet. Another. Bean bean. Two) { this. bean. Two = bean. Two; } public void set. Integer. Property(int i) { this. i = i; } } <bean id="example. Bean" class="examples. Example. Bean" singleton="false"> <constructor-arg><ref bean="another. Example. Bean"/></constructor-arg> <property name="bean. Two"><ref local="yet. Another. Bean"/></property> <property name="integer. Property"><value>1</value></property> </bean> <bean id="another. Example. Bean" class="examples. Another. Bean"/> <bean id="yet. Another. Bean" class="examples. Yet. Another. Bean” lazy-load=”true”/>

Inversion of Control

Inversion of Control

Io. C Types • Three basic types – Type I • Interface Injection •

Io. C Types • Three basic types – Type I • 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 Java. Beans 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

Basic Java. Bean Pattern • Include a “getter” and “setter” method for each field

Basic Java. Bean Pattern • Include a “getter” and “setter” method for each field class My. Bean { private int counter; public int get. Counter() { return counter; } public void set. Counter(int counter) { this. counter = counter; } }

Bean. Factories • XML-based component deployment • Create object graphs and configure data •

Bean. Factories • XML-based component deployment • Create object graphs and configure data • Inversion of Control (Dependency Injection) The bean’s ID The bean’s fullyqualified classname <beans> <bean id=“widget. Service” class=“com. zabada. base. Widget. Service”> <property name=“pool. Size”> <!—-property value here--> </property> </bean> Maps to a set. Pool. Size() call </beans>

Property Values for Bean. Factories (continued) The real magic comes in when you can

Property Values for Bean. Factories (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=“widget. Service” class=“com. zabada. base. Widget. Service. Impl”> <property name=“widget. DAO”> <ref bean=“my. Widget. DAO”/> </property> </bean> This is the basic concept of Inversion of Control calls set. Widget. DAO(my. Widget. DAO) where my. Widget. DAO is another bean defined in the configuration

Inversion of Control (Io. C) • Rather than locating needed resources, application components provide

Inversion of Control (Io. C) • Rather than locating needed resources, application components provide setters through which resources are passed in during initialization • Example: our Data. Access. Object class provides a set. Data. Source() 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.

Inversion of control • Design pattern (Wzorzec projektowy) on top of which components are

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

Io. C - Sample We would like that Movie. Lister knew only about the

Io. C - Sample We would like that Movie. Lister knew only about the interface, but how to create a working instance of Movie. Listener?

Io. C - Sample public interface Movie. Finder { List find. All(); } class

Io. C - Sample public interface Movie. Finder { List find. All(); } class Movie. Lister. . . private Movie. Finder finder; public Movie. Lister() { finder = new Colon. Delimited. Movie. Finder("movies 1. txt"); } public Movie[ ] movies. Directed. By(String arg) { List all. Movies = finder. find. All(); for (Iterator it = all. Movies. iterator(); it. has. Next(); ) { Movie movie = (Movie) it. next(); if (!movie. get. Director(). equals(arg)) it. remove(); } return (Movie[ ]) all. Movies. to. Array(new Movie[all. Movies. size()]); }

Io. C - Sample

Io. C - Sample

Io. C - Sample class Movie. Lister. . . private Movie. Finder finder; public

Io. C - Sample class Movie. Lister. . . private Movie. Finder finder; public void set. Finder(Movie. Finder finder) { this. finder = finder; } class Colon. Movie. Finder. . . public void set. Filename(String filename) { this. filename = filename; }

Io. C - Sample <beans> <bean id="Movie. Lister" class="package. Movie. Lister"> <property name="finder"> <ref

Io. C - Sample <beans> <bean id="Movie. Lister" class="package. Movie. Lister"> <property name="finder"> <ref local="Movie. Finder"/> </property> </bean> <bean id="Movie. Finder" class="package. Colon. Movie. Finder"> <property name="filename"> <value>movies 1. txt</value> </property> </bean> </beans> public void test. Spring. Container() { Application. Context ctx = new File. System. Xml. Application. Context("config. xml"); Movie. Lister movie. Lister = (Movie. Lister) ctx. get. Bean("Movie. Lister"); Movie[ ] movies = movie. Lister. movies. Directed. By("Sergio Leone"); }

Testability Implications and Refactoring

Testability Implications and Refactoring

Importance of Loose Coupling with Spring • Adopting Spring is easier when architecture is

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

High Level of Coupling • • • Products Application Framework External Providers Data Access

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.

Interface Products Interface Spring Interceptors (AOP)/Interface Workflow External Providers Spring Interceptors (AOP)/Interface Application Framework

Interface Products Interface Spring Interceptors (AOP)/Interface Workflow External Providers Spring Interceptors (AOP)/Interface Application Framework Spring Interceptors (AOP)/Interface Very Loose Coupling – layers talk only to those directly above and below them Biz Services 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

After Refactor Looking at a Layer – Façade Pattern Before Refactor Spring Audit Interceptors

After Refactor Looking at a Layer – Façade Pattern Before Refactor Spring Audit Interceptors Application Logic External Provider Layer Service 4 Service 3 Service 2 Service 1 Refactor Enabled Mock External Provider Layer Application Logic Mock

Loose Coupling w/ Business Interface Pattern • Having code in EJBs makes unit testing

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.

Practical Refactoring to Spring Framework • • • Start with bean wiring (Inversion of

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

Practical Refactoring to Spring Framework • • • Entire code base can be tested

Practical Refactoring to Spring Framework • • • Entire code base can be tested out of container except for 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

Spring MVC

Spring MVC

Model-View-Controller

Model-View-Controller

MVC for Web • • Event – HTTP request from client Controller – Custom

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

About Spring MVC • Comes with the Spring distribution • Well integrated with the

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

Quick Spring Refresher • Write dependencies as setters • Link up dependencies in XML

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=“date. Format" class=“java. text. Simple. Date. Format"> <constructor-arg value=“dd MMM yyyy”/> </bean> <bean id=“my. Bean" class=“com. platinum. Solutions. stuff. Some. Class"> <property name=“date. Format” ref=“date. Format”/> </bean>

Spring MVC Basics • All calls go through the Dispatcher. Servlet • Config file

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

Spring MVC Configuration The configurable pieces of Spring MVC: • • org. springframework. web.

Spring MVC Configuration The configurable pieces of Spring MVC: • • org. springframework. web. servlet. Handler. Mapping – what controller to call given a URL org. springframework. web. servlet. View. Resolver – how to determine what view to show org. springframework. web. servlet. Locale. Resolver – how to determine internationalization org. springframework. web. multipart. Multipart. Resolver – how to handle files org. springframework. web. servlet. Handler. Exception. Resolver – what to do with an Exception org. springframework. web. servlet. Theme. Resolver – where to get css, images, pages from org. springframework. web. servlet. Handler. Adapter – wrapper around the controller (or servlet)

Spring MVC A (simplified) sequence diagram:

Spring MVC A (simplified) sequence diagram:

Handling the request with a Handler. Mapping Given a URL, figures out what Controller

Handling the request with a Handler. Mapping Given a URL, figures out what Controller to use: • Simple. Url. Handler. Mapping – define mappings with Map or Properties • Bean. Name. Url. Handler. Mapping – bean names have same names as URL • Commons. Path. Map. Handler. Mapping – use Commons Attributes to determine mapping

Selecting a view with a View. Resolver Given a view name, figures out what

Selecting a view with a View. Resolver Given a view name, figures out what View to use: • • Bean. Name. View. Resolver – Spring beans happen to have the same name Url. Based. View. Resolver – view name maps to a URL (like a filename) Resource. Bundle. View. Resolver – look up the View in a resource file Xml. View. Resolver – uses XML file to determine mappings Free. Marker. View. Resolver – Url. Resource. View. Resolver preset for Free. Marker. View Internal. Resource. View. Resolver – Url. Resource. View. Resolver preset for Internal. Resource. View Velocity. View. Resolver – Url. Resource. View. Resolver preset for Velocity. View

Different Views Plenty of Views are packaged with Spring MVC: • • • Jstl.

Different Views Plenty of Views are packaged with Spring MVC: • • • Jstl. View – map to a JSP page Redirect. View – Perform an HTTP Redirect Tiles. View, Tiles. Jstl. View – integration with tiles Velocity. Layout. View, Velocity. Toolbox. View, Velocity. View – Integration with the Velocity templating tool Free. Marker. View – use the Free. Marker templating tool Jasper. Reports. View, Jasper. Reports. Multi. Format. View, Jasper. Reports. Pdf. View, Jasper. Reports. Xls. View – Support for Jasper Reports

Localization • • • The locale may be chosen manually, selected by the browser,

Localization • • • The locale may be chosen manually, selected by the browser, or fixed – Accept. Header. Locale. Resolver - use the HTTP accept-header to determine the locale – Cookie. Local. Resolver - set the chosen locale in a cookie – Fixed. Locale. Resolver - always use a fixed locale (set in the config file) – Session. Locale. Resolver - store the chosen locale in the session The spring tag <spring: message> picks the resource Define the bean message. Source with a Message. Source to set the resources: – Static. Message. Source - set messages within the object – Resource. Message. Bundle. Message. Source - load messages from. properties files – Reloadable. Resource. Message. Bundle. Message. Source - same as above, but reloads! – (others)

Other Provided Controllers Spring MVC includes lots of Controllers to extend from: • •

Other Provided Controllers Spring MVC includes lots of Controllers to extend from: • • • Abstract. Controller – basic controller, knows about caching, turning on/off get/set/post/head Parameterizable. View. Controller – always go to the same view Url. File. Name. View. Controller – parses the URL to return a view (http: //blah/foo. html -> foo) Simple. Form. Controller – form handling, hooks for attaching commands, validator Abstract. Wizard. Form. Controller – easy wizard controller Servlet. Wrapping. Controller – delegates to a servlet

Handling Forms • Set the Command (just a bean) • Set a Validator if

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

Wizards • • Similar to Forms, but needs to validate along the way One

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

Interceptor • Some Handler. Mappings allow you to call an interceptor before the controller

Interceptor • Some Handler. Mappings 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

Exception. Handler • Spring philosophy says that most Exceptions should not be caught •

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

Themes • Totally change look and feel of your application in one step! •

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

Conclusion • Spring MVC offers – Lots of flexibility – Straightforward design – Leverages

Conclusion • Spring MVC offers – Lots of flexibility – Straightforward design – Leverages Spring injection

Spring DAO

Spring DAO

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

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

DAO Sequence

DAO Sequence

Spring Solutions: DAO JDBC • • • DAO Pattern – abstracts particular persistence mechanism

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

Spring Solutions: DAO ORM • Manages Hibernate sessions – No more Thread. Local sessions

Spring Solutions: DAO ORM • Manages Hibernate sessions – No more Thread. Local sessions – Sessions are managed by Spring declarative transaction management • • Hibernate. Template 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

JDBC Template Driver. Manager. Data. Source data. Source = new Driver. Manager. Data. Source();

JDBC Template Driver. Manager. Data. Source data. Source = new Driver. Manager. Data. Source(); data. Source. set. Driver. Class. Name("oracle. jdbc. driver. Oracle. Driver"); data. Source. set. Url("jdbc: oracle: thin: @localhost: 1521: mydb"); data. Source. set. Username("scott"); data. Source. set. Password("tiger"); Jdbc. Template jt = new Jdbc. Template(data. Source); jt. execute("create table mytable (id integer, name varchar(100))"); int count = jt. query. For. Int("select count(*) from mytable"); String name = (String) jt. query. For. Object("select name from mytable", String. class); List rows = jt. query. For. List("select * from mytable"); jt. update("update mytable set name = ? where id = ? ", new Object[ ] {name, new Integer(id)});

Hibernate Template Hibernate. Template ht = new Hibernate. Template(session. Factory); final String name =

Hibernate Template Hibernate. Template ht = new Hibernate. Template(session. Factory); final String name = "Nivea soap"; Product product = (Product)ht. execute( new Hibernate. Callback() { public Object do. In. Hibernate(Session session) throws Hibernate. Exception { return session. find( "from com. mycompany. Product product where product. name=? ", name, Hibernate. STRING). get(0); } } );

Refactoring for Spring DAO • • • Lazy loading – a must have (session

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 3. 0. 1 Session. Factory. get. Current. Session() method. It allows application developers to delegate tracking of current sessions to Hibernate itself. Currently, the get. Current. Session() method is only available if you are using Hibernate within a JTA environment.

Spring AOP

Spring AOP

Aspect Oriented Programming • AOP Support – – – Straight forward implementation based on

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

Spring Core: Io. C+AOP Synergy • Powerful AOP framework • Built on Spring Io.

Spring Core: Io. C+AOP Synergy • Powerful AOP framework • Built on Spring Io. C for easy configuration • Out-of-the-box aspects address common concerns – Empowers modularization of cross-cutting concerns

Example: Transaction configuration via Spring AOP • Uses Spring’s transaction manager • Service implementations

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

AOP Sample - Transactions <bean id="transaction. Manager" class="org. springframework. orm. hibernate. Hibernate. Transaction. Manager">

AOP Sample - Transactions <bean id="transaction. Manager" class="org. springframework. orm. hibernate. Hibernate. Transaction. Manager"> <!--. . . --> </bean> <bean id="match. All. With. Prop. Req" class="org. springframework. transaction. interceptor. Match. Always. Transaction. Attribute. Source"> <!--. . . --> </bean> <bean id="match. All. Tx. Interceptor" class="org. springframework. transaction. interceptor. Transaction. Interceptor"> <property name="transaction. Manager"><ref bean="transaction. Manager"/></property> <property name="transaction. Attribute. Source"><ref bean="match. All. With. Prop. Req"/></property> </bean> <bean id="auto. Proxy. Creator" class="org. springframework. aop. framework. autoproxy. Bean. Name. Auto. Proxy. Creator"> <property name="interceptor. Names"> <list><idref local="match. All. Tx. Interceptor"/></list> </property> <property name="bean. Names"> <list><value>*Dao</value></list> </property> </bean> <bean id="daily. Report. Dao" class="com. mycompany. myproject. dao. hibernate. Daily. Report. Dao. Impl"> <!--. . . --> </bean>

Example - Stateless. Session. Proxy. Factory. Bean • How does it work? – Creates

Example - Stateless. Session. Proxy. Factory. Bean • 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.

Spring Core: AOP • Example: Performance. Monitor + EJBInvoker <bean id=“monitored. Ejb” class=“spring. aop.

Spring Core: AOP • Example: Performance. Monitor + EJBInvoker <bean id=“monitored. Ejb” class=“spring. aop. Proxy. Factory. Bean”/> <property name=“proxy. Interfaces”> <value>com. mycompany. My. Business. Interface</value> </property> <property name=“interceptor. Names”> <list> <value>performance. Monitor</value> <value>ejb. Invoker</value> </list> </property> </bean> <bean id=“performance. Monitor” class=“samples. Performance. Monitor. Interceptor”/> <bean id=“ejb. Invoker” class=“ spring. ejb. Remote. Stateless. Session. Bean. Invoker ”> <property name=“jndi. Name”>my. Ejb</property> </bean> Now we can measure how slow remote method calls on EJBs really are… with no change required in application code!

Spring Core: AOP • Example - Transaction. Proxy. Factory. Bean – Wraps a POJO

Spring Core: AOP • Example - Transaction. Proxy. Factory. Bean – 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

Spring Core: AOP • Example: Transaction. Proxy. Factory. Bean <bean id=“transactional. Service” class=“spring. Transaction.

Spring Core: AOP • Example: Transaction. Proxy. Factory. Bean <bean id=“transactional. Service” class=“spring. Transaction. Proxy. Factory. Bean”/> <property name=“target”> <ref bean=“my. Banking. Service”/> </property> <property name=“transaction. Manager”> <ref bean=“local. Transaction. Manager”/> <property name="transaction. Attributes"> <props> <prop key=“transfer*">PROPAGATION_REQUIRED</prop> <prop key=“withdraw">PROPAGATION_REQUIRED</prop> <prop key=“deposit”>PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED, read. Only</prop> </props> </property> </bean> Now I can have pluggable, declarative transactions without the overhead of an EJB container… again, with no change required in application code!

Spring Core AOP: Getting Fancy • Auto-proxy facility – Automatically proxy beans matching a

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

AOP Description • AOP decomposes a system into aspects or concerns, rather than objects.

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, Aspect. J, Nanning

AOP Crosscutting • Without AOP • With AOP

AOP Crosscutting • Without AOP • With AOP

AOP in Spring • Spring implements AOP in the same consistent way it deals

AOP in Spring • Spring implements AOP in the same consistent way it deals with bean definitions in a Bean. Factory. • Transactions for JDBC <!-- Transaction manager for a single JDBC Data. Source --> <!-- (see data. Access. Context-jta. xml for an alternative) --> <bean id="transaction. Manager" class="org. sf. jdbc. datasource. Data. Source. Transaction. Manager"> <property name="data. Source"><ref local="data. Source"/></property> </bean> • Transactions for JTA <!-- Transaction manager that delegates to JTA (for a transactional JNDI Data. Source) --> <!-- Necessary here due to the need for distributed transactions across two databases --> <!-- (see data. Access. Context-local. xml for an alternative) --> <bean id="transaction. Manager" class="org. springframework. transaction. jta. Jta. Transaction. Manager"/> • Transaction Interceptor

AOP in Spring • Definitions: – Aspect - An application wide concern that is

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).

Declarative Transactions with AOP • • • Provides a consistent programming model across different

Declarative Transactions with AOP • • • Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, i. BATIS 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 JPet. Store primary business object --> <bean id="pet. Store" class="org. springframework. transaction. interceptor. Transaction. Proxy. Factory. Bean"> <property name="transaction. Manager"><ref bean="transaction. Manager"/></property> <property name="target"><ref local="pet. Store. Target"/></property> <property name="transaction. Attributes"> <props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED, read. Only</prop> </props> </property> <!-- Uncomment the following in order to enable mail sending aspect --> <!-<property name="post. Interceptors"> <list> <ref local="email. Advisor"/>

Transaction. Manager Abstraction Spring Transaction Strategy Interface: public interface Platform. Transaction. Manager { Transaction.

Transaction. Manager Abstraction Spring Transaction Strategy Interface: public interface Platform. Transaction. Manager { Transaction. Status get. Transaction(Transaction. Definition definition) throws Transaction. Exception; void commit(Transaction. Status status) throws Transaction. Exception; void rollback(Transaction. Status status) throws Transaction. Exception; } JDBC - <bean id="transaction. Manager“ class="org. springframework. jdbc. datasource. Data. Source. Transaction. Manager"> <property name="data. Source"><ref local="data. Source"/></property> </bean> JTA - <bean id="transaction. Manager“ class="org. springframework. transaction. jta. Jta. Transaction. Manager"/> Hibernate <bean id="transaction. Manager" class="org. springframework. orm. hibernate. Hibernate. Transaction. Manager"> <property name="session. Factory"><ref local="session. Factory"/></property> </bean>

Spring Core: Metadata Example • Markup a method as transactional public interface Banking. Service

Spring Core: Metadata Example • Markup a method as transactional public interface Banking. Service { /** * Transfers funds from one account to another. * * @@Default. Transaction. Attribute( Transaction. Definition. PROPAGATION_REQUIRED); * @@Rollback. Rule. Attribute(Insufficient. Funds. Exception. class); */ public void transfer(. . . ) throws Insufficient. Funds. Exception; } The auto-proxy facility will automatically detect these attributes and create transactional AOP proxies which enforce them!

Aspect. J integration • Coming in Spring 1. 1 (August) • Particularly relevant to

Aspect. J integration • Coming in Spring 1. 1 (August) • Particularly relevant to Web. Sphere users given IBM’s backing for Aspect. J • Integrates Aspect. J aspects into Spring Io. C – Configure and parameterize aspects in a consistent way • Will allow the use of the Aspect. J pointcut expression language to target Spring advice • Can mix Spring and Aspect. J aspects within a consistent architectural model

Refactoring to Spring AOP • Start with just the Io. C and build from

Refactoring to Spring AOP • Start with just the Io. C 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 3 rd party code • Methods marked as “final” can not be advised • Dynamic Pointcuts (Control. Flow. Pointcuts) can be slow so try to avoid them • Avoid applying Advise to fine grained objects • Use autoproxing when you want system wide advice

Remoting

Remoting

Remoting • Binary protocols – EJB, RMI – Hessian (binary protocol, uses HTTP, projected

Remoting • Binary 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

RMI – sample (business objects) public class Account implements Serializable { private String name;

RMI – sample (business objects) public class Account implements Serializable { private String name; public String get. Name(); public void set. Name(String name) { this. name = name; } } public interface Account. Service { public void insert. Account(Account acc); public List get. Accounts(String name); } public class Account. Service. Impl implements Account. Service { public void insert. Account(Account acc) { } public List get. Accounts(String name) { } }

RMI sample (server) <bean id="account. Service" class="example. Account. Service. Impl"/> <bean class="org. springframework. remoting.

RMI sample (server) <bean id="account. Service" class="example. Account. Service. Impl"/> <bean class="org. springframework. remoting. rmi. Rmi. Service. Exporter"> <property name="service. Name"><value>Account. Service</value></property> <property name="service"><ref bean="account. Service"/></property> <property name="service. Interface"> <value>example. Account. Service</value> </property> <property name="registry. Port"><value>1199</value></property> </bean> rmi: //HOST: 1199/Account. Service

RMI – sample (client) public class Client. Simple. Object { private Account. Service account.

RMI – sample (client) public class Client. Simple. Object { private Account. Service account. Service; public void set. Account. Service(Account. Service account. Service) { this. account. Service = account. Service; } } <bean class="example. Client. Simple. Object"> <property name="account. Service"><ref bean="account. Service"/></property> </bean> <bean id="account. Service" class="org. springframework. remoting. rmi. Rmi. Proxy. Factory. Bean"> <property name="service. Url"><value>rmi: //HOST: 1199/Account. Service</value></property> <property name="service. Interface"><value>example. Account. Service</value></property> </bean>

References

References

Resources • Websites – www. springframework. org; www. springframework. net – http: //www. zabada.

Resources • Websites – www. springframework. org; www. springframework. net – http: //www. zabada. com/technology/Wiki. jsp? page=Spring. Recipes • To Integrate your existing web-app with a Spring middle tier: – Struts: http: //struts. sourceforge. net/struts-spring/ – Web Work: http: //wiki. opensymphony. com/space/Spring+Framework+Integration – Tapestry: http: //www. springframework. org/docs/integration/tapestry. html

Spring Related Tools and Add-Ons • • ACEGI Security - comprehensive security services for

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 Bean. Doc - 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 JDK 1. 5 annotations to achieve this) Spring Web Flow - for web applications with demanding page flow requirements App. Fuse Not really a tool or add-on, but App. Fuse 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 Framework. NET – Spring Clone for the Dark Side.

Web Sites & Books The Official Spring Reference Manual http: //www. springframework. org/docs/reference/ Introduction

Web Sites & Books The Official Spring Reference Manual http: //www. springframework. org/docs/reference/ Introduction to Spring by Rod Johnson http: //www. theserverside. com/articles/article. tss? l=Spring. Framework Spring in Action by Craig Walls and Ryan Breidenbach Pro Spring by Rob Harrop and Jan Machacek J 2 EE Without EJB by Rod Johnson and Juergen Holler Expert One-on-One J 2 EE 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

References • Jason Careira’s Blog: www. jroller. com/page/jcarreira/20041215 • Hibernate in Action by Gavin

References • Jason Careira’s Blog: www. jroller. com/page/jcarreira/20041215 • Hibernate in Action by Gavin King and Christian Bauer • J 2 EE Development without EJB by Rod Johnson