Spring
Spring
By Mumbai Academics
Loose Coupling: The Spring applications are loosely coupled because of dependency injection and handles injecting dependent components without a component knowing where they came from (IoC). Powerful abstraction: It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA. Declarative support: It provides declarative support for caching, validation, transactions and formatting. Portable :can use server-side in web/ejb app, client-side in swing app, business logic is completely portable. Cross-cutting behavior : Resource Management is crosscutting concern, easy to copy-and-paste everywhere.
Configuration information: Spring provides one consistent way of configuring everything, separate configuration from application logic, varying configuration. Lifecycle : Responsible for managing all your application components, particularly those in the middle tier container sees components through well-defined lifecycle: init(), destroy()
Spring
Ubiquitous for Java development Well established in enterprise Java apps Time tested and proven reliable
A primary purpose is to reduce dependencies and even introduce negative dependencies Different from almost every other framework out there Part of the reason it has been adopted so quickly Spring code base is proven to be well structured (possibly the best) 139 packages No dependency cycles
Spring
Presentation layer An MVC framework that is most similar to Struts but is more powerful and easy to use. Business layer Lightweight IoC container and AOP support (including built in aspects) Persistence layer DAO template support for popular ORMs and JDBC
Simplifies persistence frameworks and JDBC Complimentary: Not a replacement for a persistence framework
Helps organize your middle tier and handle typical J2EE plumbing problems. Solutions to typical coding busywork JDBC ,LDAP,Web Services Reduces code and speeds up development Current Version is 3.0
Spring (continued)
Do I have to use all components of Spring? Spring is a non-invasive and portable framework that allows you to introduce as much or as little as you want to your application. Promotes decoupling and reusability POJO Based Allows developers to focus more on reused business logic and less on plumbing problems. Reduces or alleviates code littering, ad hoc singletons, factories, service locators and multiple configuration files. Removes common code issues like leaking connections and more. Built in aspects such as transaction management Most business objects in Spring apps do not depend on the Spring framework.
Introduced to Spring by way of Hibernate Spring is an open source layered Java/J2EE application framework The Spring Framework is licensed under the terms of the Apache License Originally wanted Spring to provide a way to simplify DAO objects and provide declarative transaction support to our non-EJB applications. Needed a solution to loosely couple business logic in a POJO fashion. Wanted to build portable applications that provided clearer separation of presentation, business, and persistence logic. Easily integrated with our existing frameworks Great documentation and community support
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. Don't need to develop another one).
No more custom factory object to build and/or locate other objects DAO simplification Consistent CRUD Data access templates No more copy-paste try/catch/finally blocks No more passing Connection objects between methods No more leaked connections POJO Based Refactoring experience with Spring Caution Spring is addictive!
The Spring Framework can be considered as a collection of frameworks-in-the-framework: Core - Inversion of Control (IoC) and Dependency Injection. AOP :- These modules support aspect oriented programming implementation where you can use Advices, Pointcuts etc. to decouple the code. DAO - Data Access Object support, transaction management, JDBC-abstraction ORM - Object Relational Mapping data access, integration layers for JPA, JDO, Hibernate, and iBatis MVC - Model-View-Controller implementation for webapplications Context-This module supports internationalization (I18N), EJB,Remote Access, Authentication and Authorization, Remote Management like RMI,HTTP Invoker,Hessain, Messaging Framework, Web Services, Email, Testing,
Expression Language:- It is an extension to the EL defined in JSP. It provides support to setting and getting property values, method invocation, accessing collections and indexers, named variables, logical and arithmetic operators, retrieval of objects by name etc.
Spring Details
Spring allows to decouple software layers by injecting a components dependencies at runtime rather than having them declared at compile time via importing and instantiating classes. 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. 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 Details
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 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
create the class create the xml file to provide the values create the test class Load the spring jar files Run the test class
IoC container
Setter based and constructor based dependency injection Portable across application servers Promotes good use of OO practices such as programming to interfaces. Beans managed by an IoC container are reusable and decoupled from business logic Spring uses Dynamic AOP Proxy objects to provide crosscutting services Reusable components Aopalliance support today Integrates with the IoC container AspectJ support in Spring 1.1
AOP
Spring IoC
Inversion of Control
Dependency injection Beans define their dependencies through constructor arguments or properties The container provides the injection at runtime Decouples object creators and locators from application logic Easy to maintain and reuse Testing is easier Useful for separating dao and business layer Useful for separating controllers and business layer The code is more extensible, easier to read, and modules/layers can easily be replaced
public class OrderSpringService implements IOrderService { IOrderDAO orderDAO; public Order saveOrder(Order order) throws OrderException{ // perform some business logic return orderDAO.saveNewOrder(order); } public void setOrderDAO(IOrderDAO orderDAO) { this.orderDAO = orderDAO; }
Singleton
One instance of the bean created and referenced each time it is requested
Prototype
(non-singleton)
The bean class is the actual implementation of the bean being described by the BeanFactory. Bean examples DAO, DataSource, Transaction Manager, Persistence Managers, Service objects, etc Spring config contains implementation classes while your code should program to interfaces. Bean behaviors include: Singleton or prototype Autowiring Initialization and destruction methods
init-method destroy-method
Can read simple values, collections, maps, references to other beans, etc.
attributes
class (required): fully qualified java class name id: the unique identifier for this bean configuration: (singleton, init-method, etc.) constructor-arg: arguments to pass to the constructor at creation time property: arguments to pass to the bean setters at creation time Collaborators: other beans needed in this bean (a.k.a dependencies), specified in property or constructor-arg
<bean id=orderBean class=example.OrderBean init-method=init> <property name=minimumAmountToProcess>10</property> <property name=orderDAO> <ref bean=orderDAOBean/> </property> </bean> public class OrderBean implements IOrderBean{ public void setMinimumAmountToProcess(double d){ this. minimumAmountToProcess = d; } public void setOrderDAO(IOrderDAO odao){ this.orderDAO = odao; } }
Spring BeanFactory
Lightweight container that loads bean definitions and manages your beans. Configured declaratively using an XML file, or files, that determine how beans can be referenced and wired together. Knows how to serve and manage a singleton or prototype defined bean Responsible for lifecycle methods. Injects dependencies into defined beans when served
Avoids the use of singletons and factories Spring uses a BeanFactory to create, manage and locate beans which are basically instances of a class
Typical
usage is an XML bean factory which allows configuration via XML files
Spring ApplicationContext
A Spring ApplicationContext allows you to get access to the objects that are configured in a BeanFactory in a framework manner. ApplicationContext extends BeanFactory
Adds services such as international messaging capabilities. Add the ability to load file resources in a generic fashion.
XMLWebApplicationContext Configuration for a web application. ClassPathXMLApplicationContext standalone XML application context FileSystemXmlApplicationContext
Configuring an XMLWebApplicationContext
<context-param> <param-name>contextConfigLocation</paramname> <param-value> /WEB-INF/applicationContext.xml </param-value> </context-param>
Configuring an XMLWebApplicationContext
<context-param> <param-name>contextConfigLocation</paramname> <param-value> /WEB-INF/applicationContext.xml </param-value> </context-param> <servlet> <servlet-name>context</servlet-name> <servlet-class> org.springframework.web.context.ContextLoader Servlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet>
Spring AOP
Spring AOP
Framework that builds on the aopalliance interfaces. Aspects are coded with pure Java code. You do not need to learn pointcut query languages that are available in other AOP implementations. Separates the core business code from the aspects we wrap around it: security, transaction management, monitering,logging Spring aspects can be configured using its own IoC container.
Objects obtained from the IoC container can be transparently advised based on configuration
Spring AOP has built in aspects such as providing transaction management, performance monitoring and more for your beans Spring AOP is not as robust as some other implementations such as AspectJ.
Spring AOP
of Concerns (SoC)
Dont
Minimize code duplication Program aspects that affect many others (e.g. logging)
Cross-Cutting
Spring AOP
Spring allows you to chain together interceptors and advice with precedence. Aspects are weaved together at runtime. AspectJ uses compile time weaving. Spring AOP also includes advisors that contain advice and pointcut filtering. ProxyFactoryBean sources AOP proxies from a Spring BeanFactory IoC + AOP is a great combination that is non-invasive Through AOP, we add transversal functionalities to objects (ie not directly related to the code it contains)
Without AOP
With AOP
Extend your DAO classes with the proper xxxDAOSupport class that matches your persistence mechanism. JdbcDaoSupport
Super class for JDBC data access objects. Requires a DataSource to be set, providing a JdbcTemplate based on it to subclasses.
HibernateDaoSupport
Super class for Hibernate data access objects. Requires a SessionFactory to be set, providing a HibernateTemplate based on it to subclasses. Super class for JDO data access objects. Requires a PersistenceManagerFactory to be set, providing a JdoTemplate based on it to subclasses. Supper class for iBATIS SqlMap data access object. Requires a DataSource to be set, providing a SqlMapTemplate
JdoDaoSupport
SqlMapDaoSupport
Built in code templates that support JDBC, Hibernate, JDO, and iBatis SQL Maps Simplifies data access coding by reducing redundant code and helps avoid common errors. Alleviates opening and closing connections in your DAO code. No more ThreadLocal or passing Connection/Session objects. Transaction management is handled by a wired bean You are dropped into the template with the resources you need for data access Session, PreparedStatement, etc. Code only needs to be implemented in callback methods.
doInXXX(Object)
Spring has its own exception handling hierarchy for DAO logic. No more copy and pasting redundant exception logic! Exceptions from JDBC, or a supported ORM, are wrapped up into an appropriate, and consistent, DataAccessException and thrown. This allows you to decouple exceptions in your business logic. These exceptions are treated as unchecked exceptions that you can handle in your business tier if needed. No need to try/catch in your DAO. Define your own exception translation by subclassing classes such as SQLErrorCodeSQLExceptionTranslator
Can
use a standalone Spring configuration with mock objects for testing. Consider XMLApplicationContext or FileSystemApplicationContext.
Unit testing
Allows
you to test outside the container without using the Spring container.
MVC Framework
Clear separation of roles: controller, validator, form object, Dispatch servlet, View resolver, Extensible and adaptable Several views of a result (pdf, excel, html, ) Can be wired (possible to use transparently the IoC pattern). Spring Annotation Based Controllers Spring 2.5 introduced support for annotation based MVC controllers. @RequestMapping, @RequestParam, @ModelAttribute are some of the annotations provided for this implementation.
Can be used with other frameworks: JSF, Struts, Tapestry, Webwork Completely transparent: no need to change anything in what is done by these other frameworks
Features of Spring Web MVC Spring's web module provides a wealth of unique web support features, including: Clear separation of roles - controller, validator, command object, form object, model object, DispatcherServlet, handler mapping, view resolver, etc. Each role can be fulfilled by a specialized object. Powerful and straightforward configuration of both framework and application classes as JavaBeans, including easy referencing across contexts, such as from web controllers to business objects and validators. Adaptability, non-intrusiveness. Use whatever controller subclass you need (plain, command, form, wizard, multiaction, or a custom one) for a given scenario instead of deriving from a single controller for everything. Reusable business code - no need for duplication. You can use existing business objects as command or form objects instead of mirroring them in order to extend a particular
Customizable locale and theme resolution, support for JSPs with or without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, etc. A simple yet powerful JSP tag library known as the Spring tag library that provides support for features such as data binding and themes. The custom tags allow for maximum flexibility in terms of markup code. For information on the tag library descriptor. A JSP form tag library, introduced in Spring 2.0, that makes writing forms in JSP pages much easier. For information on the tag library descriptor. Beans whose lifecycle is scoped to the current HTTP request or HTTP Session. This is not a specific feature of Spring MVC itself, but rather of the WebApplicationContext container(s) that Spring MVC uses. These bean scopes are described in detail in the section entitled.
Customizable binding and validation - type mismatches as application-level validation errors that keep the offending value, localized date and number binding, etc instead of String-only form objects with manual parsing and conversion to business objects. Customizable handler mapping and view resolution - handler mapping and view resolution strategies range from simple URL-based configuration, to sophisticated, purpose-built resolution strategies. This is more flexible than some web MVC frameworks which mandate a particular technique. Flexible model transfer - model transfer via a name/value Map supports easy integration with any view technology.
The DispatcherServlet
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram:
Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet: After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request. Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser.
extra features necessary for web applications.
All the above mentioned components ie. HandlerMapping, Controller and ViewResolver are parts ofWebApplicationContext which is an extension of the plain ApplicationContext with some
JavaMail helpers Many ORM tools are supported: Hibernate, JDO, Apache OJB, iBATIS Templates using IoC to reduce the amount of code in the DAO objects Scheduling support via Quartz Convenience implementation classes for
EJB support for easier access. Acegi Security System for Spring