Five reasons to love spring.

Source: Internet
Author: User
Tags anonymous advantage
About 2 years ago, I tried the spring project highlighted on the hibernate site. I think it's like the old-fashioned kayak mentioned above: It fits me again. For enterprise hard coding, Spring is so deeply rooted in my programming 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 provides a better advantage

In the river, I learned to use my waist and my back to paddle more, because my arm muscles couldn't keep 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 find a lot of extra tools, the biggest of which is in terms of persistence. Here's a way to get a Hibernate data Access object:

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

Note that you do not see the content. There is no transaction handling. 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 location. The following is another hibernate method that does not 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 faster and with 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 hack into each bean. Of course, we need transactions, security, persistence, and sometimes remote control. For EJBs, I had to learn a widely used API and work through new tools and deployment processes. I am the slave of the service provided by the container. With spring, I can choose my own service and persistence framework. I do Pojo programming and add enterprise Services to them using configuration files.

In the book Spring:a Developer's Notebook, I built a rentabike application. I call my Pojo a hibrentabike, not a session bean or an entity bean; it is used as my data access object. I've also added services elsewhere. A spring configuration file, called a 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

Interceptors:

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 binding code for invoking the service (glue code), and also specifies how to handle each method in the target. Anyone who needs to access Rentabike calls the proxy, and the proxy invokes the transaction interceptor, and the transaction interceptor starts a transaction and invokes the target (POJO). The target completes its work, returns to the interceptor (responsible for committing the transaction), and then returns to the caller of the agent and agent.

  

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 helps 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 a property for the customer. Spring creates the customer and service, and then sets the customer's property to the value of the service. In other words, Spring is responsible for managing the bean's life cycle in context and resolving dependencies. Here is an example of dependency injection without using spring. We first look at the customer (the basic elements 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 has a dependency 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 ", and" 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;}}

The following is a compilation procedure. The code in bold is the 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 assume the role of assembler. If the service is packaged in an interface, any interface implementation can be injected into the container.

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 hibernate implementation of Rentabike and the array table version. I don't want to run all the user interface tests on the full hibernate implementation. Instead, I used an array table to simply implement the interface.

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 I use Java programming, I use dependency injection to put these mocks in places that are difficult to reach.

  4. Reverse control simplifies the JDBC

JDBC applications are cumbersome, tedious, and tedious. A good abstraction layer can be a great help. Spring allows you to use queries to customize a default JDBC method and anonymous inner classes to reduce the amount of heavy work. A simple JDBC example is given below:

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});

Consider the Template.query method as a default JDBC method. Spring executes 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 connecting, configuring data sources, or managing transactions. You do not have to specify an external result set or to manage exceptions at the bottom because spring puts SqlException in a common collection that does not check for exceptions. Other languages, such as Ruby and Smalltalk, typically use reverse control that contains blocks of code, but this is not very common in Java. The 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 require a vibrant community. Spring has one of the most active communities you can find, which has many benefits for you:

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

Support and Training: many independent consultants offer spring services, and you can receive quality training on a global scale.

Enhanced: Spring launches several versions in a year. Each version of the quality is very good, the framework of good testing, expansion of the composition is clear. Spring has started to support Hibernate 3 and will provide a powerful new web streaming framework, which is included in the latest version.

Business support: There are many people who write about spring as I do. To date, 5 books have been found that specialize in spring, and some contain spring-related content. Several product suppliers 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 the 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.