admin 管理员组

文章数量: 1184232


2024年3月28日发(作者:考研复试c语言面试题)

xxxx大学xxx学院

毕业设计(论文)外文文献翻译

系 部

专 业

学生姓名

指导教师

xxxx

xxxx

xxxx 学号 xxxx

xxxx 职称 xxxx

2013年 3 月

Introducing the Spring Framework

The Spring Framework: a popular open source application framework

that addresses many of the issues outlined in this book. This chapter will

introduce the basic ideas of Spring and dis-cuss the central “bean

factory” lightweight Inversion-of-Control (IoC) container in detail.

Spring makes it particularly easy to implement lightweight, yet

extensible, J2EE archi-tectures. It provides an out-of-the-box

implementation of the fundamental architectural building blocks we

recommend. Spring provides a consistent way of structuring your

applications, and provides numerous middle tier features that can make

J2EE development significantly easier and more flexible than in

traditional approaches.

The basic motivations for Spring are:

To address areas not well served by other frameworks. There are

numerous good solutions to specific areas of J2EE infrastructure: web

frameworks, persistence solutions, remoting tools, and so on. However,

integrating these tools into a comprehensive architecture can involve

significant effort, and can become a burden. Spring aims to provide an

end-to-end solution, integrating spe-cialized frameworks into a coherent

overall infrastructure. Spring also addresses some areas that other

frameworks don’t. For example, few frameworks address generic

transaction management, data access object implementation, and gluing all

those things together into an application, while still allowing for

best-of-breed choice in each area. Hence we term Spring an application

framework, rather than a web framework, IoC or AOP framework, or even

middle tier framework.

To allow for easy adoption. A framework should be cleanly layered,

allowing the use of indi-vidual features without imposing a whole world

1

view on the application. Many Spring features, such as the JDBC

abstraction layer or Hibernate integration, can be used in a library style

or as part of the Spring end-to-end solution.

To deliver ease of use. As we’ve noted, J2EE out of the box is

relatively hard to use to solve many common problems. A good

infrastructure framework should make simple tasks simple to achieve,

without forcing tradeoffs for future complex requirements (like

distributed transactions) on the application developer. It should allow

developers to leverage J2EE services such as JTA where appropriate, but

to avoid dependence on them in cases when they are unnecessarily complex.

To make it easier to apply best practices. Spring aims to reduce the

cost of adhering to best practices such as programming to interfaces,

rather than classes, almost to zero. However, it leaves the choice of

architectural style to the developer.

Non-invasiveness. Application objects should have minimal dependence

on the framework. If leveraging a specific Spring feature, an object

should depend only on that particular feature, whether by implementing

a callback interface or using the framework as a class library. IoC and

AOP are the key enabling technologies for avoiding framework dependence.

Consistent configuration. A good infrastructure framework should

keep application configuration flexible and consistent, avoiding the need

for custom singletons and factories. A single style should be applicable

to all configuration needs, from the middle tier to web controllers.

Ease of testing. Testing either whole applications or individual

application classes in unit tests should be as easy as possible. Replacing

resources or application objects with mock objects should be

straightforward.

2

To allow for extensibility. Because Spring is itself based on

interfaces, rather than classes, it is easy to extend or customize it.

Many Spring components use strategy interfaces, allowing easy

customization.

A Layered Application Framework

Chapter 6 introduced the Spring Framework as a lightweight container,

competing with IoC containers such as PicoContainer. While the Spring

lightweight container for JavaBeans is a core concept, this is just the

foundation for a solution for all middleware layers.

Basic Building Blocks

pring is a full-featured application framework that can be leveraged

at many levels. It consists of multi-ple sub-frameworks that are fairly

independent but still integrate closely into a one-stop shop, if desired.

The key areas are:

Bean factory. The Spring lightweight IoC container, capable of

configuring and wiring up Java-Beans and most plain Java objects, removing

the need for custom singletons and ad hoc configura-tion. Various

out-of-the-box implementations include an XML-based bean factory. The

lightweight IoC container and its Dependency Injection capabilities will

be the main focus of this chapter.

Application context. A Spring application context extends the bean

factory concept by adding support for message sources and resource loading,

and providing hooks into existing environ-ments. Various out-of-the-box

implementations include standalone application contexts and an XML-based

web application context.

AOP framework. The Spring AOP framework provides AOP support for

method interception on any class managed by a Spring lightweight container.

3

It supports easy proxying of beans in a bean factory, seamlessly weaving

in interceptors and other advice at runtime. Chapter 8 dis-cusses the

