Introducing to Spring Framework

xiaoxiao2021-03-06  46

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, it does not require EJB container Spring's transaction abstraction, which is not bound 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 key AOP concepts that are supported include:

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: org.springframework.beans.ITestBean < Property name = "interceptornames"> txinterceptor target Note that the definition of the Bean class is always the ProxyFactoryBean of the AOP framework. Although the type of bean is used in the reference or by BeanFactory's getBean () method, it is dependent on the proxy interface. (Multiple proxy methods are supported.) The "interceptorNames" property of ProxyFactoryBean requires a list of strings. (Because if the agent is a "prototype" instead of Singleton, state Interceptors may need to create a new instance, so you must use the name of the BEAN instead of the reference.) The name in the list can be Interceptor or Pointcuts (Interceptors and related them) Suitable information is used). The "Target" value in the list automatically creates an "Invoker Interceptor" package Target object. Implementing the agent interface is the name of the bean in Factory. The MyTest in this example can be used as Bean in other bean factory. For example, other objects can reference it using the element and these references are set by Spring IoC. You can also do BeanFactory, programming constructs AOP proxy, although this hardly ever use: 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 automatically added to wrap the target ity TB = (itembean) Factory.getProxy (); we believe the most It is better to remove the program from the 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.

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. Use EJB Spring to make EJB easier. Many EJB procedures use Service Locator and Business Delegate mode. These are much more than the JNDI in the customer code, but their common implementations have significant shortcomings, such as:

Typical code using EJB relies on Service Locator or Business Delegate Singletons to make tests difficult to do. 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 save the reference as an instance variable as follows:

Code: private mycomponent mycomponent; public void setMycomponent (mycomponent mycomponent) {this.mycomponent = mycomponent;} We subsequently 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: myComponent com.mycom.mycomponent There are many magical things behind the scenes, and the Spring AOP Framework is attentive, although not forced you to use the concept of AOP to enjoy these results. "MyComponent" bean is defined for EJB to create a proxy, which implements the interface of the business method. EJB Local Home is cached when started, and thus only need JNDI lookup. When EJB is called, the agent calls the CREATE () method in the LOCAL EJB and calls the corresponding business method in the EJB. MyController bean defines the MyController property of the Controller class for this proxy. This EJB access mechanism greatly simplifies the code of the application: The code of the web layer does not depend on EJB. If you want to use Pojo, Mock Object, or other Test Stub replace EJB reference, we can simply change the MyComponent Bean definition without affecting a line of Java 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.

转载请注明原文地址:https://www.9cbs.com/read-81258.html

New Post(0)