Introducing to Spring Framework
Author: Rod Johnson
Translator: Yanger, Taowen
School: taowen
About Spring Framework, you may have heard a lot of discussions this summer. 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, for example:
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. JDBC Abstract and Data Storage Exception Hierarchical Data Access is another flash point of Spring. JDBC provides a good database abstraction, but it needs to use painful API. These issues include:
Requires lengthy error handling code to ensure that ResultSets, Statements, and (most important) Connections are closed after use. This means that the correct use of JDBC can quickly lead to a large amount of code. It is still a common incorrect source. The Connection Leak can quickly drop out the application with a load.
SQLException is relatively confirmed to explain any problems. JDBC does not provide an abnormal level, but uses throwing SQLException to respond to all errors. Find out where to go wrong - for example, the problem is deadlock or invalid SQL? - To check SQLSTATE or error code. This means that these values are varied between the database.
Spring solves these problems in two ways:
Provides an API to move lengthy and easily error-proof from program code to the framework. The framework processes all exception handling; program code can focus on writing appropriate SQL and extract results.
Provide a meaningful exception level for you to handle the SQLException program code. When Spring acquires a connection from the data source, it checks metadata to determine the database. It uses this information to map SQLException to yourself from org.springframework.dao.DataAccessException. The correct exception is derived. Therefore, your code can be deal with meaningful exceptions and do not need to worry about private SQLSTATE or error. Spring's data access is not a JDBC unique, so your DAO does not necessarily be tied to JDBC because they may thrown an exception.
Spring provides two JDBC APIs. In the first one, in the org.springframework.jdbc.core package, the callback mechanism is used to move control - and thus the error handling and connection acquisition and release - from the program's code to the frame. This is a different Inversion of Control, but almost importantly equally important for configuration management. Spring uses similar callback mechanisms to follow other APIs that include special acquisition and cleanup resource steps, such as JDO (acquisition, and release are completed by PersistenceManager), transaction management (using JTA) and JNDI. These callbacks in Spring are called Template. For example, Spring's JDBCTemplate object can be used to perform SQL queries and save results in the following list: JDBCTemplate Template = new jdbcTemplate (Datasource); Final List name = new linkedList (); template.query ("SELECT User.Name "From user", new rowcallbackhandler () {public void processrow (ResultSet RS) throws sqlexception {names.add (rs.getstring (1));}}); pay attention to the program code in the callback is free to throw SQLException: Spring These exceptions will be captured and resolved with their own class levels. The developer of the program can choose which exception, if any, captured and then processed. JDBCTemplate provides a number of methods that support different scenarios include prepared statements and bulk updates. Spring's JDBC abstraction is very small than standard JDBC, and even when the result set is large when the application needs. In the org.springframework.jdbc.Object package is a higher level of JDBC. This is the API that is built on the core of the JDBC callback function, but provides an API that can be modeled to RDBMS - whether queries, updates, or stored procedures - using Java objects. This API part is affected by the JDO query API, I found it intuitively and useful. A query object for returning a User object may be like this:
Code: class UserQuery extends MappingSqlQuery {public UserQuery (DataSource datasource) {super (datasource, "? SELECT * FROM PUB_USER_ADDRESS WHERE USER_ID ="); declareParameter (new SqlParameter (Types.NUMERIC)); compile ();} // Map a result set row to a Java object protected Object mapRow (ResultSet rs, int rownum) throws SQLException {User user = new User (); user.setId (rs.getLong ( "USER_ID")); user.setForename (rs.getString ( "Forname"); return user;} public user finduser (}) {// use superclass communication method method to provide strong typing return (user) FindObject (ID);}} This class can be used below: Code: User User = UserQuery.FindUser (25); such objects can often be used as a DAO's Inner Class. They are thread safety, unless the child has some things that exceed regular. Another important class in the org.springframework.jdbc.Object package is the StoredProcedure class. Spring allows the storage process to proxy by Java classes with a business method. If you like, you can define an interface implemented by a stored procedure, meaning that you can complete your program code from the depends on the stored procedure. Spring Data Access Exception hierarchy is unchecked (running) Exception. After using Spring in several projects, I am more confident that this decision is correct. Data Access Exceptions are generally unrecoverable. For example, if we can't link to the database, a business object is likely to complete the problem to be solved. A possible exception is Optimistic Locking Violation, but not all programs use Optimistic Locking. Forced writing to capture the fatal anomalies that cannot be effectively processed are usually not good. Let them spread to the upper Handler, such as servlet or EJB containers are usually more appropriate. All Spring objects Access exceptions are subclasses of DataAccessException, so we can easily do this if we do have selected all Spring data access to exceptions. Note If we do need to recover from unchecked data access, we can still do this. We can write code only to process recoverable situations. For example, if we think that only Optimistic Locking Violation is recoverable, we can write like this in Spring's DAO:
Code: try {// do work} catch (OptimisticLockingFailureException ex) {// i 'inTED in this} If Spring's data access is checked, we need to write the following code. Note that we can still choose this:
Code: try {// do work} catch (OptimisticLockingFailureException EX) {// i i in inTED in this} Catch (dataaccessException ex) {// Fatal; Just Rethrow It} The potential defect of the first example is - Compiler It is not possible to force handling possible recoverable abnormalities - this is true for the second one. Because we are forced to capture Base Exception (DataAccessException), the compiler does not force the OptiSticLockingFailureException check. Therefore, the compiler may force us to write code that handles unrecoverable issues, but there is no help to force us to handle recoverable issues. Spring UNECKED uses and many of the data access exception - may be mostly - successful persistence frames. (Indeed, it is affected by JDO.) JDBC is one of several fewer data accessing APIs using Checked Exception. For example, Toplink and JDO use unchecked Exception. Gavin King now believes that Hibernate should also choose to use Unchecked Exception. Spring's JDBC can help you with the following measures: You must never need to write Finally Block when using JDBC.
In general, you need to write less code.
You never need to dig your RDBMS document to find a rare error code that it returns to the wrong column name. Your program no longer rely on RDBMS unique error handling code.
No matter what persistence technology is used, you will find that the DAO mode is easy to implement, so that the business code does not need to rely on any specific data access API.
In practice, we found that all of this does contribute to the increase of productivity and less bugs. I have often dismused the JDBC code in the past; now I find that I can concentrate on the SQL I want to perform, not an annoying JDBC resource management. If you need, Spring's JDBC abstraction can be used independently - do not force you to use them as part of Spring. O / R mapping integration Of course, you often need to use O / R mapping instead of using relational data access. Your overall application framework must also support it. Therefore, integration support for Hibernate 2.x and JDO is provided. Its data access architecture enables it to integrate with any underlying data access technology. Spring and Hibernate are integrated. Why do you want to use Hibernate plus spring instead of using hibernate?
Session Management Spring provides efficient, simple and secure processing of Hibernate Session. The same hibernate "session" object is usually used for efficiency and proper transaction processing. Spring makes it easy to create and bind session to the current thread, either use declarative, AOP's Method Interceptor method, or use explicit, "template" package class in the Java code level. So Spring solves usage problems that often appear on the Hibernate forum.
Resource Management Spring Application Context can handle the location and configuration of Hiberante SessionFactories, JDBC data sources, and other related resources. This makes these values to manage and change.
The integrated transaction management Spring allows you to pack your Hibernate code, either use the declarative, AOP style Method Interceptor, or explicitly use the "Template" package class at the Java code level. In both practices, business semantics are handled for you, and it is also a proper transaction (rollback, etc.) when an exception. As discussed below, you have also obtained the ability to use and replace different Transaction Manager without allowing you of the Hibernate code to be affected. Additional, JDBC-related code is fully transactional and Hibernate code integration. This is useful for handling the features that have not been implemented in the Hibernate. The exception packaging as described above can package Hibernate anomalies, and convert them from private, Checked exceptions into a set of abnormal runtime exceptions. This allows you to handle most of the unrecoverable persistence exceptions only in the appropriate level, without affecting the template Catch / Throw, and exception declarations. You can still capture and process anomalies in any where you need. Remember that JDBC exceptions (including DB-specific dialects) are also converted to the same level, meaning that you can perform the same operations in the same programming model.
To avoid and manufacture, Hibernate is powerful, flexible, open source and free, but it still uses private APIs. Some options are given, using standard or abstract API implementation of primary programming is usually what you want, when you need to convert to other implementations due to functionality, performance, or other considerations to use other implementations.
Let the test simple Spring Inversion Of Control method make it easy to change Hibernate's session factories, data sources, and transaction manager's implementation and location. If desired, you can change the implementation of Mapper Object. This makes it easier to isolate and test the code-related code.
Transaction management Abstract API has an API of a data access; we also need to consider transaction management. JTA is an obvious choice, but it is a very cumbersome API, so many J2EE developers feel EJB CMT is the only reasonable choice for transaction management. Spring provides its own abstraction of transaction management. Spring provides these:
By programming management transactions with a callback template similar to JDBCTemplate, it is easy to use JTA directly.
Similar to the declarative transaction management of EJB CMT, but does not need EJB container
Spring's transaction abstraction is unique, it does not bind to JTA or any other transaction management technology. Spring uses the concept of transaction policing to solve the program code and the underlying transaction architecture (such as JDBC). Why do you want to care about it? Is JTA not the best answer to all transaction management? If you are writing only programs that only use a database, you don't need a complexity of JTA. You don't care about the XA transaction or two phases. You don't even need to provide high-end application servers for these things. But on the other hand, you will not want to override your code when you need to deal with multiple data sources. Assume that you decide to avoid the additional burden brought by JTA by directly using JDBC or Hibernate. Once you need to handle multiple data sources, you must strip all transaction management code and use JTA transactions to replace. This is not very attractive and leads most J2EE programmers, including myself, it is recommended to use global JTA transactions. However, use Spring transactions, you only need to reconfigure Spring to make it use JTA, rather than JDBC or Hibernate transaction strategy, everything is OK. This is a change in configuration, not the change of the code. Thus, Spring makes you free to zoom your application.
AOP has recently applied AOP to solve a lot of interest in business concerns, such as transaction management, these are EJBs to solve. The primary goal of Spring's AOP support is to provide J2EE services to Pojos. This is similar to the Target of JBoss 4, and the Spring AOP is capable of transplanting the application server, so that there is no risk that is tied to the manufacturer. It can be used either in a web or EJB container, and can be used on WebLogic, Tomcat, JBoss, Resin, Jetty, Orion, and many other application servers and web containers. Spring AOP supports Method Interception. The support key AOP concept includes: Interception: Custom behavior can be inserted before and after the call to the interface and class. This is similar to similar "around advice" in AspectJ terms.
Introduction: Specifies Advice to cause an additional interface to be implemented. This confusing inheritance.
Static and dynamic PointCuts: Specify Points at the program execution of Interception. Static PointCuts Concern function signature; dynamic PointCuts can also consider the parameters of the function in a place where Point is evaluated. PointCuts Independent Interceptors separately defines that standard Interceptor can be applied to different applications and code contexts.
Spring supports both state (an instance of an Advised Object) also supports state-free Interceptors (all Advice uses an instance). Spring does not support Field Interception. This is a well-thoughtable design decision. I always feel Field Interception violates the package. I tend to take AOP as a full object, not something conflict with OOP. If in 5 years or 10 years, we have walked farther on the AOP learning curve and feel that you should give AOP a location on the desktop designed, I will not be surprised. (However, in that time-based solution examples, aspectj may be more attractive than they seem to be more attractive today.) Spring uses dynamic proxy to implement AOP (where there is an interface) or use CGLIB to generate one by section code when running (this makes it possible Agent class). Both methods can be used in any application server. Spring is the first AOP frame (www.sourceforge.net/projects/aopalliance) that implements AOP Alliance Interfaces. These are attempts that define interceptors that are interceptors that can intercept interceptors in different AOP frames. There is a matter of THESERVERSIDE and other places, but not so fascinating, this interception is "True AOP". I don't care about it. I just need to know if it is useful in practice. I am also here to call it "Declarative MiddleWare" (declared middleware). The Spring AOP recognizes the alternative to simple, lightweight stateless beans, which does not require Monolithic EJB containers, and these are only allowed to build containers with the services you need. I don't recommend any Pojo, which helps you understand the recommended granularity than the class of Local Slsbs. (However, unlike EJB, in the appropriate but rare case, you can freely apply Spring's AOP to a better granularity.) Because Spring is an Advises object on an instance, not on the Class Loader level. Multiple instances using the same class with different advice are possible, or use the unadvised instance with the Advised instance. Maybe Spring AOP is most common is to declare transaction management. This is based on the top-described TansActionTemplate abstraction and can provide declarative transaction management to any Pojo. Depending on the transaction strategy, the underlying mechanism can be JTA, JDBC, Hibernate, or any other API that provides transaction management. Spring's declarative transaction management is similar to EJB CMT, some of which are different: transaction management can be applied to any Pojo. We recommend business objects to implement interfaces, but this is just a good program habit, not by the framework.
Programming callbacks can be implemented in transactional POJO by using Spring's transaction API. We provide static methods for this purpose, using Threadloacal variables, so you don't need to spread Context objects such as ejbcontext to ensure rollback.
You can declare "rollback rules". EJB does not automatically roll back when unusually captured an exception (only when unchecked exceptions and other throwables), application developers often need to roll back when any exception occurs. Spring transaction management allows you to declare what abnormality can cause automatic rollback. The default behavior and EJB are consistent, but you can automatically roll back when checking and unchecked exceptions. This has a great advantage in the least programming callback code, and the callback depends on Spring's transaction API (completed in EJBCONTEXT when ejb programming callback). Transaction management is not bound to JTA. As explained earlier, Spring's transaction management can be used in different transaction strategies.
Of course, you can also use the Spring AOP to implement procedures unique aspect. Depending on your level of acceptance of the AOP concept, decide if you choose to do this, not the ability of Spring, but it is really useful. The success of the success we have ever seen includes:
Custom security interception, when the complexity of security check is exceeded by the ability of J2EE security architecture
Debugging aspects used in development
Send an email notification Administrator user unusual move interceptors
Program Customed Aspects can be an advantageous weapon that eliminates template code that requires many functions. Spring AOP is integrated with Spring BeanFactory concept. Contains a code from the Spring BeanFactory object where it is still not an advised. Like any object, the contract is defined in the interface and object implementation. The following XML fragment shows how to define an AOP proxy:
Code:
Code: TestBean target = new TestBean (); DebugInterceptor di = new DebugInterceptor (); MyInterceptor mi = new MyInterceptor (); ProxyFactory factory = new ProxyFactory (target); factory.addInterceptor (0, di); factory.addInterceptor (1, Mi); // An "invoker interceptor" IS Automatic Or Added to Wrap the Target ITESTBEAN TB = (iTestBean) Factory.getProxy (); We believe it is best to shift program assembly from Java code, and AOP is no exception. Spring's direct competitor in its AOP capabilities is Jon Tirts Nanning aspects (http://nanning.codehaus.org). I think AOP is important as EJB's alternative to providing business services. Over time, this will become a very important focus of Spring. The MVC Web Framework Spring includes a powerful and highly configurable MVC web framework. Spring MVC Model is similar to Struts. At multi-threaded service objects, Spring's Controller is similar to Struts Action, and only one instance processes the request of all customers. However, we believe that Spring has many advantages compared to Struts, for example: Spring provides a very clear division in Controllers, JavaBean, Models, and Views.
Spring's MVC is very flexible. Unlike struts, it enforces your Action and Form objects into the cured level (so you forcing you to use Java's entity), Spring MVC is completely interface-based. Moreover, all parts of almost Spring MVC frames are configurable by inserting into your own interface. Of course, we also provide a convenient class as an implementation choice.
Spring MVC is true for real view. You will not be enforced using JSP, if you don't want to do it so much. You can use Velocity, XSLT, or other View technology. If you want to use a custom View mechanism - for example, your own template language - you can simply implement the spring View interface and integrate it.
Like other objects, Spring Controllers are configured through IOC. They make them easy to test, and perfectly and other objects managed by Spring.
The web layer has become a thin layer of the business object layer. This encourages good habits. Struts and other specialized web frameworks let you implement your own business object; Spring provides integration of all layers of your application.
As seen in Struts 1.1, you can have the same more Dispatcher Servlets as you need in the Spring MVC application. The following example shows how a simple Spring Controller can access the business object defined in the application Context. This Controller executes Google Search in its handleRequest () method:
Code: public class GoogleSearchController implements Controller {private IGoogleSearchPort google; private String googleKey; public void setGoogle (IGoogleSearchPort google) {this.google = google;} public void setGoogleKey (String googleKey) {this.googleKey = googleKey;} public ModelAndView handleRequest ( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String query = request.getParameter ( "query"); GoogleSearchResult result = // Google property definitions omitted ... // Use google business object google.doGoogleSearch (this.googleKey, query START, MAXRESULTS, FILTER, RESTRICT, SAFESEARCH, LR, IE, OE); Return New ModelandView ("GoogleResults", "Result", Result);}} In the prototype used by this code, Igooglesearchport is a Glue Web Services Agent Returns Spring FactoryBean. However, Spring separated the Controller from the underlying Web Service library. The interface can be implemented using a normal Java object, Test Stub, Mock object, or the EJB proxy as discussed below. This contORLER does not include resource search; there is nothing else except for the necessary code to support its web interaction. Spring also provides support for data binding, Forms, Wizards, and more complex workflows. Excellent introduction to the Spring MVC framework is the Spring MVC tutorial of Thomas Risberg (http://www.springframework.org/docs/mvc-step-book-step/spring-mvc-step-cy-step.html). You can also see "Web MVC with the Spring Framework" (http://www.springframework.org/docs/web_mvc.html). If you are happy to use your favorite MVC framework, Spring hierarchical architecture allows you to use other parts of Spring without the MVC layer. We have the use of Spring to do intermediate layer management and data access, but users using Struts, Webwork, or Tapestry in the web layer. Implementing EJB If you choose to use EJB, Spring can provide a lot of benefits in both EJB implementation and client access EJB. Reconstructing business logic and takes it from EJB FACADES to POJO has been widely recognized.
(Do not talk about, this makes the business logic easier unit test because EJB is seriously reliable and it is difficult to isolate tests.) Spring provides convenient superclars for Session Bean and Message Driver Beans, making it based on automatic load based on included The XML document in the EJB JAR file beanfactory makes this easy. This means that the stateless session EJB can be obtained and used so desired objects: Code: import org.springframework.ejb.support.AbstractStatelessSessionBean; public class MyEJB extends AbstractStatelessSessionBean implements MyBusinessInterface {private MyPOJO myPOJO; protected void onEjbCreate () {this.myPOJO = GetBeanFactory (). getBean ("mypojo");} public void mybusinessMethod () {this.mypojo.invokeMethod ();}} Assume mypojo is an interface, its implementation class - and any configuration it needs, injecting basic Properties and more collaborators - Hide in the XML Bean Factory definition. We tell Spring where to load an XML document by the environment variable definition in EJB-JAR.XMLDEPLOYMENT DESCRIPTOR named EJB / BeanFactoryPath. as follows:
Code:
In the case where the Service Locator mode does not use Business Delegate, the program code also calls the create () method in the EJB Home, and processing the exception that may result. Therefore, it is still bound to the EJB API and endure the complexity of the EJB programming model.
Implementing business delegate mode usually results in a significant code repetition, where we must write a large number of methods for calling EJB equivalents.
Based on these and other reasons, traditional EJB access, as shown in Sun Adventure Builder and OTN J2EE Virtual Shopping Mall, which will reduce productivity and bring significant complexity. Spring has stepped by introducing Codeless Business Delegate. With Spring, you no longer need to write another Service Locator, another JNDI lookup, or repeat code in hardcoded business delegate, unless you affirms this to increase value. For example, suppose we have Web Controller using Local EJB. We will follow best practices, use the EJB Business Methods Interface mode, EJB's local interface extend non-EJB proprietary business method interface. (One reason for this is to ensure automatic synchronization of the signature of the local interface and the bean implementation class.) Let us call this business method interface MyComponent. Of course, we also need to implement the Local Home interface and provide the implementation class for Beans to implement the sessionBean and MyComponent business methods. With Spring EJB access, we use our web layer Controller and EJB to hook the Java encoding you need to be on our Controller to expose a Type MyComponent's setter method in our Controller. This will be saved as an instance variable: code: private mycomponent mycomponent; public void setMycomponent (mycomponent mycomponent) {this.mycomponent = mycomponent;} We will then use this instance variable in any business method. Spring automatically refers to the remaining work, defined like this XML bean. LocalStateLessSessionProxyFactoryBean is a universal Factory Bean that can be used for any EJB. It creates objects can be automatically transformed into MyComponent types being transformed by Spring.
Code:
We still don't need to write a row of JNDI to find or other EJB Plumbing Code.
Performance testing and experience in actual procedures indicate that the performance impact of this method (including the reflection of the target EJB) is small, and can't be detected in a typical application. Remember that we don't want to use the Fine-grained EJB call because there will be the price of the underlying architecture of EJB on the application server. We can apply the same way to remote EJB, through similar org.springframework.ejb.access.simpleremotestatelessSessionProxyFactoryBean Factory Bean method. However, we cannot hide the RemoteException in the business method interface of remote EJB.
Test if you might have noticed, I have developed a firm supporter of the importance of the comprehensive unit test. We believe that the framework is thoroughly tested is very important, and the main goal of our frame design is to make the program built on the frame to easily test. Spring itself has an excellent unit test package. Our 1.0 m1 unit test coverage is 75%, and we want to reach 80% of the unit test coverage when 1.0 RC1. We found that the benefits of testing priorities in this project are real. For example, it makes extremely efficient as an international distributed development team, and user reviews CVS Snapshots tend to stabilize and use security. Because of the following reasons, we believe that the application built by Spring is very easy to test:
IOC promotes unit testing
The application does not include Plumbing Code that directly uses J2EE services that inject JNDI, which generally makes tests in Spring Bean Factories and Contexts to be able to set up
The ability to set Spring Bean Factory outside the container provides an optional option for the development process. In several ways of using Spring, work is starting from the defined service interface and starting with external integration of Web containers. After the business function is complete enough, the web interface is only the thin layer added thereon.
Who is using Spring Although Spring is still a new project, we already have an impressive and growing user base. They already have many products to use Spring. Users include a major global investment bank (made large projects), some well-known network companies, several web development consultants, health care companies, and college institutions. Many users use Spring intact, but some components are only available. For example, a large number of users use our JDBC or other data access functions. Roadmap we mainly do this year later is to let Spring release Release 1.0. However, we have some longer-term goals. For 1.0 final plan, mainly improved source code grade data support, which is mainly used (but not limited to) AOP framework. This will make the C # style Attribute driven transaction management, and make the declarative enterprise services are very easy to configure in typical applications. Attribute support will be added in Spring 1.0 Final Release support, and designed to integrate with JSR-175 at that time of publishing. 1.0, some possible improvements include:
Support JMS by a fairly abstraction supporting our JDBC and transaction support
Support for the dynamic reproduction of Bean Factories
Provide Web Services
IDE and other tools support
As an agile project, we are mainly driven by user needs. Therefore, we will not develop a feature that does not have a user needs, and we will carefully listen to the sound from the user group.
Summary Spring is a powerful framework that solves many problems in J2EE development. Spring provides a consistent way of managing business objects and encourages the injection of interface programming rather than a good habit of programming. Spring's architecture basis is based on Inversion of Control containers using the JavaBean property. However, this is just part of the full picture: Spring is unique in using IOC containers as a complete solution to all architectural layers. Spring provides unique data access abstraction, including simple and efficient JDBC frameworks, greatly improved efficiency and reduces possible errors. Spring's data access architecture also integrates Hibernate and other O / R mapping solutions. Spring also provides unique transaction management, which provides a consistent programming model in various underlying transaction management technologies, such as JTA or JDBC paper. Spring provides a AOP framework written in standard Java language, which provides POJOS with a declarative transaction management and other business transactions - if you need - you can implement your own aspects. This framework is strong enough to allow the application to thrush the complexity of EJB while enjoying key services related to traditional EJBs. Spring also provides a powerful and flexible MVC web framework that can be integrated with the overall IOC container.
For more information, see the following resources get more information about Spring:
Expert One-ON-One J2EE Design and Development (Rod Johnson, Wrox, 2002). Although Spring has greatly advanced and improved after book publishing, it is still an excellent way to understand the Spring motivation.
Spring Home: http://www.springframework.org. Here is Javadoc and several tutorials. Forum and download on SourceForge
Spring users and Spring developers' mailing list
We are doing our best to improve Spring documents and examples. We also proud to pride in the letter and email list. We hope that you can quickly integrate our community!
Regarding the author Rod Johnson has been developed as Java developers and architects and has been developed in the J2EE platform. He is the author of "Expert One-ONE J2EE Design and Development" (Wrox, 2002) and contributes some other books about J2EE. He is currently writing another book on the J2EE architecture for Wiley. Rod serves two Java Standards Committee and is often spokespersons. Now he is a consultant in UK.