Spring AOP framework in detail. The main use of the Spring AOP framework

is to provide declarative enterprise services for POJOs.

Auto-proxying. Spring provides a higher level of abstraction over the

AOP framework and low-level services, which offers similar ease-of-use

to .NET within a J2EE context. In particular, the provision of declarative

enterprise services can be driven by source-level metadata.

Transaction management. Spring provides a generic transaction

management infrastructure, with pluggable transaction strategies (such

as JTA and JDBC) and various means for demarcat-ing transactions in

applications. Chapter 9 discusses its rationale and the power and

flexibility that it offers.

DAO abstraction. Spring defines a set of generic data access

exceptions that can be used for cre-ating generic DAO interfaces that

throw meaningful exceptions independent of the underlying persistence

mechanism. Chapter 10 illustrates the Spring support for DAOs in more

detail, examining JDBC, JDO, and Hibernate as implementation strategies.

JDBC support. Spring offers two levels of JDBC abstraction that

significantly ease the effort of writing JDBC-based DAOs: the

package (a template/

callback approach) and the package

(modeling RDBMS operations as reusable objects). Using the Spring JDBC

packages can deliver much greater pro-ductivity and eliminate the

potential for common errors such as leaked connections, compared with

direct use of JDBC. The Spring JDBC abstraction integrates with the

transaction and DAO abstractions.

Integration with O/R mapping tools. Spring provides support classes

4

for O/R Mapping tools like Hibernate, JDO, and iBATIS Database Layer to

simplify resource setup, acquisition, and release, and to integrate with

the overall transaction and DAO abstractions. These integration packages

allow applications to dispense with custom ThreadLocal sessions and

native transac-tion handling, regardless of the underlying O/R mapping

approach they work with.

Web MVC framework. Spring provides a clean implementation of web MVC,

consistent with the JavaBean configuration approach. The Spring web

framework enables web controllers to be configured within an IoC container,

eliminating the need to write any custom code to access business layer

services. It provides a generic DispatcherServlet and out-of-the-box

controller classes for command and form handling. Request-to-controller

mapping, view resolution, locale resolution and other important services

are all pluggable, making the framework highly extensi-ble. The web

framework is designed to work not only with JSP, but with any view

technology, such as Velocity—without the need for additional bridges.

Chapter 13 discusses web tier design and the Spring web MVC framework in

detail.

Remoting support. Spring provides a thin abstraction layer for

accessing remote services without hard-coded lookups, and for exposing

Spring-managed application beans as remote services. Out-of-the-box

support is included for RMI, Caucho’s Hessian and Burlap web service

protocols, and WSDL Web Services via JAX-RPC. Chapter 11 discusses

lightweight remoting.

While Spring addresses areas as diverse as transaction management and

web MVC, it uses a consistent approach everywhere. Once you have learned

the basic configuration style, you will be able to apply it in many areas.

Resources, middle tier objects, and web components are all set up using

the same bean configuration mechanism. You can combine your entire

5

configuration in one single bean definition file or split it by

application modules or layers; the choice is up to you as the application

developer. There is no need for diverse configuration files in a variety

of formats, spread out across the application.

Spring on J2EE

Although many parts of Spring can be used in any kind of Java

environment, it is primarily a J2EE application framework. For example,

there are convenience classes for linking JNDI resources into a bean

factory, such as JDBC DataSources and EJBs, and integration with JTA for

distributed transaction management. In most cases, application objects

do not need to work with J2EE APIs directly, improving reusability and

meaning that there is no need to write verbose, hard-to-test, JNDI

lookups.

Thus Spring allows application code to seamlessly integrate into a

J2EE environment without being unnecessarily tied to it. You can build

upon J2EE services where it makes sense for your application, and choose

lighter-weight solutions if there are no complex requirements. For

example, you need to use JTA as transaction strategy only if you face

distributed transaction requirements. For a single database, there are

alternative strategies that do not depend on a J2EE container. Switching

between those transac-tion strategies is merely a matter of configuration;

Spring’s consistent abstraction avoids any need to change application

code.

Spring offers support for accessing EJBs. This is an important feature

(and relevant even in a book on “J2EE without EJB”) because the use of

dynamic proxies as codeless client-side business delegates means that

Spring can make using a local stateless session EJB an

implementation-level, rather than a fundamen-tal architectural, choice.

6

Thus if you want to use EJB, you can within a consistent architecture;

however, you do not need to make EJB the cornerstone of your architecture.

This Spring feature can make devel-oping EJB applications significantly

faster, because there is no need to write custom code in service loca-tors

or business delegates. Testing EJB client code is also much easier,

