# Bộ khung Spring

### Bách khoa toàn thư mở Wikipedia

Spring Framework
Hình:Spring Framework.jpg
Phát triển: | Interface21
Phiên bản mới nhất: | 2.0.2 / Jan 10, 2007
Hệ điều hành: | Cross-platform
Thể loại: | Application framework
Giấy phép: | Apache 2.0
Trang chủ: | springframework.org

Bộ khung Spring - tiếng Anh: Spring Framework - (hay ngắn hơn là Spring) là một cấu trúc dùng để xây dựng chương trình ứng dụng nguồn mở (open source application framework) dành cho Java. Phiên bản đầu tiên của nó do ông Rod Johnson viết, và đã được ông cho xuất bản cùng với quyển sách đầu tay của ông Expert One-on-One Java EE Design and Development (Nhà xuất bản Wrox Press, Tháng Mười năm 2002) - tạm dịch là Thiết kế và kiến tạo Java EE - tương giao cá nhân một đối một chuyên ngành. Phiên bản phần mềm này cũng còn được xuất sang nền tảng .NET nữa (.Net Platform), được gọi là Spring.net.

Kiến trúc của Bộ khung Spring được ra mắt công chúng lần đầu tiên hồi tháng Sáu năm 2003 dưới Giấy phép Apache - phiên bản 2.0. Phiên bản 1.0 đánh dấu mốc thành đạt đầu tiên được xuất bản vào hổi tháng Ba năm 2004, và tiếp đó vào tháng Chín năm 2004, tháng Ba năm 2005.

Tuy Bộ khung Spring không bắt buộc người ta phải tuân theo một mô hình lập trình (programming model) cụ thể nào, song nó lan truyền rộng rãi trong cộng đồng những người viết chương trình dùng Java, như một hình thức chủ yếu thay thế cho mô hình Enterprise JavaBean. Theo thiết kế, bộ khung hình này giải phóng lập trình viên dùng Java, cho phép họ nhiều quyền tự do hơn, và đồng thời cung cấp một giải pháp tiện lợi, đầy đủ dẫn chứng bằng tài liệu, dễ dàng sử dụng, phù hợp với những thực hành thông dụng trong công nghệ phần mềm.

Bên cạnh những đặc trưng nền tảng của Bộ khung Spring là những cái có thể dùng được trong bất cứ một chương trình ứng dụng Java nào, rất nhiều các mở rộng và tiến bộ trong việc kiến tạo các trình ứng dụng dành cho nền tảng mạng web (web-based applications) dựa trên Java Enterprise platform cũng tồn tại nữa. Spring nổi tiếng cũng một phần do chính đặc thù kể trên và được giới thương mại (vendors) công nhận như một nền tảng kiến trúc có tầm quan trọng trong chiến lược kiến tạo phần mềm [cần chú thích].

## [sửa] Lịch sử của Spring Framework

Phần đầu tiên của cái mà sau này trở thành Bộ khung Spring nguyên được Rod Johnson viết vào năm 2000, trong khi ông đang làm một chuyên viên cố vấn cho các khách hàng trong thị trường kinh tế tài chính tại Luân Đôn. Trong lúc đang viết quyển Expert One-on-one J2EE Design And Development (Programmer to programmer) - (Thiết kế và kiến tạo Java EE - tương giao cá nhân một đối một chuyên ngành (lập trình viên với lập trình viên)) - ông đã mở rộng thêm phần mã nguồn, hòng biểu đạt ý tưởng của mình về mối tương quan của các trình ứng dụng với những phần khác nhau của J2EE và cho rằng chúng ta có thẻ đơn giản hóa mối tương quan của chúng, và mối liên hệ ấy có thể trở nên cố định, bất biến hơn là những gì mà các lập trình viên và các công ty vốn quen sử dụng tại thời điềm đó.

Trước đây, vào năm 2001, những mô hình lập trình cho các trình ứng dụng cho mạng WEB (web-based) được đại đa số sử dụng đều do Java Servlet API và Enterprise JavaBeans cung cấp. Cả hai đều là đặc tả do Sun Microsystems kiến tạo với sự cộng tác của các nhà buôn bán phần mềm và các bên quan tâm, và chúng rất được mến chuộng trong cộng đồng Java. Những trình ứng dụng không dùng cho mạng WEB như các ứng dụng trình khách (client-based applications) hay các ứng dụng tác vụ (batch applications) đều có thể sử dụng các công cụ từ mã nguồn mở (open source), các công cụ trên thị trường (commercial tools) hoặc từ các dự án khác là những cái cung cấp những đặc trưng yêu cầu.

