The Spring FrameworkMission 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... •In1998 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 • 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
6.
What are LightweightFrameworks? • 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? Atit’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 • Springallows 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 • LayerArchitecture – 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 SpringArchitecture 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 AfterSpring • 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!
IoC Types • Threebasic 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 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 componentdeployment • Create object graphs and configure data • Inversion of Control (Dependency Injection) <beans> <bean id=“widgetService” class=“com.zabada.base.WidgetService”> <property name=“poolSize”> <!—-property value here--> </property> </bean> </beans> The bean’s ID The bean’s fully- qualified classname Maps to a setPoolSize() call
24.
Property Values forBeanFactories (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.
• 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 Inversion of control
27.
IoC - Sample Wewould like that MovieLister knew only about the interface, but how to create a working instance of MovieListener?
28.
class MovieLister... private MovieFinderfinder; 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()]); } public interface MovieFinder { List findAll(); } IoC - Sample
Importance of LooseCoupling 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.
High Level ofCoupling • 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. Products External Providers Data Access Application Framework
35.
Very Loose Coupling– layers talk only to those directly above and below them External Providers Workflow Products Data Access Application Framework 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 Spring Interceptors (AOP)/Interface Spring Interceptors (AOP)/Interface Interface Biz Services Spring Interceptors (AOP)/Interface Interface
36.
Application Logic Application Logic ApplicationLogic Service4 External Provider Layer Mock External Provider Layer Before Refactor After Refactor Refactor Enabled Looking at a Layer – Façade Pattern Spring Audit Interceptors Mock Mock Mock Mock Service3 Service2 Service1 Service1 Service2 Service3 Service4
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 toSpring 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 toSpring 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
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”/> </bean>
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 Theconfigurable 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)
Handling the requestwith 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 viewwith 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 ofViews 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 localemay 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 SpringMVC 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 (http://blah/foo.html -> foo) • SimpleFormController – for form handling, hooks for attaching commands, validator • AbstractWizardFormController – easy wizard controller • ServletWrappingController – delegates to a servlet
53.
Handling Forms • Setthe 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 toForms, but needs to validate along the way • One Controller handles multiple pages • Process at the end • Cancel anywhere along the line
55.
Interceptor • Some HandlerMappingsallow 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 philosophysays that most Exceptions should not be caught • ExceptionHandler determines what to do if an Exception is thrown through the Controller
57.
Themes • Totally changelook and feel of your application in one step! • Lets you point to different css, jsp, images
58.
Conclusion • Spring MVCoffers – Lots of flexibility – Straightforward design – Leverages Spring injection
Spring Solutions: DAOJDBC • 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: DAOORM • 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.
DriverManagerDataSource dataSource =new DriverManagerDataSource(); dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver"); dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:mydb"); 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)}); JDBC Template
65.
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); } } ); Hibernate Template
66.
Refactoring for SpringDAO • 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 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.
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
69.
Spring Core: IoC+AOPSynergy • 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 configurationvia 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
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> </property> </bean> <bean id=“performanceMonitor” class=“samples.PerformanceMonitorInterceptor”/> <bean id=“ejbInvoker” class=“spring.ejb.RemoteStatelessSessionBeanInvoker”> <property name=“jndiName”>myEjb</property> </bean> Now we can measure how slow remote method calls on EJBs really are… with no change required in application code!
74.
• 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 Spring Core: AOP
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> </property> </bean> 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
77.
AOP Description • AOPdecomposes 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
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 withAOP • 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="emailAdvisor"/> </list> </property> -->
Spring Core: MetadataExample • Markup a method as transactional public interface BankingService { /** * Transfers funds from one account to another. * * @@DefaultTransactionAttribute( TransactionDefinition.PROPAGATION_REQUIRED); * @@RollbackRuleAttribute(InsufficientFundsException.class); */ public void transfer(...) throws InsufficientFundsException; } The auto-proxy facility will automatically detect these attributes and create transactional AOP proxies which enforce them!
84.
AspectJ integration • Comingin 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 SpringAOP • 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
public class Accountimplements 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) { } } RMI – sample (business objects)
Resources • Websites – www.springframework.org;www.springframework.net – http://www.zabada.com/technology/Wiki.jsp?page=SpringRecipes • 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
93.
Spring Related Toolsand 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 http://www.springframework.org/docs/reference/ Introduction to Spring by Rod Johnson http://www.theserverside.com/articles/article.tss?l=SpringFramework 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’sBlog: www.jroller.com/page/jcarreira/20041215 • Hibernate in Action by Gavin King and Christian Bauer • J2EE Development without EJB by Rod Johnson
Editor's Notes
#5 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
#16 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)
#26 Komponenty - nie należy wprowadzać zmian w ich kodzie źródłowym, powinny być konfigurowalne.
#64 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.
#75 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!!!
#76 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.
#83 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.