because it only depends on the EJB’s Business Methods interface (which

is not EJB-specific), not on JNDI or the EJB API.

Spring also provides support for implementing EJBs, in the form of

convenience superclasses for EJB implementation classes, which load a

Spring lightweight container based on an environment variable specified

in the deployment descriptor. This is a powerful and

convenient way of imple-menting SLSBs or MDBs that are facades for

fine-grained POJOs: a best practice if you do choose to implement an EJB

application. Using this Spring feature does not conflict with EJB in any

way—it merely simplifies following good practice.

Introducing the Spring Framework

The main aim of Spring is to make J2EE easier to use and promote good

programming practice. It does not reinvent the wheel; thus you’ll find

no logging packages in Spring, no connection pools, no distributed

transaction coordinator. All these features are provided by other open

source projects—such as Jakarta Commons Logging (which Spring uses for

all its log output), Jakarta Commons DBCP (which can be used as local

DataSource), and ObjectWeb JOTM (which can be used as transaction

manager)—or by your J2EE application server. For the same reason, Spring

doesn’t provide an O/R mapping layer: There are good solutions for this

problem area, such as Hibernate and JDO.

Spring does aim to make existing technologies easier to use. For

example, although Spring is not in the business of low-level transaction

7

coordination, it does provide an abstraction layer over JTA or any other

transaction strategy. Spring is also popular as middle tier

infrastructure for Hibernate, because it provides solutions to many

common issues like SessionFactory setup, ThreadLocal sessions, and

exception handling. With the Spring HibernateTemplate class,

implementation methods of Hibernate DAOs can be reduced to one-liners

while properly participating in transactions.

The Spring Framework does not aim to replace J2EE middle tier services

as a whole. It is an application framework that makes accessing low-level

J2EE container ser-vices easier. Furthermore, it offers lightweight

alternatives for certain J2EE services in some scenarios, such as a

JDBC-based transaction strategy instead of JTA when just working with a

single database. Essentially, Spring enables you to write appli-cations

that scale down as well as up.

Spring for Web Applications

A typical usage of Spring in a J2EE environment is to serve as backbone

for the logical middle tier of a J2EE web application. Spring provides

a web application context concept, a powerful lightweight IoC container

that seamlessly adapts to a web environment: It can be accessed from any

kind of web tier, whether Struts, WebWork, Tapestry, JSF, Spring web MVC,

or a custom solution.

The following code shows a typical example of such a web application

context. In a typical Spring web app, an file will

reside in the WEB-INF directory, containing bean defini-tions according

to the “spring-beans” DTD. In such a bean definition XML file, business

objects and resources are defined, for example, a “myDataSource” bean,

a “myInventoryManager” bean, and a “myProductManager” bean. Spring

takes care of their configuration, their wiring up, and their lifecycle.

8

ManagerDataSource”>

.

Driver

jdbc:mysql:myds

DefaultInventoryManager”>

DefaultProductManager”>

true

By default, all such beans have “singleton” scope: one instance per

context. The “myInventoryManager” bean will automatically be wired up

with the defined DataSource, while “myProductManager” will in turn

receive a reference to the “myInventoryManager” bean. Those objects

(traditionally called “beans” in Spring terminology) need to expose

only the corresponding bean properties or constructor arguments (as

you’ll see later in this chapter); they do not have to perform any custom

lookups.

A root web application context will be loaded by a

ContextLoaderListener that is defined in as follows:

9

tLoaderListener

...

After initialization of the web app, the root web application context

will be available as a ServletContext attribute to the whole web

application, in the usual manner. It can be retrieved from there easily

via fetching the corresponding attribute, or via a convenience method in

. licationContextUtils.

This means that the application context will be available in any web

resource with access to the ServletContext, like a Servlet, Filter, JSP,

or Struts Action, as follows:

WebApplicationContext wac = WebApplicationContextUtils.

getWebApplicationContext(servletContext);

The Spring web MVC framework allows web controllers to be defined as

JavaBeans in child application contexts, one per dispatcher servlet. Such

controllers can express dependencies on beans in the root application

context via simple bean references. Therefore, typical Spring web MVC

applications never need to perform a manual lookup of an application

context or bean factory, or do any other form of lookup.

Neither do other client objects that are managed by an application

context themselves: They can receive collaborating objects as bean

references.

The Core Bean Factory

10

In the previous section, we have seen a typical usage of the Spring

IoC container in a web environment: The provided convenience classes allow

for seamless integration without having to worry about low-level

container details. Nevertheless, it does help to look at the inner