Rod Johnson được ghi công là người thiết lập bộ khung, dựa trên những thói quen hành nghề được công chúng chấp nhận là những phương pháp tốt nhất (best practices), và tạo cơ hội cho chúng có thể được sử dụng trong tất cả các loại hình chương trình ứng dụng, không chỉ cho các trình ứng dụng cho mạng WEB riêng mà thôi. Ý tưởng này còn được biểu lộ trong cuốn sách của ông và, sau khi được độc giả yêu cầu, ông còn cho xuất bản kèm với mã nguồn với giấy phép mã nguồn mở nữa (open-source license).

Bài này đang được dịch từ tiếng Anh, nếu bạn có đủ khả năng xin góp sức dịch bài này. Nếu không tiếp tục được quan tâm, phần ngoại ngữ của bài sẽ bị xóa sau khoảng 1 tháng. Xin tham khảo Hướng dẫn cách biên soạn bài để biết thêm chi tiết.

Expression error: Unrecognised word "expression"

A small team of developers willing to work on extending the framework was formed and a project home was created on Sourceforge in February 2003. After working on the framework for more than one year they released their first release (1.0) in March 2004. After this release the framework gained a lot of popularity within the Java community, this is in part due to the higher than average standard of the Javadoc and reference documentation for an open source project.

However, the Spring Framework was also heavily criticized in 2004 and remains the subject of sometimes heated discussions up to this date. At the time of its first major release many developers and thought leaders saw the Spring Framework as a move away from the traditional programming model; this was especially true for Enterprise JavaBeans. One of the design goals of the Spring Framework is to easily integrate with existing J2EE standards and vendor tools. To a large extent this removes the need to define its features in an official committee-controlled specification document which is criticized by some.

The Spring Framework made previously unfamiliar techniques popular in a short period of time, the most notable example is Inversion of Control. In 2004 the Spring Framework enjoyed high adoption rates and by offering its own aspect-oriented programming (AOP) framework it also helped to make this programming paradigm more popular within the Java community.

2005 saw even higher adoption rates than the previous year thanks to new milestone releases and more features being added. The Spring Forum that was launched at the end of 2004 also helped to increase the framework's popularity and has since grown out to be the most important source of information and help for its users.

In the same year the Spring developers started their own company to offer commercial support and notably started a partnership with BEA [cần chú thích]. In December 2005 the first Spring conference was held in Miami attracting 300 developers over the course of 3 days, followed by a conference in Antwerp in June 2006, attended by over 400 people.

## [sửa] Key features

Tiêu bản:Advertisment

- Powerful JavaBeans-based configuration management, applying Inversion-of-Control (IoC) principles. This makes wiring up applications quicker and easier. The use of IoC in the Spring framework is also referred to as Dependency Injection (DI). The IoC principle used in Spring framework is a technique that externalizes the creation and management of component dependencies. Assume the case where class Foo depends on an instance of Bar to perform some kind of operation. Traditionally, Foo creates an instance of Bar using the new operator or obtains one from some kind of factory class. Using the IoC approach, an instance of Bar (or a subclass) is provided to Foo at runtime by some external process. This is the reason why the term DI is more descriptive of Spring functionality. (compared to IoC).

- A core bean factory, usable in any environment, from applets to Java EE containers.

- Generic abstraction layer for database transaction management, allowing for pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues.

- Built-in generic strategies for JTA and a single JDBC DataSource. In contrast to plain JTA or EJB CMT, Spring's transaction support does not require Java EE environments.

- JDBC abstraction layer that offers a meaningful exception hierarchy (no more pulling vendor codes out of SQLException), simplifies error handling, and greatly reduces the amount of code programmers need to write. You'll never need to write another 'finally' block to use JDBC again. The JDBC-oriented exceptions comply with Spring's generic DAO (Data Access Object) exception hierarchy.

- Integration with Hibernate, JDO and iBATIS SQL Maps: in terms of resource holders, DAO implementation support, and transaction strategies. First-class Hibernate support with lots of IoC convenience features, addressing many typical Hibernate integration issues. All of these comply with Spring's generic transaction and DAO exception hierarchies.

- Flexible MVC web application framework, built on core Spring functionality. Developers have a high degree of control over this framework via strategy interfaces, and it accommodates multiple view technologies like JSP, FreeMarker, Velocity, Tiles, iText, and POI. Note that a Spring middle tier can easily combine with a web tier based on any other web MVC framework, like Struts, WebWork, or Tapestry.

