Five reasons to love spring.

Source: Internet
Author: User
Tags anonymous versions advantage
About 2 years ago, I tried out the spring project highlighted on the hibernate site. I think it's like the old canoe mentioned above: it suits me just the same. For enterprise hard coding, Spring is so deeply rooted in my programming work that I use it as the theme of my 4th Java book, Spring:a Developer's notebook. In this article, I'll explain why.

  1.Spring offers a better advantage

In the river, I learned to use my waist and back to paddle more, because my arm muscles could not insist on rowing on the River all day. I became more efficient and I got better utilization. With Spring, I can make every line of code do more things. With spring, you can discover a number of additional tools, the biggest of which is persistence. The following is a method for Hibernate data Access objects:

Public List getreservations () {return gethibernatetemplate (). Find ("from reservation");

Notice what you don't see. There is no transaction processing here. Spring allows you to build configuration code to handle transactions. You do not have to manage resources by shutting down sessions. You do not have to make your own configuration. You do not have to manage exceptions at this level, because exceptions are unchecked. Be free to manage them in the most appropriate place. Here's another hibernate method that doesn't use spring:

Public List Getbikesoldway () throws Exception {List bikes = null; Session S = null;try {s = mysessionfactory.opensession (); bikes = S.find ("from Bike");} catch (Exception ex) {//handle Exception gracefully}finally {s.close ();} return bikes;

Spring provides you with a better advantage. With spring, you can write code more quickly and do less maintenance.

  2.Spring Support Pojo programming

After the EJB 2.x failed, we were looking for ways to express enterprise services without using clumsy models to invade each bean. Of course, we need transactions, security, persistence, and sometimes remote control. For EJBS, I have to learn a widely used API and work through new tools and deployment processes. I am a slave to the service provided by the container. With spring, I can choose my own service and persistence framework. I do Pojo programming and use configuration files to add Enterprise Services to them.

In the book "Spring:a Developer's Notebook", I built a rentabike application. I call my Pojo a hibrentabike, not a session bean or entity bean; it's used as my data access object. I also added a service elsewhere. The spring configuration file, called the context, is an XML file that contains all the beans in the container and the properties and services required by the bean. Let's take a look at the following.

Goal:

Bruce ' s Bikes

Intercepting device:

com.springbook.rentabike.transferreservation=propagation_required,- reservationtransferexceptioncom.springbook.rentabike.save*=propagation_requiredcom.springbook.rentabike.*= Propagation_required,readonly

Agent:

Com.springbook.rentabiketransactioninterceptor,rentabiketarget

Note that there are 3 different types of beans: agents, targets, and interceptors. The agent will invoke Pojo and any services required by Pojo. The interceptor contains a combination of code for invoking the service (glue code), and also specifies how to handle each method in the target. Anyone who needs access to rentabike invokes the proxy, and the broker invokes the transaction interceptor, and then the transaction interceptor starts a transaction and invokes the target (POJO). The target completes its work, returns it to the Interceptor (which is responsible for committing the transaction), and returns it to the agent and the agent's caller.

  

Figure 1: Pojo Programming in progress

You build and configure the program outside of Pojo, and the rest of the work is given to spring. I am a pojo programmer.

  3. Dependency Injection contributes to testability

With a design pattern called Dependency Injection (Dependency injection,di), spring greatly improves testability. When a customer relies on a dependency (which we will call a service), you create an attribute of the customer. Spring creates the customers and services, and then sets the customer's properties to the value of the service. In other words, Spring is responsible for managing the life cycle of the bean in the context and resolving dependencies. Here's an example of a dependency injection that doesn't use spring. Let's look at the customer first (the basic element of the application):

public class Commandlineview {private Rentabike rentabike;public Commandlineview () {rentabike = new Arraylistrentabike (" Bruce ' s bikes "); }public void Setrentabike (Rentabike rentabike) {this.rentabike = Rentabike;} public void Printallbikes () {System.out.println (rentabike.tostring ()); iterator iter = Rentabike.getbikes (). Iterator ( while (Iter.hasnext ()) {Bike Bike = (Bike) iter.next (); System.out.println (Bike.tostring ());} public static final void main (string[] args) {Commandlineview CLV = new Commandlineview (); Clv.printallbikes ();}}

Next is the service, the model. It is a simple implementation with an array table. It is dependent on the model (rentabike).

Interface Rentabike {List getbikes (); Bike getbike (String serialno); public class Arraylistrentabike implements Rentabike {private String storename;final List bikes = new ArrayList ();p ublic A Rraylistrentabike (String storename) {this.storename = Storename;bikes.add (New Bike ("Shimano", "Roadmaster", 20, "11111 "," Fair ")); Bikes.add (New Bike (" Cannondale "," F2000 XTR "," 22222 "," excellent ")); Bikes.add (New Bike (" Trek "," 6000 ",", "33333", 12.4, "Fair");} Public String toString () {return "Rentabike:" + storename;} Public List Getbikes () {return bikes;} Public Bike getbike (String serialno) {iterator iter = Bikes.iterator (), while (Iter.hasnext ()) {Bike Bike = (Bike) iter.next (); if (Serialno.equals (Bike.getserialno ())) return bike; return null;}}

Here is an assembler. Code that is in bold is dependency injection. The assembler instantiates the service and the customer, and then resolves the dependency by setting the Rentabike property.

public class Rentabikeassembler {public static final void main (string[] args) {Commandlineview CLV = new Commandlineview ( ); Rentabike rentabike = new Arraylistrentabike ("Bruce's Bikes"); Clv.setrentabike (rentabike); Clv.printallbikes ();}

Of course, spring will eventually act as an assembler. If the service is packaged in an interface, it can be injected into the container with any interface implementation.

Dependency injection allows you to encode production dependencies and test dependencies. For example, this example creates a stub object, which makes it easier to test the view.

You have seen the Rentabike hibernate implementations and array table versions. I don't want to run all the user interface tests on the full hibernate implementation. Instead, I used an array table to implement the interface simply.

Dependency injection allows you to obtain a production version (using Hibrentabike), a development version (using a arraylistrentabike list), and a test version (using a mock object). When using Java programming, I use dependency injection to put these mocks in places that are difficult to reach.

  4. Reverse control simplifies JDBC

JDBC applications are cumbersome, tedious, and tedious. A good abstraction layer can help a lot. Spring allows you to use queries to customize a default JDBC method and anonymous inner class to reduce a lot of heavy work. Here's a simple example of JDBC:

JdbcTemplate template = new JdbcTemplate (DataSource); Final List names = new LinkedList (); Template.query ("SELECT user.name from USER", New RowCallbackHandler () {public void PR Ocessrow (ResultSet rs) throws SQLException});

Treat the Template.query method as a default JDBC method. Spring will perform the Processrow method in the anonymous inner class for each row in the result set. You configure the data source in the context. You don't have to worry about opening or closing statements or connections, configuring data sources, or managing transactions. You do not have to specify an external result set or manage the exception at the bottom because spring puts SqlException in a common collection of unchecked exceptions. Other languages, such as Ruby and Smalltalk, often use reverse controls that contain blocks of code, but this is not very common in Java. Reverse control can achieve amazing results.

  5.Spring Prosperity in the community

Some open source projects do not need to be particularly useful. For example, JUnit completes a scheduled task, and if you like the programming model, it basically has all the functionality you need. Lightweight containers like spring need a vibrant community. Spring has one of the most active communities you can find, and it has many benefits for you:

Services: With spring, you can find hundreds of different services, from security to system management, to workflows. For persistence, you can insert Jdo, Hibernate, top Link, JDBC, or OJB.

Support and Training: many independent consultants offer spring services, and you can get quality training worldwide.

Enhancements: Spring launches several versions a year. The quality of each version is very good, the test in the framework is good, the expansion composition is clear. Spring has started supporting Hibernate 3 and will provide a powerful new web streaming framework, all of which are included in the latest releases.

Business support: There are many people like me who write books about spring. So far, 5 books devoted to spring have been found, and some books contain spring content. Several product vendors also support spring. Many open source frameworks, such as Geronimo and Hibernate, provide special support for spring.

The spring community makes it easier to use this framework. I can hire spring developers and train them. I can read books to supplement my knowledge and get components for the work that needs to be done. I can't find another community that has other similar lightweight containers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.