workings to understand how Spring manages the container. Therefore, we

will now look at the Spring bean container in more detail, starting at

the lowest building block: the bean factory. Later, we’ll continue with

resource setup and details on the application context concept.

One of the main incentives for a lightweight container is to dispense

with the multitude of custom facto-ries and singletons often found in J2EE

applications. The Spring bean factory provides one consistent way to set

up any number of application objects, whether coarse-grained components

or fine-grained busi-ness objects. Applying reflection and Dependency

Injection, the bean factory can host components that do not need to be

aware of Spring at all. Hence we call Spring a non-invasive application

framework.

Fundamental Interfaces

The fundamental lightweight container interface is

Factory. This is a simple

interface, which is easy to implement directly in the unlikely case that

none of the implementations provided with Spring suffices. The

BeanFactory interface offers two getBean() methods for looking up bean

instances by String name, with the option to check for a required type

(and throw an exception if there is a type mismatch).

public interface BeanFactory {

11

Object getBean(String name) throws BeansException;

Object getBean(String name, Class requiredType) throws

BeansException;

boolean containsBean(String name);

boolean isSingleton(String name) throws

NoSuchBeanDefinitionException;

String[] getAliases(String name) throws

NoSuchBeanDefinitionException;

}

The isSingleton() method allows calling code to check whether the

specified name represents a sin-gleton or prototype bean definition. In

the case of a singleton bean, all calls to the getBean() method will return

the same object instance. In the case of a prototype bean, each call to

getBean() returns an inde-pendent object instance, configured

identically.

The getAliases() method will return alias names defined for the given

bean name, if any. This mecha-nism is used to provide more descriptive

alternative names for beans than are permitted in certain bean factory

storage representations, such as XML id attributes.

The methods in most BeanFactory implementations are aware of a

hierarchy that the implementation may be part of. If a bean is not found

12

in the current factory, the parent factory will be asked, up until the

root factory. From the point of view of a caller, all factories in such

a hierarchy will appear to be merged into one. Bean definitions in ancestor

contexts are visible to descendant contexts, but not the reverse.

All exceptions thrown by the BeanFactory interface and sub-interfaces

extend framework. xception, and are unchecked.

This reflects the fact that low-level configuration prob-lems are not

usually recoverable: Hence, application developers can choose to write

code to recover from such failures if they wish to, but should not be forced

to write code in the majority of cases where config-uration failure is

fatal.

Most implementations of the BeanFactory interface do not merely

provide a registry of objects by name; they provide rich support for

configuring those objects using IoC. For example, they manage

dependen-cies between managed objects, as well as simple properties. In

the next section, we’ll look at how such configuration can be expressed

in a simple and intuitive XML structure.

The sub-interface

leBeanFactory supports listing

beans in a factory. It provides methods to retrieve the number of beans

defined, the names of all beans, and the names of beans that are instances

of a given type:

public interface ListableBeanFactory extends BeanFactory {

int getBeanDefinitionCount();

String[] getBeanDefinitionNames();

String[] getBeanDefinitionNames(Class type);

13

boolean containsBeanDefinition(String name);

Map getBeansOfType(Class type, boolean includePrototypes,

boolean includeFactoryBeans) throws BeansException

}

The ability to obtain such information about the objects managed by

a ListableBeanFactory can be used to implement objects that work with a

set of other objects known only at runtime.

In contrast to the BeanFactory interface, the methods in

ListableBeanFactory apply to the current factory instance and do not take

account of a hierarchy that the factory may be part of. The

ctoryUtils class provides analogous

methods that traverse an entire factory hierarchy.

There are various ways to leverage a Spring bean factory, ranging from

simple bean configuration to J2EE resource integration and AOP proxy

generation. The bean factory is the central, consistent way of setting

up any kind of application objects in Spring, whether DAOs, business

objects, or web controllers. Note that application objects seldom need

to work with the BeanFactory interface directly, but are usu-ally

configured and wired by a factory without the need for any Spring-specific

code.

For standalone usage, the Spring distribution provides a tiny

file that can be embed-ded in any kind of application.

Its only third-party dependency beyond J2SE 1.3 (plus JAXP for XML parsing)

is the Jakarta Commons Logging API.

The bean factory is the core of Spring and the foundation for many

other services that the framework offers. Nevertheless, the bean factory

can easily be used stan-dalone if no other Spring services are required.

Derivative:network

14

Spring 框架简介

Spring框架:这是一个流行的开源应用框架,它可以解决很多问题。这里

主要介绍Spring的基本概念,并详细介绍其中以“bean工厂”为核心的轻量级

