Spring framework: Spring is an open-source application frameworkSpring framework: Spring is an open-source application framework
SPRING Framework... AN
by Farihah Noushene B.E.,
(PUBLISHED IN DEVELOPER IQ -
Spring is an open-source
application framework, introduced and developed in 2004. The main ideas were
suggested by an experienced J2EE architect, Rod
He had earlier, written
a book titled 'J2EE
Just as Hibernate
attacks CMP as primitive ORM technology, Spring attacks EJB as unduly
complicated and not susceptible to unit-testing. Instead of EJB, Spring suggests
that we make use of ordinary Java beans, with some slight modifications, to
get all the supposed advantages of EJB environment. Thus, Spring is posed
as an alternative to EJB essentially. However, as a concession to the existing
EJB investments, Spring is designed to operate with EJB if required.
Much of the philosophy and approach of Spring framework, however, predates , the latest EJB vesrion (ie) EJB-3, about to arrive shortly. It is said that EJB-3 has absorbed a number of new ideas suggested by Spring and some more, to answer the criticisms. There is a debate going on in the Java community about Spring and EJB-3. Spring is not a Persistence technolgy but a framework which allows plug in of other such technologies. But EJB-3 is primarily focussed on Persistence Technology and has now incorporated Hibernate, the best ORM todate.Talks are going on to incorpotrate another equally nice ORM Technology known as JDO, which provides for Object Database also. Moreoveer, EJB-3 's Attribute-Orientaed Meta tags, help in vastly reducing the size of XML lines. Some have complained that Spring is still too dependent on XML files. In this tutorial, any reference to EJB, is only to EJB-2.My aim in presenting this tutorial is not to advocate the choice of either Spring or EJB-3, a topic still being devbated by experts but to share my perception with our readers.
In spring, we can make use of plain Java Beans to achieve things that were previously possible with EJB only. The main aim of Spring is to simplify the J2EE development and testing.
EJB has been around since 1988 and is an established standard and specification in Enterprise world. Though there have been numerous Open-source Java technologies recently, no other technology has claimed to be superior to EJB, in its total features.
Rod Johnson, in his
book, critices a number of features in EJB. Significantly, he has also spoken
approvingly of some features of EJB and has recommended its use in some special
EJB is a standard with wide Enterprise-level Industry support.It has been deployed in thousands of successful applications around the world. The EJB specification is a fixed target and so tool-developers are able to develop wizards, which can make ejb development quick and easy. There are many vendors for EJB application server like IBM (Web-Sphere), BEA (Weblogic), Oracle (JDeveloper) etc.
To quote from another book on Spring ("Spring in Action" - Craig Walls-Manning press) " EJB is complex ", as the author put it nicely, "not for just being complex'. It is complex because it attempts to provide solutions for complex problems". EJB is developed mainly for the remote transaction and distributed objects. But a number of enterprise projects do not have this level of complexity and still use EJBs and even the simple application becomes complex. In such cases Spring claims to be an alternative.
Since Spring comes with rich support to enterprise level services, it claims to be an alternative to EJB It is worthwhile to begin with a comparison of EJB-2 and Spring, in some main features.
The main advantages of
EJB are :
b) Declarative Transaction support
c) Persistence ( CMP & BMP)
d) Declarative Security
e) Distributed Computing (Container managed RPC)
Spring does not attempt to do everything by itself but supports the best of breed technologies for each of these requirements.
For example, instead of CMP & BMP, it supports several persistence technologies like JDO, Hibernate and OJB. These ORM toools are far more capable than the implementation in CMP.To simplify JDBC coding, there are tools like iBatis and Spring supports iBatis also.
Spring makes use of Acegi, an open-source Security framework and provides declarative security through spring configuration file or class metadata while in EJB declarative security is configured through deployment descriptor.
Spring provides proxying for RMI (special remoting technologies like Burlap) JAX-RPC & web-service while EJB provides container-managed remote method calls.
Spring can offer declarative transaction like EJB. But spring provides declarative rollback behavior also ,for methods and exceptions
Thus, while EJB is monolithic and attempts to do many things, some tasks fairly well and some others not so well, Spring uses ordinary Java beans only and through special techniques provides many of the functionalities of EJB, by integrating with a number of open-source technologies.
Thereby, it gives the
following advantages over EJB2.
a) testing is easier. We do not need to start the EJB container , for testing.
b) As Spring is based on the standard JavaBeans naming convention, programmers find it easy to work with.
c) It makes use of AOP(Aspect-Oriented Programming) which is a very recent and useful paradigm., in addition to classic OOP and preserves the purity of OOP.
d) It is flexible.
Spring's goal is to be an entire Application Framework. Other popular framewoks like Struts, Tapestry, JSF etc., are very good web tier frameworks but when we use these framework, we have to provide additional framework to deal with enterprise tier that integrates well with these framework. Spring tries to alleviate this problem by providing a comprehensive framework, which includes
a core bean container,
an MVC framework,
an AOP integration framework,
a JDBC integration framework and
an EJB integration framework.
It also provides integration modules for O/R mapping tools like Hibernate and JDO. Thus spring framework can be thought of as a layered architecture consisting of seven well defined modules.
The function of each component is as follows:
1. Core Container:
The core container provides the fundamental functionality of Spring. It's primary component is the 'BeanFactory', an implementation of the Factory pattern. The BeanFactory applies the IOC pattern to separate an application's configuration and dependency specification from the actual application code.
2. Spring Context/Application Context:
The Spring context is a configuration file that provides context information to the Spring framework . The Spring context supplies enterprise services such as JNDI access, EJB integration, e-mail, internalization, validation, and scheduling functionality.
3. Spring AOP:(Aspect-Oriented)
The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result we can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP we can incorporate declarative transaction management into our applications without relying on EJB components.
The Spring AOP module also introduces metadata programming to Spring. Using this we can add annotation to the source code that instructs Spring on where and how to apply aspects.
4. Spring DAO:
The Spring's JDBC and DAO abstraction layer offers a meaningful exception hierarchy for managing the databaase connection, exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of code that we need to write, such as opening and closing connections. This module also provide transaction management services for objects in a spring application.
5. Spring ORM:
The Spring framework can be integrated to several ORM frameworks to provide Object Relational tool, including JDO, Hibernate, OJB and iBatis SQL Maps.
6. Spring Web module:
The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts, JSF and webworks. The Web module also eases the tasks of handling multipart requests and binding request parameters to domain objects.
7. Spring MVC
The MVC framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles and the generation of PDF and Excel Files.
I would venture to suggest that Spring will win sure acceptance among j2ee devcelopers , very soon because of its ready-made adapters for various hot web-tier and presentation technologies.!
For example, there is a great varierty of technologies in the web-tier like MVC PATTERN,
In the MVC adapter, it offers the following View choices.
JSP is default view template. 'InternalResouceViewResolver' can be used for this purpose. Spring can be integrated with other template solutions like Velocity, FreeMarker, tiles etc., Also Spring can be used to produce dynamic binary Excel spreadsheet, PDF documents etc.,
To configure the velocity engine 'VelocityConfigurer' bean is declared in spring configuration. The view resolver is configured by 'VelocityViewResolver' bean.
To configure the FreeMarker
engine 'FreeMarkerConfigurer' bean is declared in spring configuration.
The view resolver is configured by 'FreeMarkerViewResolver' bean.
'TilesConfigurer' can used to used to load Tiles configuration file for rendering Tiles view. 'AbstractExcelView' is used to generate Excel SpreadSheet as views. 'AbstactPdfView' supports the creation of PDF as views. 'buildPdfDocument()' is used to create PDF decument. Similarly we have 'buildExcelDocument()' to create the excel document.
For delegation purpose, Spring provides 'DelegatingRequestProcessor' and to use the tiles 'DelegatingTilesRequestProcessor' is used. 'SpringTapestryEngine' is used for integrating Tapestry to Spring. 'FacesSpringVariableResolver' is used to resolve spring-managed beans in JSF.
Next we shall see the
main concepts of Spring, Inversion of Control (IoC) and Aspect Oriented
Programming. Spring is based on dependency injection type of IoC
The container provides callbacks to components and a lookup context. The managed objects are responsible for their other lookups. This is the EJB Approach. The Inversion of Control is limited to the Container involved callback methods that the code can use to obtain resources. Here we need to use JNDI to look up other EJBs and resources. Because of this reason EJB is not branded as 'IOC framework'.There are some problems in this implementation. The class needs a application server environment as it is dependent on JNDI and it is hard to test as we need to provide a dummy JNDI contest for testing purpose.
In this application objects is not responsible for looking up resources they depend on. Instead IoC container configures the object externalizing resource lookup from application code into the container. That is, dependencies are injected into objects. Thus lookups are completely removed from application objects and it can be used outside the container also.
In this method, the objects can be populated via Setter Injection (Java-Beans properties) or Constructor Injection (constructor arguments). Each method has its own advantage and disadvantage.
Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows
public void setName(String a)
name = a;
public String getName()
We will create an instance of the bean 'namebean' (say bean1) and set property as bean1.setName("tom"); Here in setter injection, we will set the property 'name' by using the <property> subelement of <bean> tag in spring configuration file as showm below,
The subelement <value> sets the
'name' property by calling the set method as
process is called setter injection.
For constructor injection, we use constructor with parameters as shown below,
public class namebean
public namebean(String a)
name = a;
We will set the property 'name' while creatinf an instance of the bean 'namebean' as namebean bean1 = new namebean("tom");
Here we use the <constructor-arg> element to set the the property by constructor injection as
<value>My Bean Value</value>
To set properties that reference other beans <ref>, subelement of <property> is used as shown below,
Oriented programming is a new
programming technique that promotes
separation of concerns within the system. System are composed of several
components each responsible for a specific piece of functionality. Whatever may
be the core function of the program, the system service like logging,
transaction management, security etc., must be included in the program. These
system services are commonly refered to as 'cross-cutting concerns' as
they tend to cut across multiple components in a system. AOP makes it
possible to modularize and separate these services and then apply them
declaratively to the components and we can focus on our own specific concerns.
In spring, aspects are wired into objects in the spring XML file in the
same way as JavaBean. This process is known as 'Weaving'.
The container is at the core of Spring Container. In manages the life cycle and configuration of application objects. We can configure how each of our beans should be created either to create a single instance of bean or produce a new instance every time and how they should be associated with each other. Spring should not, however, be confused with traditionally heavyweight EJB containers, which are often large. The Spring actually comes with two distinct containers: Bean Factories-defined by "org.springframework. beans.factory.BeanFactory" are the simplest containers, providing support for dependency injection. Application contexts - defined by "org.springframework.context.Application Context" provides application framework services.
Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. As the bean factory knows about many objects within an application, it is able to create association between collaborating objects as they are instantiated. This removes the burden of configuration from the bean and the client.
There are several implementation of BeanFactory. The most useful one is "org.springframework.beans.factory.xml.
XmlBeanFactory". It loads its beans based on the definition contained in an XML file. To create an XmlBeanFactory, pass a InputStream to the constructor. The resource will provide the XML to the factory.
BeanFactory factory = new XmlBeanFactory(new FileInputStream("myBean.xml"));
This line tells the bean factory to read the bean definition from the XML file. The bean definition includes the description of beans and their properties. But the bean factory doesn't instantiate the bean yet. To retrieve a bean from a 'BeanFactory', the getBean() method is called. When getBean() method is called, factory will instantiate the bean and begin setting the bean's properties using dependency injection.
While Bean Factory is used for simple applications, the Application Context is spring's more advanced container. Like 'BeanFactory' it can be used to load bean definitions, wire beans together and dispense beans upon request.
It also provide
1) a means for resolving text messages, including support for internationalization.
2) a generic way to load file resources.
3) events to beans that are registered as listeners.
Because of additional functionality, 'Application Context' is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, 'BeanFactory' is used. The three commonly used implementation of 'Application Context' are
1. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
2. FileSystemXmlApplicationContext :
It loads context definition from an XML file in the filesystem. The application
context is loaded from the file system by using the code
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
3. XmlWebApplicationContext : It
loads context definition from an XML file contained within a web application.
Spring is lightweight in terms of both size and overhead. The entire Spring framework can be distributed in a single JAR file that weighs just over 1.7 MB. And the processing overhead required by Spring is negligible. Also Spring is nonintrusive:(ie) objects in a Spring-enabled application typically have no dependencies on Spring-specific classes.
There are other lightweight containers like HiveMind, Avalon, PicoContainer etc., Avalon was one of the first IoC containers. Avalon mainly provides interface-dependent IoC. so, we much change our code in order to use a different container. This couples your code to a particular framework which is an undesirable feature.
PicoContainer is a minimal (very small size nearly 50k) lightweight container that provides IoC in the form of constructor and setter injection. By using PicoContainer we can only assemble components programmatically through PicoContainer's API. But it allows only one instance of any particular type to be present in the registry. Also PicoContainer is only a container. It does not offer various special features as spring like integration.
HiveMind is relatively new IoC container. Like PicoContainer, it focuses on wiring with support for both constructor and setter injections. It also allows us to define our configuration in an XML file. Like PicoContainer, HiveMind is only a container. It does not offer integration with other technology. Thus Spring makes it possible to configure and compose complex applications from simpler components. In Spring, application objects are composed declaratively, typically in an XML file. Spring also provides much infrastructure functionality like transaction management, persistence framework integration, etc., leaving the development of application logic
With this inroduction, we shall see a simple example in Spring in next article.
1.'Spring in Action' - Craig Walls
and Ryan Breidenbach.
2.'J2EE Development without EJB'
- Rod Johnson