Introducing to Spring Framework
Author: Rod Johnson Translator: yanger, taowen proof: taowen on Spring Framework, this summer you've probably heard a lot of talk. In this article, I will try to explain what Spring can do, and how can I think it can help you develop J2EE applications. Another Framework? You may be thinking "it is another Framework". When there are many open source (and proprietary) J2EE Framework, why do you want to be able to read this article or download Spring Framework? I believe that Spring is unique, several reasons:
It is concerned that many of the other popular Framework have not been concerned. Spring provides a way to manage your business objects.
Spring is both comprehensive and modular. Spring has a hierarchical architecture, which means that you can choose to use any of its separate parts, and its architecture is internally. So you can get the biggest value from your study. For example, you may choose to use Spring to simplify the use of JDBC, or to manage all business objects.
Its design is to help you write the code that is easy to test. Spring is an ideal framework for projects using test-driven development.
Spring will not give your project to other framework dependencies. Spring may be called a one-stop solution that provides most of the infrastructure required for typical applications. It also involves the content that other framework is not considered.
Although it is just an open source project starting from February 2003, Spring has a deep historical roots. This open source project is the basic code in the "Expert One-ONE J2EE Design and Development" book published in 2002. This book shows the basic architecture thought behind Spring. However, the concept of this infrastructure can be traced back to 2000, and reflects my successful experience in the development of a series of business engineering development.
In January 2003, Spring has settled in SourceForge. There are now 10 developers, 6 of which are highly investive active molecules.
Benefits on the Spring architecture
Before we enter the details, let's take a look at the benefits of Spring to the project:
Spring can effectively organize your intermediate object, whether you choose to use EJB. If you only use Struts or other API special Framework for J2EE, Spring is committed to resolving the remaining issues.
Spring can eliminate excessive use of Singleton in many projects. According to my experience, this is a big problem that reduces the system's testability and object-oriented level.
The configuration file is handled by a method between different applications and projects, and Spring can eliminate the needs of various custom formats. Once I have to find a certain type of property item or system attribute, I have to read Javadoc or even source coding for this? With Spring, you just need to see the JavaBean property of the class. Inversion of Control's use (discussed below) Help completed this simplification.
By reducing the interface of interfaces rather than the programming of the programming, Spring can facilitate developing good programming habits.
Spring is designed to let the app that use it to depends on his APIs as possible. Most business objects in Spring applications do not depend on Spring.
Applications built using Spring are easy to test.
Spring enables the use of EJBs into an implementation choice instead of the application architecture. You can choose to use Pojos or Local EJBS to implement the business interface, but it will not affect the call code.
Spring helps you solve many problems without using EJB. Spring provides an EJB replacement that is suitable for many web applications. For example, Spring can use AOP to provide declarative transaction management without passing the EJB container, if you only need to deal with a single database, don't even need a JTA implementation. Spring provides a consistent framework for data access, whether JDBC or O / R mapping products (such as hibernate) are used.
Spring does allow you to solve your problem through the simplest solution. And this is very value.
What did Spring do?
Spring provides a number of features, here I will quickly show all major aspects.
mission details
First, let us clarify the Spring range. Although Spring covers many aspects, we should have a clear understanding of it.
The main purpose of Spring is to make J2EE easy to use and promote good programming habits.
Spring does not renew the wheel. Therefore, you found that there is no logging in Spring, no pool, no distributed transaction scheduling. All these things have open source projects (for example, we are used to handle all log outputs of Commons Logging and Commons DBCP), or provided by your application server. For the same reason, we did not provide an O / R mapping layer. For this issue, there is already an excellent solution like Hibernate and JDO.
Spring's goal is to make existing technologies more easily. For example, although we don't have underlying transaction coordination, we provide an abstract layer to cover JTA or any other transaction strategy.
Spring does not compete with other open source projects unless we feel that we can provide new things. For example, like many developers, we have never been happy to Struts, and feel that there is room for improvement in MVC Web Framework. In some areas, such as lightweight IOC containers and AOP frameworks, Spring does have direct competition, but there is no more popular solutions in these areas. (Spring is a pioneer in these areas.)
Spring is also benefited from intrinsic consistency. All developers are singing the same praise song, the basic idea is still similar to the design and development of Expert One-ON-One J2EE. And we have been able to use some central concepts in multiple fields, such as Inversion of Control.
Spring is portable between the application server. Of course, it is always a challenge to ensure that portability is always a challenge, but we avoid using any platform unique or non-standard, and support users on WebLogic, Tomcat, Resin, JBoss, WebSphere, and other application servers.
Inversion of Control container
The core of Spring is org.springframework.beans package, which is designed to work with Javabeans. This package is generally not directly used by users, but is the basis for many other functions.
The next level is highly abstract "bean factory". A Spring Bean Factory is a universal Factory that enables objects to be obtained by name, and can manage the relationship between objects.
Bean Factories supports two modes:
Singleton: In this mode, there is a shared object instance with a specific name, which is obtained when looking up. This is the default, and it is most often used. It is an ideal pattern for stateless objects.
Prototype: In this mode, a separate object will be created each time you get. For example, this can be used to allow users to have their own objects.
Because org.springframwork.beans.Factory.BeanFactory is a simple interface, it can be implemented by a large number of underlying storage methods. You can easily implement your own BeanFactory, although few users need to do this. The most commonly used BeanFactory definition is: XMLBeanFactory: An XML structure that can be parsed simple and intuitive definition classes and named object properties. We provide a DTD to make the writing easier.
ListableBeanFactoryImpl: Provides the ability to prepare bean definitions stored in the properties file and create BeanFactories by programming.
Each bean definition may be a pojo (definition by class name and JavaBean initial attribute) or a FactoryBean. A indirect layer has been added to the FactoryBean interface. Typically, this is used to create a proxy object using AOP or other methods: for example, add a proxy for declarative transaction management. (This is similar to the interception of EJB, but it is easier.)
BeanFactories can selectively participate in a hierarchy, inheriting the definition of Ancestor (ancestor). This makes sharing of public configuration throughout the application possible, although individual resources, such as Controller Servlets, also have their own independent object collections.
This use of JavaBeans's motivation in Chapter 4 of "Expert One-ONE J2EE Design and Development" has a description, with a free PDF version on the THESERVERSIDE website (http://www.theserverside.com/resources/ Article.jsp? l = rodjohnsoninterView).
With the BeanFactory concept, Spring becomes an inversion of control container. (I don't like the word Container because it makes people think of the weight-reserved container, such as the EJB container. Spring BeanFactory is a container created by a line of code and does not require special deployment steps.)
The concept behind Inversion of Control is often expressed as Hollywood Principles: "Don't call me, I'll Call you." IoC moves the role of control into the framework and remove it from the application code. Where the configuration is involved, it means that in the traditional container architecture, such as EJB, one component can call the container and ask "Where do I need it to do the object X?"; Use IOC container only need to point out Components require X objects, which will be provided to it at runtime. The container is done by viewing the parameter table of the method (for example, the attribute of JavaBean), or may be based on the configuration data such as XML.
IOC has several important benefits, such as:
Because components do not need to find collaborators at runtime, they can write and maintain more easily. In the Spring version of IOC, components express their dependence on other components that expose JavaBean's setter method. This is equivalent to finding the EJB to find through JNDI, and EJB looks out that the developer needs to write code.
The same reason is easier to test. The JavaBean property is simple, belonging to the Java core, and it is easy to test: only a self-contained JUnit test method is used to create objects and set related properties.
A good IOC implementation retains a strong type. If you need to use a universal factory to find a partner, you must turn the return result into the desired type by type conversion. This is not a big deal, but not anger. With IOC, you expressed strong type dependencies in your code, the framework will be responsible for type conversion. This means that the type mismatch will result in an error when the framework configuration is applied; in your code, you don't have to worry about the type conversion exception. Most business objects do not depend on the IOC container. This makes it easy to use legacy code, and it is easy to use objects or in the container or not in the container. For example, Spring users often configure the Jakarta Commons DBCP data source as a Spring Bean: No need to do any custom code to do this. We say that an IOC container is not invasive: use it does not make your code depend on its APIS. Any JavaBean can become a component in Spring Bean Factory.
Finally, it should be emphasized that IOC is different from the architecture of the traditional container, such as EJB, and the application code is minimized by the container. This means that your business object can potentially run on a different IOC frame - or in any frame - no change in any code.
In the experience of me and other Spring users, how to emphasize the benefits of IOC bring to the application code.
IOC is not a new concept, but it has just arrived at the J2EE group. There are some optional IOC containers such as Apache Avalon, Picocontainer and HiveMind. Avalon has never been very popular, although it is very powerful and has a long history. Avalon is quite heavy and complex, and it seems to be more invasive than the new IOC solution. PicoContainer is a lightweight and emphasizes the expression dependence of constructor rather than JavaBeaN properties. Unlike Spring, its design allows each type of object definition (probably because it rejects the limitations caused by metadata outside the Java code). Between Spring, PicoContainer, and other IOC Frameworks, see "The Spring Framework - A Lightweight Container" on the article Spring on http://www.springframework.org/docs/lightweight_container.html. This page contains links to the PicoContainer site.
Spring beanfactories is very lightweight. Users have successfully applied them in Applets and separate SWING applications. (They also work well in the EJB container.) There is no special deployment step and aware start-up time. This capability indicates that a container can immediately exert a very value at any level of the application.
The Spring BeanFactory concept always passes through Spring, and it is a key reason for Spring so inherent. In the IOC container, Spring is also unique, which uses IOC as the foundation concept throughout the entire feature-rich framework.
For use developers, most importantly, one or more beanfactory provide a defined business object layer. This is similar to the Local Session Bean layer, but is more simple than it. Unlike EJBs, the objects in this layer may be related, and their relationship is owned by their Factory management. There is a great definition of a clear business object layer to be a successful architecture.
Spring ApplicationContext is the sub-interface of BeanFactory, providing support for the following things:
Information lookup supports internationalization
Event mechanism, allow release of application objects and optional registration to receive events
Portable documents and resource access
XMLBeanFactory example
Spring users are typically configured in XML's "Bean Definition" file. Spring's XML bean defines the root of the document is the
J2EE Datasource
Use DataSource's DAO
Use DAO's business object during processing
In the following example, we use a BasicDataSource from the Jakarta Commons DBCP project. This class (like many other existing Class) can be simply applied in the Spring Bean Factory as long as it provides a JavaBean format configuration. The Close method that needs to be called when ShutDown can be registered via the Spring's Destroy-Method property to avoid BasicDataSource needs to implement any spring interface.
Code:
All properties we are interested in BasicDataSource are string types, so we use the
Code:
Code:
With this feature, Spring finds the DataSource property of the ExampleBusinessObject should be set to the DataSource implementation found in the current Beanfactory. In the current BeanFactory, an error will occur if the Bean of the required type does not exist or more than one. We still have to set an ExampleParam property because it is not a reference. AutoWire support and dependencies have just been added to Spring 1.0 M2 (to 10/20, 2003). All other features discussed herein are included in the current 1.0 m1 version. There is a great advantage that the management is shifted from the Java code than hard coding, as this can only change the XML file without changing a row Java code. For example, we can simply changing the MyDataSource's bean definition to reference different bean class to use other connection pools, or a data source for testing. The XML section becomes another, we can use Spring's JNDI Location FactoryBean to get a data source from the application server. Let us now take a look at the Java code of the business object in the example. Note that there is no dependence on Spring in the code listed below. Unlike EJB containers, Spring BeanFactory does not have invasive: you usually don't need hard coding for Spring in the application object. Code: public class ExampleBusinessObject implements MyBusinessObject {private ExampleDataAccessObject dao; private int exampleParam; public void setDataAccessObject (ExampleDataAccessObject dao) {this.dao = dao;} public void setExampleParam (int exampleParam) {this.exampleParam = exampleParam;} public void myBusinessMethod ( ) {// do stuff using dau}}
Note those Property Setter, which correspond to the XML reference in the bean definition document. These will be called by Spring before the object is used. These applications beans do not need to rely on Spring: they do not need to implement any spring interfaces or inherit the class of Spring. They only need to comply with JavaBeans's naming habits. It is very simple to reuse them outside the Spring application environment, for example in a test environment. It is only necessary to instantiate them with their default constructor, and set its properties by calling setDataSource () and setExampleParam (). If you want to create a line of code support, as long as you have a parametric constructor, you can freely define the constructor that requires multiple properties. Note that there is no declaration in the business interface will be used together will be used with the JavaBeaN property. They are a detail of implementation. We can "insert" different implementations with different bean properties without affecting the connected objects or calls. Of course, Spring XML Bean Factories have more features not described here, but you should make you feel some feelings. And, simple properties, properties of the Javabean property editor, Spring can automatically process Lists, Maps, and Java.util.properties. Bean Factories and Application Contexts are usually associated with a range defined by J2EE Server, for example:
Servlet Context .: In the Spring's MVC frame, each of the web applications containing Common Objects defines a Context with an application. Spring provides the ability to instantiate such context through the Listener or Servlet without the need to rely on the Spring's MVC framework, so it can also be used in Struts, WebWork, or other web frameworks. A servlet: Each servlet controller in the Spring MVC framework has its own application Context, derived from the root (full application range) application Context. It is also very expensive to achieve these in Struts or other MVC frameworks.
EJB: Spring provides convenient superclars for EJB, which simplifies the creation of EJB and provides a BeanFactory loaded from the XML document from the EJB JAR file.
Hooks provided by these J2EE specifications typically avoid using Singleton to create a bean factory. However, if we are willing to create a beanfactory with code, although there is no meaning. For example, we can create Bean Factory in the following three lines of code and get a reference to a business object:
Code: InputStream is = getClass () getResourceAsStream ( "myFile.xml"); XmlBeanFactory bf = new XmlBeanFactory (is); MyBusinessObject mbo = (MyBusinessObject) bf.getBean ( "exampleBusinessObject");
This code will be able to work outside of an application server: even does not depend on J2EE, because Spring's IOC container is pure Java.