控制反转(IoC)容器。

Spring让开发者更轻松的实现轻量级、可扩展的J2EE架构。对于我们推荐

的架构模块,让Spring提供了即时可用的实现。此外,Spring还提供了同意的

应用架构方式,以及大量的中间层功能模块,能大大简化了J2EE的开发,并且

比传统的开发方式更加灵活。

第一章:Spring项目的出发点

1.1解决被其它框架忽略的部分

在J2EE的各个具体领域都有很多出色的解决方案----web框架、持久化方

案、远程调用工具,凡此种种。然而,将这些工具整合成一个全面的架构却困难

重重,甚至成为一种负担。Spring的目标就是提供一种贯穿始终的解决方案,

将各种专用框架整合成一个连贯的整体架构。Spring还涉及到其它框架没有触

及到的地方。例如,很少有框架提供普遍适用的事务管理或是数据库存储对象实

现;即便各个领域都有很好的选择,也没有一个框架能够帮忙把所有这些东西整

合到一个应用中去。因此,我们说Spring是一个应用框架,而不是web框架、

IoC框架、AOP框架或者中间层框架什么的。

1.2易于选择

一个框架应该有清楚的层次划分,允许用户使用其中的单项功能,而不是把

自己的整个世界观强加给用户。Spring中的许多特性---例如JDBC抽象层或者

Hibernation集成----都可以作为一个库单独使用,当然也可以作为Spring整

体方案的一个部分。

1.3易于使用

正如前面说过的,仅仅J2EE本身并不易用---很多常见的问题光靠J2EE都

很难解决。一个好的基础框架首先应该让容易的任务容易完成,而不需要让应用

开发人员现在就为将来的复杂需求(例如分布式事务)买单。框架应该帮助开发

15

人员合理使用J2EE的服务(例如JTA),同时又避免造成对服务的依赖,从而减

少不必要的复杂性。

1.4 鼓励最佳实现

Spring力求把遵循最佳实践--例如“针对接口编程”--的成本降低到最小。

另一方面,Spring又力求不强加任何架构风格,而是把选择的权利留给开发者。

1.5 非入侵性

一个好的基础设施框架应保持应用组态灵活和一致,避免自定义单身和工厂

的需要。一个单一的风格应该是适用于所有配置的需要,从中间层的网络控制器。

1.6 统一配置

测试整个应用程序或单个应用程序类的单元测试应该尽可能的容易。模仿对

象替换资源或应用程序的对象应该是简单的。

1.7 可扩展

由于Spring本身是基于接口的,而不是类,它是很容易扩展或定制。许多

Spring组件使某种形式的Strategy模式,因此可以方便定制。

第二章:一个分层的应用框架

前面我们从轻量级容器(lightwight container)的角度介绍了Spring框

架,并将其与别的IoC容器(例如PicoContainer) 作了比较。虽然为JavaBean

设计的轻量级容器是Spring的核心概念,但这也只是所有中间层解决方案的基

础而已。

2.1 基础构建模块

Spring是一个完整的应用框架,它可以在很懂应用层发挥作用。Spring由

多个子框架组成,而且这些框架都是相对独立的。不过,只要你愿意,你就可以

将它们无缝集成起来,成为一个全面的应用框架,下面讲解Spring框架的关键

概念。

2.1.1 bean工厂

Spring轻量级IoC容器能够配置、装备JavaBean和大多数Java对象,使

得开发者不必定制Singleton和自己的配置机制。Spring提供了多个“即拿即

用”的bean工厂实现。其中包括一个基于XML的bean工厂。轻量级IoC容器和

16

依赖注入(Dependency Injcction)将是本章节关注的内容。

2.1.2应用上下文

Spring应用程序上下文添加消息来源和资源加载支持扩展bean工厂的概

念,并提供钩到现有的环境中。不同的盒子的实现包括独立的应用程序上下文和

基于Web的应用程序上下文的XML。

2.1.3 AOP框架

Spring的AOP框架提供的任何类的Spring轻量级容器管理方法拦截AOP支

持。可以对轻量级容器管理的任何对象进行方法拦截。在bean工厂中,可以轻

松的为JavaBean提供代理,从而在运行天衣无缝地将拦截器和其他的adcice

整合进来。我们将在后面详细讨论Spring的AOP框架。Spring AOP的主要用途

就是为了POJO提供声明性的企业级服务。

2.1.4 自动代理

Spring提供了一个更高的抽象层次的AOP框架和低水平的服务,同时也提

供了很多基础性的服务,从而在J2EE环境中提供了类似于.NET的易用性--特别