- Aspect-oriented programming framework to provide services like transaction management. AOP provides the ability to implement crosscutting logic—that is, logic that applies to many parts of your application—in a single place and to have that logic applied across your application automatically.

As MVC patterns (such as Struts) often have difficulty in providing a clear framework for designing the Model part of an application, Spring's ability to work easily with such patterns means that developers can quickly refactor many unsuccessful approaches to make use of Spring's JDBC abstraction layer.

## [sửa] Introduction to the Spring Framework

The Spring Framework provides solutions to many technical challenges faced by Java developers and organizations wanting to create applications based on the Java platform. Because of the sheer vastness of the functionality that is offered it can be hard to distinguish the major building blocks the framework is composed of. The Spring Framework is not exclusively linked to the Java Enterprise platform although its far-reaching integration in this area is an important reason for its popularity.

The Spring Framework is probably best known for offering features required to effectively create complex business applications outside of the programming models that historically have been dominant in the industry. Next to that it is also credited for introducing previously unfamiliar functionalities into today's mainstream development practices, even beyond the Java platform.

This amounts to a framework that offers a consistent model and makes it applicable to most application types that are created on top of the Java platform today. The Spring Framework is considered to implement one way of working based on best practices and industry standards and making it available to many domains in Java.

### [sửa] Modules of the Spring Framework

The Spring Framework can be considered as a collection of smaller frameworks or frameworks-in-the-framework. Most of these frameworks are designed to work independently of each other yet provide better functionalities when used together. These frameworks are divided along the building blocks of typical complex applications:

- Inversion of Control container: configuration of application components and lifecycle management of Java objects.
- Aspect-oriented programming framework: working with functionalities that cannot be implemented with Java's object-oriented programming capabilities without making sacrifices.
- Data access framework: working with relational database management systems on the Java platform using JDBC and Object-relational mapping tools providing solutions to technical challenges that are reusable in a multitude of Java-based environments.
- Transaction management framework: harmonization of various transaction management API's and configurative transaction management orchestration for Java objects.
- Model-view-controller framework: HTTP and Servlet based framework providing many hooks for extension and customization.
- Remote Access framework: configurative RPC-style export and import of Java objects over computer networks supporting HTTP-based protocols, RMI, CORBA and web services (SOAP).
- Authentication and authorization framework: configurative orchestration of authentication and authorization processes supporting many popular and industry-standard standards, protocols, tools and practices.
- Remote Management framework: configurative exposure and management of Java objects for local or remote configuration via JMX.
- Messaging framework: configurative registration of message listener objects for transparent message consumption from message queues via JMS, improvement of message sending over standard JMS API's.
- Testing framework: support classes for writing unit tests and integration tests.

### [sửa] Inversion of Control container

  Main article: Spring core container

Central in the Spring Framework is its Inversion of Control container that provides a consistent means of configuring and managing Java objects. This container is also known as BeanFactory, ApplicationContext or Core container.

The container has many responsibilities and extension points that can all be considered as forms of Inversion of Control, hence its name. Examples are: creating objects, configuring objects, calling initialization methods and passing objects to registered callback objects. Many of the functionalities of the container together form the object lifecycle which is one of the most important features it provides.

Objects that are created by the container are also called Managed Objects or Beans. Typically the container is configured by loading XML files that contain Bean definitions. These provide all information that is required to create objects. Once objects are created and configured without raising error conditions they become available for usage. Objects can be obtained by means of Dependency lookup or Dependency injection.

Dependency lookup is a pattern where a caller asks the container object for an object with a specific name or of a specific type. Dependency injection is a pattern where the container passes objects by name to other objects, either via constructors, properties or factory methods.

In many cases it's not required to use the container when using other parts of the Spring Framework although using it will likely make application easier to configure and customize. The Spring container provides a consistent mechanism to configure applications and integrates with almost all Java environments, from small-scale applications to large enterprise applications [cần chú thích].

The container can be turned in a partially-compliant EJB3 container by means of the Pitchfork project. This project by itself however does not make the container fully compliant with the EJB3 specifications. The Spring Framework is criticized by some as not being standards compliant. Interface21 doesn't see EJB3 compliance as a major goal and claims the Spring Framework and the container allow for more powerful programming models[1].

### [sửa] Aspect-oriented programming framework

  Main article: Spring AOP framework

The Spring Framework has its own AOP framework that modularizes cross-cutting concerns in aspects. The motivations for creating a separate AOP framework comes from the belief that it would be possible to provide basic AOP features without too much complexity in either design, implementation or configuration. The Spring AOP framework also takes full advantage of the versatile and flexible Spring Container to ease configuration and add features.

