`
itwangxinli
  • 浏览: 146106 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

SPRING ... AN INTRODUCTION

阅读更多

SPRING ... AN INTRODUCTION<o:p> </o:p>

------------------------ <o:p></o:p>

by Farihah Noushene B.E.,<o:p> </o:p>

---------------------------<o:p> </o:p>

PART-I<o:p> </o:p>

----------------- <o:p></o:p>

                         

(PUBLISHED IN DEVELOPER IQ - September2005) <o:p></o:p>

Spring is an open-source application framework, introduced and developed in 2004. The main ideas were suggested by an experienced J2EE architect,  Rod Johnson.<o:p> </o:p>

He had earlier, written a book titled 'J2EE<o:p> </o:p>Develoment without using EJB' and had introduced the concept of Light-weight container. Primarily, his argument is that while EJB  has its merits, it is not always necessary and suitable in all applications.<o:p> </o:p>

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.<o:p> </o:p>

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. <o:p></o:p>

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.<o:p> </o:p>

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. <o:p></o:p>

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 circumstances. <o:p></o:p>

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. <o:p></o:p>

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.<o:p> </o:p>

The main advantages of EJB are :<o:p> </o:p>

a) Transaction Management<o:p> </o:p>
b) Declarative Transaction support<o:p> </o:p>
c) Persistence ( CMP & BMP)<o:p> </o:p>
d) Declarative Security<o:p> </o:p>
e) Distributed Computing (Container managed
RPC)<o:p> </o:p>

Spring does not attempt to do everything by itself but supports the best of breed technologies for each of these requirements.<o:p> </o:p>
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.<o:p> </o:p>

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.<o:p> </o:p>
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<o:p> </o:p>
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.<o:p> </o:p>

Thereby, it gives the following advantages over EJB2.<o:p> </o:p>
a) testing is easier. We do not need to start the EJB container , for testing.<o:p> </o:p>
b) As Spring is based on the standard JavaBeans naming convention, programmers find it easy to work with.<o:p> </o:p>
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.<o:p> </o:p>
d) It is flexible.<o:p> </o:p>
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 <o:p></o:p>
a core bean container, <o:p></o:p>
an MVC framework,<o:p> </o:p>
an AOP integration framework,<o:p> </o:p>
a JDBC integration framework and <o:p></o:p>
an EJB integration framework.<o:p> </o:p>

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:<o:p> </o:p>

1. Core Container:<o:p> </o:p>
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.<o:p> </o:p>

2. Spring Context/Application Context:<o:p> </o:p>
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. <o:p></o:p>

3. Spring AOP:(Aspect-Oriented)<o:p> </o:p>
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.<o:p> </o:p>

4. Spring DAO:<o:p> </o:p>
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.<o:p> </o:p>

5. Spring ORM:<o:p> </o:p>
The Spring framework can be integrated to  several ORM frameworks to provide Object Relational tool, including JDO, Hibernate, OJB and iBatis SQL Maps. <o:p></o:p>

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. <o:p></o:p>

7. Spring MVC Framework:
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. <o:p></o:p>

--------------------------------------------<o:p> </o:p>
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.!<o:p> </o:p>
For example, there is a  great varierty of technologies in the web-tier like MVC PATTERN,<o:p> </o:p>STRUTS, JSF, WEB-WORK, JSP, TAPESTRY,FREEMARKER  etc.<o:p> </o:p>Developers are now puzzled and confused about the relative merits and demerits of all these. Once they choose a technology and start implementing and later want to change over to another technology, it is very difficult. But, as Spring offers modules for aall the above technologies, it is most often simply changing the configuraion file. With this approach, it is even possible for a development team to try and test a given task in all the above forms and see the effect and performance before deciding the choice. Spring offers its own version of MVC architecture. It also offers adapters for Struts.<o:p> </o:p>

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.,<o:p> </o:p>

To configure the velocity engine 'VelocityConfigurer' bean is declared in spring configuration. The view resolver is configured by 'VelocityViewResolver' bean.  <o:p></o:p>

To configure the FreeMarker engine 'FreeMarkerConfigurer' bean is declared in spring configuration. The view resolver is configured by 'FreeMarkerViewResolver' bean.<o:p> </o:p>

'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.<o:p> </o:p>

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.<o:p> </o:p>

-----------------------------------------------------------------------------

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<o:p> </o:p>. We don't directly connect our components and services together in code but describe which services are needed by which components in a configuration file. A container is responsible for hooking it up. This concept is similar to 'Declarative Management'. IOC is a broad concept. the two main types are <o:p></o:p>

 1. Dependency Lookup:<o:p> </o:p>
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.<o:p> </o:p>

2. Dependency Injection:<o:p> </o:p>
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.<o:p> </o:p>

----<o:p> </o:p>
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. <o:p></o:p>
Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows<o:p> </o:p>

 <o:p> </o:p>public class namebean<o:p> </o:p>

{<o:p> </o:p>

     String      name;<o:p> </o:p>

 <o:p> </o:p>

     public void setName(String a)<o:p> </o:p>

     {<o:p> </o:p>

        name = a;<o:p> </o:p>

     }<o:p> </o:p>

     public String getName()<o:p> </o:p>

     {<o:p> </o:p>

        return name;<o:p> </o:p>

     }<o:p> </o:p>

}<o:p> </o:p>

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,<o:p> </o:p>

 <o:p> </o:p>

<bean id="bean1"   class="namebean"><o:p> </o:p>

 <o:p> </o:p>

   <property        name="name" > <o:p></o:p>

       <value>tom</value><o:p> </o:p>

   </property><o:p> </o:p>

 <o:p> </o:p>

</bean><o:p> </o:p>

 <o:p> </o:p>

The subelement <value> sets the 'name' property by calling the set method as <o:p></o:p>

setName("tom"); This process is called setter injection.<o:p> </o:p>

For constructor injection, we use constructor with parameters as shown below,<o:p> </o:p>

 public class namebean<o:p> </o:p>

{<o:p> </o:p>

     String name;<o:p> </o:p>

     public namebean(String a)<o:p> </o:p>

     {<o:p> </o:p>

        name = a;<o:p> </o:p>

     }    <o:p></o:p>

}<o:p> </o:p>

We will set the property 'name' while creatinf an instance of the bean 'namebean' as namebean bean1 = new namebean("tom"); <o:p></o:p>
 Here we use the <constructor-arg> element to set the the property by constructor injection as<o:p> </o:p>

 <bean id="bean1"  class="namebean"><o:p> </o:p>

    <constructor-arg><o:p> </o:p>

       <value>My Bean Value</value><o:p> </o:p>

   </constructor-arg><o:p> </o:p>

 <o:p> </o:p>

</bean><o:p> </o:p>

To set properties that reference other beans <ref>, subelement of <property> is used as shown below,<o:p> </o:p>

 <bean id="bean1"   class="bean1impl"><o:p> </o:p>

   <property name="game"><o:p> </o:p>

       <ref bean="bean2"/><o:p> </o:p>

   </property><o:p> </o:p>

</bean><o:p> </o:p>

<bean id="bean2"   class="bean2impl" /><o:p> </o:p>

 Aspect-Oriented Programming<o:p> </o:p>

---------------------------<o:p> </o:p>

 Aspect Oriented programming is a new <o:p></o:p>

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'. <o:p></o:p>

----------------------------------------<o:p> </o:p>

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.<o:p> </o:p>

BEAN FACTORY:<o:p> </o:p>
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.<o:p> </o:p>

There are several implementation of BeanFactory. The most useful one is "org.springframework.beans.factory.xml.<o:p> </o:p>
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.<o:p> </o:p>
BeanFactory  factory = new XmlBeanFactory(new FileInputStream("myBean.xml"));<o:p> </o:p>

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. <o:p></o:p>

 <o:p> </o:p>myBean bean1 = (myBean)factory.getBean("myBean");<o:p> </o:p>

<o:p></o:p>APPLICATION CONTEXT:<o:p> </o:p>
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. <o:p></o:p>

It also provide <o:p></o:p>
1) a means for resolving text messages, including support for internationalization.<o:p> </o:p>
2) a generic way to load file resources.<o:p> </o:p>
3) events to beans that are registered as listeners.<o:p> </o:p>

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 <o:p></o:p>

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<o:p> </o:p>
ApplicationContext    context = new ClassPathXmlApplicationContext("bean.xml");<o:p> </o:p>

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<o:p> </o:p>
ApplicationContext    context = new FileSystemXmlApplicationContext("bean.xml");<o:p> </o:p><o:p></o:p>

3. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.<o:p> </o:p>
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. <o:p></o:p>

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.<o:p> </o:p>

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. <o:p></o:p>

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<o:p> </o:p>to us.<o:p> </o:p>
With this inroduction, we shall see a simple example in Spring in next article.<o:p> </o:p>

-------------------------------------------<o:p> </o:p>

 <o:p> </o:p>BOOKS FOR REFERENCE:<o:p> </o:p>

1.'Spring in Action' - Craig Walls and Ryan Breidenbach.<o:p> </o:p>

2.'J2EE Development without EJB' <o:p></o:p>

   - Rod Johnson<o:p>

</o:p>
分享到:
评论

相关推荐

    Manning.Spring.in.Action.4th.Edition.2014.11.epub

    15.1. An overview of Spring remoting 15.2. Working with RMI 15.2.1. Exporting an RMI service 15.2.2. Wiring an RMI service 15.3. Exposing remote services with Hessian and Burlap 15.3.1. Exposing bean ...

    Apress.Introducing.Spring.Framework.A.Primer.

    This book is an introduction to the well-known Spring Framework that offers an inversion of control container for the Java platform. The Spring Framework is an open source application framework that ...

    Spring.MVC.Beginner's.Guide.2nd.Edition.2016.7.pdf

    It begins with an introduction to the Spring development environment and architecture so you’re familiar with the know-hows. From here, we move on to controllers, views, validations, Spring Tag ...

    Cambridge.University.Press.Netowrking.Coding.An.Introduction.Apr.2008

    《网络编码:一种新兴通信技术的全面介绍》 在当今高度互联的世界中,网络编码(Network Coding)作为一种新兴的通信技术,正逐步改变着我们对通信网络的理解与设计方式。本书《网络编码:一种全面的介绍》由加州理工...

    spring-framework-reference-4.1.2

    4.1. Introduction to the Spring IoC container and beans .............................................. 22 4.2. Container overview .........................................................................

    spring-framework-reference4.1.4

    4.1. Introduction to the Spring IoC container and beans .............................................. 22 4.2. Container overview .........................................................................

    Spring.Boot.in.Action.2015.12.pdf

    Spring Boot in Action is an easily readable book, as weve now come to expect from Craig and manning From chapter Is attention-getting introduction to Boot and the now legend ary 9Oish-character ...

    Packt.Learning.Spring5

    Beginning with an introduction to Spring and setting up the environment, the book will teach you in detail about the Bean life cycle and help you discover the power of wiring for dependency injection....

    An Introduction To Ajax

    在"An Introduction To Ajax"的主题中,提到了"DWR-SPRING DEMO",这表明我们将讨论如何将DWR与Spring框架集成。Spring是一个强大的企业级Java应用框架,提供了丰富的功能,包括依赖注入、面向切面编程以及对Web应用...

    《activmq in action 》

    An Introduction to Messaging and ActiveMQ ............................................. 1 1. Introduction to Apache ActiveMQ ....................................................... 2 1.1. What is ...

    mastering-spring-cloud2018

    used as an API gateway and proxy for Spring Cloud applications: Spring Cloud Netlix Zuul and Spring Cloud Gateway. You will learn how to integrate them with service discovery and create simple and ...

    Learn Microservices with Spring Boot

    Build a microservices architecture with Spring Boot, by evolving an application from a small monolith to an event-driven architecture composed of several services. This book follows an incremental ...

    An Introduction to Hopf Algebras:Robert G. Underwood

    《An Introduction to Hopf Algebras》是由著名数学家Robert G. Underwood撰写的一部关于Hopf代数的入门级著作。这本书以其清晰的论述和深入浅出的讲解,为读者提供了一个理解Hopf代数理论的理想起点。Hopf代数在...

Global site tag (gtag.js) - Google Analytics