是,声明的企业提供的服务可以通过源代码级的元数据驱动的。

2.1.5 事务管理

Spring提供了一个通用的交易管理基础设施,可插拔的交易策略(例如JTA

和JDBC)和不同的事务划分方式。后面会详细介绍Spring事务管理的基本原理,

及其强大的威力和灵活性。

2.1.6 DAO的抽象

Spring定义一组通用的数据访问异常,在创建通用的DAO接口时可以用这

些异常类型抛出有意义的异常信息,,独立于底层的存储机制。后面阐述了更多

的细节讨论Spring对DAO的支持,以及针对JDBC JDO,Hibernate的不同实施

策略。

2.1.7 JDBC的支持

Spring提供了两个层次的抽象,使得编写基于JDBC的DAO特别简单:

包提供了基于模板、回调的JDBC用法,

包则把关系数据库操作建模为可服用对象。

比起直接使用JDBC,用Spring 的JDBC包可以提供更大的生产力和消除常见的

错误,如泄漏等。Spring JDBC抽象层集成了事务抽象和DAO的抽象。

2.1.8 集成O/R映工具

17

Spring提供了多种O/R映射工具的支持,如Hibernate,JDO和ibatis数

据库简化资源设置,采集,和释放,并且将O/R映射与整个事务和DAO抽象集成

起来。这些集成软件包允许应用程序分配自定义ThreadLocal会话和本地事务进

行处理,不必考虑底层究竟采用哪种O/R映射工具。

2.1.9 web MVC框架

Spring提供了一个相当干净的Web MVC实现--同样使用了统一JavaBean配

置方式。使用Spring web框架时,web控制器也可以在IoC容器中配置,从而

不必为“访问业务层服务”额外编写代码。Spring还提供了通用的

DispatcherServlet和“即拿急用”的控制器类。请求与控制器之间的映射方式、

师徒的判断、本地化、以及其他重要服务都是可以插的,使得整个框架酷友更好

的扩展性。Spring web框架设计不仅仅局限于JSP,还可以与其他的视图技术--

例如Velocity--无缝的结合。

2.1.10 远程调用支持

Spring提供一种薄的抽象层用于访问远程服务,避免了在应用对象中硬编

码对服务的查找。线成支持的远程调用方式包括RMI,Caucho的Hessian和

Burlap Web服务的协议,和基于JAX-RPCWSDL的Web服务。

虽然Spring涉及了下至事务管理、上至web MVC的不同领域,它但它解决

问题的方式却是一以贯之的。一旦你学会了基本的配置方式,你将能够应用在许

多领域。资源,中间层对象,和Web组件都使用同一个bean配置机制的建立。

你可以将你的整个配置在一个单一的bean定义文件或分裂,它的应用模块或层;

选择是为应用程序开发人员到你。有没有需要在各种不同的格式,不同的配置文

件,遍布的应用。

第三章:J2EE之上的Spring

虽然Spring的许多部分可用于任何Java环境,它主要是一个J2EE应用框

架。例如,有链接到一个bean工厂的JNDI资源方便的类,如JDBC数据源和EJB

和JTA,分布式事务管理一体化。在大多数情况下,应用程序对象不需要与j2ee

api直接,提高可重用性和意义,不需要写冗长,难以测试,JNDI查找。

因此,Spring允许应用程序代码的无缝集成到J2EE环境不被不必要地捆绑

在一起。你可以建立在J2EE服务,让您的应用程序,如果没有复杂的要求选择

18

重量轻的解决方案。例如,你需要使用JTA事务的策略,如果你面对分布式事务

的要求。为一个单一的数据库,有不依赖于一个J2EE容器替代策略。这些交易

和策略之间的切换只是配置;春天的一致的抽象避免任何需要更改应用程序代

码。

Spring访问EJB提供支持。这是一个重要的特征(甚至在“没有EJB的J2EE

一本有关)因为动态使用代理作为客户端业务代表无代码意味着春天可以使用本

地的无状态会话EJB的实现程度,而不是一个根本的建筑,选择。因此,如果你

想使用EJB,您可以在一个一致的架构;然而,你不需要让你的架构的基石,EJB。

今年春天功能可以使开发EJB应用程序更快,因为不需要编写自定义代码在服务

中心职责范围或业务代表。测试EJB客户端代码也容易得多,因为它不仅取决于

EJB的业务方法接口(这是不特定的,不是在EJB)或EJB JNDI API。

Spring也提供了实现EJB的支持,在方便的超类EJB实现类的形式,其中