The Spring AOP framework is interception-based and configured at runtime. This removes the need for a special compilation step or load-time weaving. On the other hand interception only allows for public or protected method executions on existing object as join point. The trade-off between simplicity and available features is an important one as Spring AOP is reasonably powerful yet remains reasonably easy to learn.

Compared to the AspectJ framework Spring AOP is less powerful but also less complicated. Spring 1.2 includes support to configure AspectJ aspects in the container. Spring 2.0 has more integration with AspectJ, for example the pointcut language is reused.

Spring AOP has been designed to make it reasonably easy to work with cross-cutting concerns inside the Spring Framework. Any object that's created and configured by the container can be enriched using Spring AOP.

The Spring Framework uses Spring AOP internally for transaction management, security, remote access and JMX.

### [sửa] Data access framework

  Main article: Spring data access framework

The data access framework that's part of Spring addresses common difficulties developers face when working with databases in applications. Support is provided for all popular data access frameworks in Java: JDBC [1], iBatis [2], Hibernate [3], JDO [4], JPA [5], Oracle TopLink, Apache OJB [6] and Cayenne [7] amongst others.

For all these supported frameworks Spring provides these features:

- Resource management (automatically acquiring and releasing database resources)
- Exception handling (translating data access related exception to a Spring data access hierarchy)
- Transaction participation (transparent participation in ongoing transactions)
- Resource unwrapping (retrieving database objects from connection pool wrappers)
- Abstraction for BLOB and CLOB handling

All these features become available when using Template classes provided by Spring for each supported framework. Critics say these Template classes are intrusive and offer no advantage over using for example the Hibernate API directly [8]. In response the Spring developers have made it possible to directly use the Hibernate and JPA APIs. This however requires transparent transaction management as application code no longer assumes the responsibility to obtain and close database resources and doesn't support exception translation.

Together with Spring's transaction management its data access framework offers a flexible abstraction for working with data access frameworks. The Spring Framework doesn't offer a common data access API, instead the full power of the supported APIs are kept intact. The Spring Framework is the only framework available in Java that offers managed data access environments outside of an application server or container.

### [sửa] Transaction management framework

  Main article: Spring transaction management framework

Spring's transaction management framework brings an abstraction mechanism to the Java platform that has never been attempted before. Its abstraction is capable of:

- working with local and global transactions (local transaction don't require an application server)
- working with nested transactions
- working with transaction safepoints
- in almost all environments of the Java platform

Compare with JTA which only supports nested transactions and global transactions and requires an application server (and in some cases also deployment of applications in an application server).

The Spring Framework ships a PlatformTransactionManager for a number of transaction management strategies:

- Transactions managed on a JDBC Connection
- Transactions managed on Object-relational mapping Units of Work
- Transactions managed via the JTA TransactionManager and UserTransaction
- Transactions managed on other resources, like object databases

Next to this abstraction mechanism the framework also provides two ways of adding transaction management to applications:

- Programmatically, by using Spring's TransactionTemplate
- Configuratively, by using metadata like XML or Java 5 annotations

Together with Spring's data access framework - which integrates the transaction management framework - it's possible to setup up a transactional system through configuration without having to rely on JTA or EJB. The transactional framework also integrates with messaging and caching engines.

### [sửa] Model-view-controller framework

  Main article: Spring MVC framework

The Spring Framework features its own MVC framework, which wasn't originally planned. The Spring developers decided to write their own web framework as a reaction to the poor design of the popular Jakarta Struts web framework [cần chú thích].

Spring MVC is a request-based framework comparable to Struts in this respect. The framework defines strategy interfaces for all responsibilities that have to be handled by a modern request-based framework. The responsibility of each interface is sufficiently simple and clear that it's easy for Spring MVC users to write their own implementations if they choose to. All interfaces are tightly coupled to the Servlet API to offer the full power of this API. This tight coupling to the Servlet API is seen by some as a failure on the part of the Spring developers to offer a high-level abstraction for web-based applications [cần chú thích]. However, this coupling makes sure that the features of the Servlet API remain available to developers while offering a high abstraction framework to ease working with said API.

The DispatcherServlet class is the front controller [9] of the framework and is responsible for delegating control to the various interfaces during the execution phases of a HTTP request.

The most important interfaces defined by Spring MVC and their responsibilities are listed below:

- HandlerMapping: selecting objects that handle incoming requests (handlers) based on any attribute or condition internal or external to those requests
- HandlerAdapter: execution of objects that handle incoming requests
- Controller: comes between Model and View to manages incoming requests and redirect to proper response.
- View: responsible for returning a response to the client
- ViewResolver: selecting a View based on a logical name for the view (use is not strictly required)
- HandlerInterceptor: interception of incoming requests comparable but not equal to Servlet filters (use is optional and not controlled by DispatcherServlet).
- LocaleResolver: resolving and optionally saving of the locale of an individual user
- MultipartResolver: facilitate working with file uploads by wrapping incoming requests

Each strategy interface above has an important responsibility in the overall framework. The abstractions offered by these interfaces is sufficiently powerful to allow for a wide set of variations in their implementations. Spring MVC ships with implementations of all these interfaces and together offer a powerful feature set on top of the Servlet API. However, developers and vendors are free to write other implementations. Spring MVC uses the Java `java.util.Map` interface as a data-oriented abstraction for the Model where keys are expected to be string values.

The ease of testing the implementations of these interfaces is one important advantage of the high level of abstraction offered by Spring MVC. DispatcherServlet is tightly coupled to the Spring Inversion of Control container for configuring the web layers of applications. However, applications can use other parts of the Spring Framework - including the container - and choose not to use Spring MVC.

Because Spring MVC uses the Spring container for configuration and assembly web-based applications can take full advantage of the Inversion of Control features offered by the container.

### [sửa] Remote access framework

  Main article: Spring remote access framework

Spring's Remote Access framework is an abstraction for working with various RPC-based technologies available on the Java platform both for client connectivity and exporting objects on servers. The most important feature offered by this framework is to ease configuration and usage of these technologies as much as possible by combining Inversion of Control and AOP.

The framework also provides fault-recovery (automatic reconnection after connection failure) and some optimizations for client-side use of EJB remote stateless session beans.

Spring provides support for these protocols and products out of the box:

- HTTP-based protocols
  - Hessian: binary serialization protocol, open-sourced and maintained by Caucho
  - Burlap: XML-based serialization protocol, open-sourced and maintained by Caucho
  - HttpInvoker: Java serialization over HTTP, specific for Spring
- RMI/Corba-based protocols
  - RMI (1): method invocations using RMI infrastructure yet specific to Spring
  - RMI (2): method invocations using RMI interfaces complying with regular RMI usage
  - RMI-IIOP (Corba): method invocations using RMI-IIOP/Corba
- Enterprise JavaBean client integration
  - Local EJB stateless session bean connectivity: connecting to local stateless session beans
  - Remote EJB stateless session bean connectivity: connecting to remote stateless session beans
- SOAP
  - Integration with the Apache Axis web services framework

The XFire SOAP framework provides integration with the Spring Framework for RPC-style exporting of object on the server side.

Both client and server setup for all RPC-style protocols and products supported by the Spring Remote access framework (except for the Apache Axis support) is configured in the Spring Core container.

### [sửa] Authentication and authorization framework

  Main article: Acegi security framework (Java)

### [sửa] Remote management framework

  Main article: Spring JMX framework

## [sửa] References

- Johnson, Rod; Jürgen Höller, Alef Arendsen, Thomas Risberg, and Colin Sampaleanu (2005). Professional Java Development with the Spring Framework, Wiley. ISBN 0-7645-7483-3.
- Harrop, Rob; Jan Machahek (2005). Pro Spring, APress. ISBN 1-59059-461-4.
- Johnson, Rod; Jürgen Höller (2004). J2EE Development without EJB, Wiley. ISBN 0-7645-5831-5.
- Johnson, Rod (2002). Expert One-on-on J2EE Design and Development, Wiley. ISBN 0-7645-4385-7.
- Walls, Craig; Ryan Breidenbach (2005). Spring in Action, Manning. ISBN 1-9323-9435-4.
- Wolff, Eberhard (2006). Spring - Framework für die Java Entwicklung, dpunkt. ISBN 3-89864-365-4.

## [sửa] External links

- Spring Framework
- Spring.Net

Lấy từ “http://vi.wikipedia.org../../../b/%E1%BB%99/_/B%E1%BB%99_khung_Spring_aad9.html”

Thể loại: Bài cần chú thích nguồn gốc | Java enterprise platform | Web application frameworks

##### Views

- Bài viết
- Thảo luận
- Phiên bản hiện hành

##### Tìm kiếm

##### Ngôn ngữ khác

- Deutsch
- English
- Français
- Italiano
- Nederlands
- ‪Norsk (bokmål)‬
- Polski
- Português
- Русский
- 中文