负载基于部署描述符指定的环境变量的Spring轻量级容器。这是

一个强大的和方便的方式实现SLSBs或MDBS是细粒度的POJO立面:最佳实践,

如果你选择实现EJB应用。Spring的这些特性和EJB毫无冲突,因为它只是遵

循了公认的最佳实践而已。

Spring的主要目的是使J2EE更容易使用和促进良好的编程实践。Spring

不重新发明轮子,这样你会在spring找不到登录包,连接池,分布式事务协调

器。这些特征是由其他的开源项目,如Jakarta Commons测井提供(Spring使

用其所有的日志输出),Jakarta Commons DBCP(可作为局部数据源)和ObjectWeb

JOTM(可作为事务管理器)或通过你的J2EE应用服务器。出于同样的原因,Spring

不提供O/R映射层:有良好的解决问题的方法,如Hibernate,JDO。

Spring的目标是使现有的技术更容易使用。例如,虽然Spring不是低级事

务协调业务,它提供了在jta或者任何交易策略的一个抽象层。Spring为

Hibernate提供的中间层的基础设施也很受欢迎,因为它提供了像

SessionFactory的设置,许多常见问题可以解决,ThreadLocal会议,与异常处

理。与Spring HibernateTemplate类,Hibernate DAO实现方法可以减少到一

个衬垫,同时适当参与交易。

Spring框架的目的并不是要取代J2EE中间层服务。这是一个应用程序框架,

19

使访问低级J2EE容器服务更容易。此外,它提供了在某些情况下,某些J2EE

服务的轻量级的替代品,如代替JTA JDBC基础交易策略时,只使用一个数据库。

基本上,Spring将帮助你编写极具可伸缩性的应用程序。

第四章:web应用中的Spring

在J2EE环境中,Spring有一种典型的用法:为J2EE web应用提供逻辑中

间层的基本骨架。Spring提供了“web应用上下文”的概念,将一个强大的轻量

级IoC容器无缝结合到web环境中,各种web层程序--不管是Struts、webWork、

JSF、Spring web MVC还是其他自制的方案--都可以使用IoC容器。

下面的代码显示了这样一个Web应用程序上下文的一个典型的例子。在一个

典型的Spring web应用中,文件驻留在WEB-INF目录,

包含bean的声明(遵循“spring-beans”DTD)。这个文件中定义了业务对象和

资源对象,如“myDataSource”、“myInventoryManager”和“myProductManager”

等。Spring将负责管理所有这些bean的配置、关联和生命周期。

ManagerDataSource”>

.

Driver

jdbc:mysql:myds

DefaultInventoryManager”>

DefaultProductManager”>

true

20

在默认情况下,所有的bean都是通过Singleton模式创建的:每个应用上

下文中只有一个实例。当Spring开始构造上述应用上下文时,

“myInventoryManager”bean将自动获得生命的DataSource对象

(“myDataSource”bean):随后,“myProductManager”也会获得

“myInventoryMnager”bean的引用。这些对象(也就是Spring属于常说的

“bean”)只需要暴露相应的bean属性或者后遭子参数即可,而不需要进行任何

特定的查找操作。

我们在中定义一个监听器(ContextLoaderListener),用于加载根

应用上下文(root applicatiob context)。这个监听器定义如下:

tLoaderListener

...

Web应用程序的初始化后,根Web应用程序上下文将作为ServletContext

的属性对整个Web应用程序,以通常的方式。它可以很容易地通过取相应的属性,

从那里检索,或通过便利的方法。

licationcontextutils。这意味着应用程序的上下文将

在任何Web资源访问ServletContext可用,如Servlet,JSP,过滤器,或Struts

动作,如下:

WebApplicationContext WAC = webapplicationcontextutils。

getwebapplicationcontext(ServletContext);

Spring Web MVC框架允许web控制器被定义为在应用程序上下文中的孩子,

21

每一个调度servlet。这种控制器可以表达依赖于豆类中的根的应用程序上下文

中通过简单的bean的引用。因此,典型的Spring Web MVC应用程序不需要执行

一个应用程序上下文或bean工厂手工查找,或做任何其他形式的查找。

其他客户端对象是由应用程序上下文自己管理不:他们可以接收的协作对象

作为bean的引用。

第五章:核心bean工厂

在前面的章节中,我们已经看到在一个网络环境的Spring IoC容器典型用

途:提供便利类允许无缝集成,而不必担心底层容器的细节。然而,它确实帮助

的内部运作看明白春天经营集装箱。因此,现在我们将看看更详细的Spring bean

容器,从最低的建筑块:bean工厂。后来,我们将继续在应用程序上下文的概

念资源设置和细节。

一个轻量级容器的主要动机之一是用定制的工厂,经常发现在J2EE应用程

序的许多单身。Spring bean工厂提供了设置任何数量的应用程序对象的一个一

致的方式,无论是粗粒度组件或细粒度业务对象。应用反射和依赖注入,bean

工厂可以不需要知道Spring所有的组件的宿主。因此,我们称之为Spring的一

种非侵入性的应用程序框架。

第六章:基础接口

在Spring中,轻量级容器最基本的接口时

ctory。这是一个非常简单的接口,

所以如果没有任何现成的bean工厂实现能够满足你的要求(这种情况非常罕

见)。你也可以很容易地创建自己的实现。BeanFactory接口提供了两个getBean

()方法,它们都可以根据String类型的名称查找获取bean实例,两者的不同

之处在于:其中一个getBean()方法允许使用者检查获得的bean是否具有所需

的类型(如果类型不符,会抛出一个BeanNotOfRequireTypeExpection异常)。

public interface BeanFactory {

Object getBean(String name) throws BeansException;

Object

getBean(String name,

22

Class requiredType) throws

BeansException;

boolean containsBean(String name);

boolean isSingleton(String name) throws

NoSuchBeanDefinitionException;

String[] getAliases(String name) throws

NoSuchBeanDefinitionException;

}

使用者可以通过issingleton()方法检查牧歌特定名称声明的bean被定为

Singleton还是Prototype。如果bean被定义为Singleton,所有对getBean()

方法的调用将返回同一个对象实例的引用;如果bean被定义为Prototype,每

次对getBean()的调用都将新建一个独立的对象实例。

如果某个bean配置了别名,getAliases()方法将返回它所有的别名。借助

这种机制,我们可以为bean提供更具描述力的名称,而不必受特定的bean工厂

存储机制的约束--例如XML文档对id属性的取值就有诸多限制。

在大多数的BeanFactory实现方法是意识到一个层次,可实施的一部分。如

果一个bean是不是在目前厂发现,母厂会问,直到根厂。从一个人的角度,在

这样一个层次结构的所有工厂会合并成一个。在祖先的上下文的bean定义中是

可见的后代,而不是反。

BeanFactory接口的大多数实现不仅提供给了一个可以按名称查询的对象

注册表,对于“用IoC配置这些对象”也提供了丰富的支持。例如,他们可以管

理对象之间的依赖关系,也可以将简单属性值赋给对象。在下一节,我们将看到

如何在一个简单、直观的XML结构中描述这些配置信息。

大多数的BeanFactory接口实现不只是提供一个注册的对象的名称;他们提

供配置这些对象使用IOC丰富的支持。例如,他们管理的托管对象之间的关联,

23

以及简单的性质。在下一节,我们将看看这样的配置可以在一个简单而直观的

XML结构表达。

lebeanfactory子接口可以

列出工厂中所有的bean。这个子接口提供了一系列方法,可以用于获得工厂中

定义bean的数量、所有bean的名称、具有特定类型的所有的名称等:

public interface ListableBeanFactory extends BeanFactory {

int getBeanDefinitionCount();

String[] getBeanDefinitionNames();

String[] getBeanDefinitionNames(Class type);

boolean containsBeanDefinition(String name);

Map getBeansOfType(Class type, boolean includePrototypes,

boolean includeFactoryBeans) throws BeansException

}

ListableBeanFactory可以获得管理对象的相关信息,可以利用这一能力来

实现这样的对象:这种对象需要与一组别的对象协作,并且只有到运行时才知道

与其协作的究竟是哪些对象。

相反,BeanFactory接口,在ListableBeanFactory方法适用于目前的工厂

实例和不带一个层次的帐户,工厂可能是部分。该

ctoryutils类提供了类似的方法,遍历整个

工厂层次。

Spring的bean工厂有很多种方法,从简单的bean配置J2EE资源整合和AOP

代理生成。bean工厂是中央的,一致的方式设置任何一种在春天,应用对象是

否刀,业务对象,或网络控制器。注意,应用对象很好需要直接用到BeanFactory

接口--它们通常都在工厂中配置、组装,不需要针对Spring编写任何特殊的代

码。

如果只需要使用bean工厂,Spring发布了一个很小的文

件,可以植入任何种类的应用中去。除了J2SE 1.3(以及用于XML解析的JAXP)

之外,它唯一依赖的第三方只有Jakarta Commons Logging API。

24

出处:网络

25


本文标签: 对象 框架 提供