| | + title | Ref. /chapter[1]/translation[1] |
| Original | Traduction | Beans, BeanFactory and the ApplicationContext | Beans, BeanFactory et l'ApplicationContext | sect1
| | + title | Ref. /chapter[1]/sect1[1]/translation[1] |
| Original | Traduction | Introduction | Introduction |
| + para | Ref. /chapter[1]/sect1[1]/translation[2] |
| Original | Traduction | Two of the most elementary and important packages in Spring are the
org.springframework.beans and
org.springframework.context packages. Code in these
packages provides the basis for Spring's Inversion of
Control (alternately called Dependency
Injection) features. The BeanFactory
provides an advanced configuration mechanism capable of managing beans
(objects) of any nature, using potentially any kind of storage facility.
The ApplicationContext
builds on top of the BeanFactory and adds other functionality such as
easier integration with Springs AOP features, message resource handling
(for use in internationalization), event propagation, declarative
mechanisms to create the ApplicationContext and optional parent contexts,
and application-layer specific contexts such as the
WebApplicationContext, among other enhancements. | Deux des plus importantes packages de Spring sont org.springframework.beans
et org.springframework.context. Le code de ces packages fournit
les dispositifs de base pour réaliser l'Inversion de Contrôle
(alternativement appelé Injection de Dépendance).
L'interface BeanFactory
fournit un mécanisme avancé de configuration des beans managés de toute
sorte, utilisant potentiellement n'importe quel type de stockage.
L'interface ApplicationContext
est construite au dessus de la classe BeanFactory et ajoute d'autres dispositifs comme
une intégration plus facile avec l'AOP, la manipulation des messages (pour l'internationalisation),
la propagation des événements, les mécanismes déclaratifs pour créer l'ApplicationContext et
les contextes parents optionnels et des contextes spécifiques aux couches des applications
comme WebApplicationContext, parmi d'autres.
|
| + para | Ref. /chapter[1]/sect1[1]/translation[3] |
| Original | Traduction | In short, the BeanFactory provides the
configuration framework and basic functionality, while the
ApplicationContext adds enhanced capabilities to it,
some of them perhaps more J2EE and enterprise-centric. In general, an
ApplicationContext is a complete superset of a BeanFactory, and any
description of BeanFactory capabilities and behavior should be considered
to apply to ApplicationContexts as well. | En résumé, l'interface BeanFactory fournit la
configuration du framework et de ses fonctionnalités de base, tandis que
l'interface ApplicationContext ajoute des possibilités
perfectionnées, dont certaines sont plus orientées J2EE et axées pour les
applications d'entreprise. En général, un ApplicationContext est une surcouche
complète d'un BeanFactory, et toutes les descriptions des possibilités d'un BeaFactory
et comportement devraient être considérés comme appliquer aux ApplicationContexts
eux-mêmes.
|
| + para | Ref. /chapter[1]/sect1[1]/translation[4] |
| Original | Traduction | Users are sometimes unsure whether BeanFactory or ApplicationContext
are best suited for use in a particular situation. Normally when building
most applications in a J2EE-environment, the best option is to
use the ApplicationContext, since it offers all the features of
the BeanFactory and adds on to it in terms of features, while also
allowing a more declarative approach to use of some functionality, which
is generally desirable. The main usage scenario when you might prefer to
use the BeanFactory is when memory usage is the greatest concern (such as
in an applet where every last kilobyte counts), and you don't need all the
features of the ApplicationContext.
| Parfois les utilisateurs ne sont pas sûrs laquelle des deux interfaces
BeanFactory ou Application est bien adaptée pour un cas précis dans une situation
particulière. Normalement pour la construction d'applications dans un
environnement J2EE, la meilleure option est d'utiliser l'ApplicationContext,
puisqu'il offre tous les dispositifs de BeanFactory et lui en ajoute d'autres
tout en permettant également une approche déclarative pour l'utilisation de
certaines fonctionnalités, qui est générallement souhaité. Le principal scénario
d'utilisation où il est préférable d'utiliser BeanFactory, est quand la gestion
de la mémoire est une grand préoccupation (comme dans le cas d'applets où chaque kilo
octets compte), et tous les dispositifs de ApplicationContext sont nécessaires. |
| + para | Ref. /chapter[1]/sect1[1]/translation[5] |
| Original | Traduction | This chapter is roughly divided into two parts, the first part
covering the basic principles that apply to both the BeanFactory and the
ApplicationContext. The second part will cover some of the features that
only apply to the ApplicationContext. | Ce chapître est divisé en deux parties. La première couvre les principes
basiques qui s'appliquent aussi bien à BeanFactory qu'à ApplicationContext. La seconde
partie s'applique à des dispositifs qui ne s'appliquent qu'à ApplicationContext.
|
| | sect1
| | + title | Ref. /chapter[1]/sect1[2]/translation[1] |
| Original | Traduction | BeanFactory and BeanDefinitions - the basics | BeanFactory et BeanDefinitions - les bases | sect2
| | + title | Ref. /chapter[1]/sect1[2]/sect2[1]/translation[1] |
| Original | Traduction | The BeanFactory | La BeanFactory |
| + para | Ref. /chapter[1]/sect1[2]/sect2[1]/translation[2] |
| Original | Traduction | The BeanFactory
is the actual container which instantiates,
configures, and manages a number of beans. These beans typically
collaborate with one another, and thus have dependencies between
themselves. These dependencies are reflected in the configuration data
used by the BeanFactory (although some dependencies may not be visible
as configuration data, but rather be a function of programmatic
interactions between beans at runtime). | L'interface BeanFactory
est actuellement le conteneur qui instantie, configure
et gère un ensemble de beans. Ces beans collaborent typiquement avec d'autres
et ainsi ils ont des dépendances entre eux. Celles-ci sont reflétées dans la
configuration utilisée par BeanFactory (bien que des dépendances peuvent ne pas
être visible dans la configuration, elles peuvent plutôt être fonction d'intégrations
réalisées par la programmation à l'exécution). |
| + para | Ref. /chapter[1]/sect1[2]/sect2[1]/translation[3] |
| Original | Traduction | A BeanFactory is represented by the interface
org.springframework.beans.factory.BeanFactory, for
which there are multiple implementations. The most commonly used simple
BeanFactory implementation is
org.springframework.beans.factory.xml.XmlBeanFactory.
(This should be qualified with the reminder that ApplicationContexts are
a subclass of BeanFactory, and most users ultimately prefer to use XML
variants of ApplicationContext). | Une BeanFactory est représentée par l'interface
org.springframework.beans.factory.BeanFactory pour laquelle
il existe plusieurs implémentations. La plus simple et la plus communément
utilisée implémentation de BeanFactory est
org.springframework.beans.factory.xml.XmlBeanFactory.
(Il devrait être identifié que les ApplicationContexts sont des sous classes
de BeanFactory et que la plupart des utilisateurs préfèrent finalement
les variantes de ApplicationContext basées sur XML).
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[1]/translation[4] |
| Original | Traduction | Although for most scenarios, almost all user code managed by the
BeanFactory does not have to be aware of the BeanFactory, the
BeanFactory does have to be instantiated somehow. This can happen via
explicit user code such as: | Bien que, pour la plupart des scénarios, presque tout le code
géré par BeanFactory n'a pas besoin d'avoir conscience de celle-ci, la
BeanFactory doit être instancié. Cela se réalise explicitement avec
un code similaire:
|
| + programlisting | Ref. /chapter[1]/sect1[2]/sect2[1]/programlisting[1] |
| Original | Traduction | InputStream is = new FileInputStream("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(is); |
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[1]/translation[5] |
| Original | Traduction | or | ou |
| + programlisting | Ref. /chapter[1]/sect1[2]/sect2[1]/programlisting[2] |
| Original | Traduction | ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res); |
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[1]/translation[6] |
| Original | Traduction | or | ou |
| + programlisting | Ref. /chapter[1]/sect1[2]/sect2[1]/programlisting[3] |
| Original | Traduction | ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml", "applicationContext-part2.xml"});
// of course, an ApplicationContext is just a BeanFactory
BeanFactory factory = (BeanFactory) appContext; |
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[1]/translation[7] |
| Original | Traduction | For many usage scenarios, user code will not have to instantiate
the BeanFactory, since Spring Framework code will do it. For example,
the web layer provides support code to load a Spring ApplicationContext
automatically as part of the normal startup process of a J2EE web-app.
This declarative process is described here: | Dans beaucoup de scénarios d'utilisation, le code développé n'a
pas à instancier la BeanFactory, puisque le framework Spring le fera.
Par exemple, la couche web fournit un support pour charger un ApplicationContext
Spring automatiquement en tant que partie intégrante du processus de
démarrage d'une application web J2EE. La déclaration du processus est
décrite ici:
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[1]/translation[8] |
| Original | Traduction | While programmatic manipulation of BeanFactories will be described
later, the following sections will concentrate on describing the
configuration of BeanFactories. | Comme la manipulation par la programmation des BeanFactories sera
décrite plus tard, les sections suivantes se concentrent sur la description
de la configuration des BeanFactories.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[1]/translation[9] |
| Original | Traduction | A BeanFactory configuration consists of, at its most basic level,
definitions of one or more beans that the BeanFactory must manage. In an
XmlBeanFactory, these are configured as one or more
bean elements inside a top-level
beans element. | Une configuration de BeanFactory consiste, au niveau le plus basique,
à définir un ou plusieurs beans que la BeanFactory doit gérer. Dans une
XmlBeanFactory, ceux-ci sont configurés en tant qu'éléments
bean imbriqués dans un élément racine
beans.
|
| + programlisting | Ref. /chapter[1]/sect1[2]/sect2[1]/programlisting[4] |
| Original | Traduction | <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="..." class="...">
...
</bean>
<bean id="..." class="...">
...
</bean>
...
</beans> |
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[2]/sect2[2]/translation[1] |
| Original | Traduction | The BeanDefinition | BeanDefinition |
| + para | Ref. /chapter[1]/sect1[2]/sect2[2]/translation[2] |
| Original | Traduction | Bean definitions inside a DefaultListableBeanFactory variant (like
XmlBeanFactory) are represented as BeanDefinition objects, which contain
(among other information) the following details: | Les définitions des beans dans les variantes de DefaultListableBeanFactory
(comme XmlBeanFactory) sont représentées en tant qu'objets BeanDefinition, qui
contiennent (parmi d'autres informations) les détails suivants:
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[2]/itemizedlist[1]/listitem[1]/translation[1] |
| Original | Traduction | a class name: this is normally the actual implementation
class of the bean being described in the bean definition. However,
if the bean is to be constructed by calling a static
factory method instead of using a normal
constructor, this will actually be the class name of the factory
class. | un nom de classe: ceci est normalement la classe réelle
d'implémentation du bean décrit dans la définition du bean. Cependant,
si le bean est construit en appelant une méthode statique d'une
fabrique au lieu d'un constructeur normal,
ceci peut être le nom de la classe de la fabrique.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[2]/itemizedlist[1]/listitem[2]/translation[1] |
| Original | Traduction | bean behavioral configuration elements, which state how the
bean should behave in the container (i.e. prototype or singleton,
autowiring mode, dependency checking mode, initialization and
destruction methods) | les éléments de configuration du comportement du bean qui
établisse comme le bean devrait se comporter dans le conteneur
(i.e. prototype ou singleton, mode automatique de détection des
dépendances, mode de vérification des dépendances, méthodes
d'initialisation et de finalisation).
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[2]/itemizedlist[1]/listitem[3]/translation[1] |
| Original | Traduction | constructor arguments and property values to set in the
newly created bean. An example would be the number of connections
to use in a bean that manages a connection pool (either specified
as a property or as a constructor argument), or the pool size
limit. | les arguments du constructeur ou les valeurs des propriétés
à positionner sur le bean nouvellement créé. Un exemple pourrait
être le nombre de connexions à utiliser dans un bean qui gère un
pool de connexions (aussi bien spécifié en tant que propriété ou
argument d'un constructeur), ou la limite de taille du pool.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[2]/itemizedlist[1]/listitem[4]/translation[1] |
| Original | Traduction | other beans a bean needs to do its work, i.e.
collaborators (also specified as properties
or as constructor arguments). These can also be called
dependencies. | les autres beans dont un bean a besoin pour réaliser
ses traitements, i.e. collaborateurs
(également spécifiés comme propriétés ou arguments du
constructeur). Ceux-ci peuvement également être appelés
dépendances.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[2]/translation[3] |
| Original | Traduction | The concepts listed above directly translate to a set of elements
the bean definition consists of. Some of these element groups are listed
below, along with a link to further documentation about each of them. | Les concepts listés ci-dessus traduisent en un ensemble d'éléments
la définition d'un bean. Quelques groupes d'éléments sont listés ci-dessous,
avec un lien vers une documentation les décrivant.
|
| + title | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/translation[1] |
| Original | Traduction | Bean definition explanation | Explication de la définition d'un Bean |
| + entry | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/tgroup[1]/thead[1]/row[1]/translation[1] |
| Original | Traduction | Feature | Fonctionalité |
| + entry | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/tgroup[1]/thead[1]/row[1]/translation[2] |
| Original | Traduction | More info | Plus d'information |
| + entry | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/tgroup[1]/tbody[1]/row[1]/translation[1] |
| Original | Traduction | class | classe |
| + entry | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/tgroup[1]/tbody[1]/row[2]/translation[1] |
| Original | Traduction | id and name | identifiant et nom |
| + entry | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/tgroup[1]/tbody[1]/row[3]/translation[1] |
| Original | Traduction | singleton or prototype | singleton ou prototype |
| + entry | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/tgroup[1]/tbody[1]/row[4]/translation[1] |
| Original | Traduction | constructor arguments | arguments du constructor |
| + entry | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/tgroup[1]/tbody[1]/row[5]/translation[1] |
| Original | Traduction | bean properties | propriétés du bean |
| + entry | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/tgroup[1]/tbody[1]/row[6]/translation[1] |
| Original | Traduction | autowiring mode | mode détection automatique |
| + entry | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/tgroup[1]/tbody[1]/row[7]/translation[1] |
| Original | Traduction | dependency checking mode | mode de vérification des dépendences |
| + entry | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/tgroup[1]/tbody[1]/row[8]/translation[1] |
| Original | Traduction | initialization method | méthode d'initialisation |
| + entry | Ref. /chapter[1]/sect1[2]/sect2[2]/table[1]/tgroup[1]/tbody[1]/row[9]/translation[1] |
| Original | Traduction | destruction method | méthode de finalisation |
| + para | Ref. /chapter[1]/sect1[2]/sect2[2]/translation[4] |
| Original | Traduction | Note that a bean definition is represented by the real interface
org.springframework.beans.factory.config.BeanDefinition,
and its various sub-interfaces and implementations. However, it is very
unlikely that most user code would ever work with a
BeanDefinition. | Il est à noter que la définition d'un bean est représenté par une
réelle interface org.springframework.beans.factory.config.BeanDefinition,
et ses divers sous interfaces et implémentations. Cependant, il est très
peu probable que du code utilisateur ne travaille avec un BeanDefinition.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[2]/translation[5] |
| Original | Traduction | Besides bean definitions which contain information on how to
create a bean, a bean factory can also allow to register existing bean
instances. DefaultListableBeanFactory supports this through the
registerSingleton method, as defined by the
org.springframework.beans.factory.config.ConfigurableBeanFactory
interface. Typical applications purely work with bean definitions,
though. | En outre les définitions des beans qui contiennent des informations
sur la façon de créer un bean ou une fabrique de beans, peuvent de plus
autoriser l'utilisation d'instances existantes de beans.
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[2]/sect2[3]/translation[1] |
| Original | Traduction | The bean class | La classe du bean |
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/translation[2] |
| Original | Traduction | The class attribute is normally mandatory (see
and for the two exception) and is
used for one of two purposes. In the much more common case where the
BeanFactory itself directly creates the bean by calling its constructor
(equivalent to Java code calling new), the class
attribute specifies the class of the bean to be constructed. In the less
common case where the BeanFactory calls a static, so-called
factory method on a class to create the bean, the
class attribute specifies the actual class containing the static factory
method. (the type of the returned bean from the static factory method
may be the same class or another class entirely, it doesn't
matter). | L'attribut class est normalement obligatoire
(voir et pour les deux exceptions à la règle)
et est utilisé pour un ou deux buts. Dans la plupart des cas classiques où
la BeanFactory crée elle-même directement le bean en appelant son constructeur
(equivalent à l'appel de new), l'attribut class spécifie
la classe du bean à construire. Dans des cas moins fréquents où la BeanFactory
appèle une méthode statique équivalente à une fabrique
sur une classe pour créer le bean, l'attribut class spécifie la classe réelle
contenant la méthode statique de fabrication. (le type du bean renvoyé par cette
méthode peut être la même ou une autre classe, cela n'a aucune importance).
|
| + title | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[1]/translation[1] |
| Original | Traduction | Bean creation via constructor | Création d'un bean via un constructeur |
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[1]/translation[2] |
| Original | Traduction | When creating a bean using the constructor approach, all normal
classes are usable by Spring and compatible with Spring. That is, the
class being created does not need to implement any specific interfaces
or be coded in a specific fashion. Just specifying the bean class
should be enough. However, depending on what type of IoC you are going
to use for that specific bean, you may need a default (empty)
constructor. | En créant un bean en utilisant l'approche basée sur le constructeur,
toutes les classes normales sont utilisables par Spring et compatible
avec ce framework. Cela signifie que la classe étant créée, n'a pas besoin
d'implémenter aucune interface spécifique ou être développée d'une certaine
manière. Le fait d'uniquement spécifier la classe du bean devrait suffir.
Cependant, suivant le type d'IoC utilisé, il se peut d'un constructeur par
défaut (vide) soit nécessaire.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[1]/translation[3] |
| Original | Traduction | Additionally, the BeanFactory isn't limited to just managing
true JavaBeans, it is also able to manage virtually
any class you want it to manage. Most people
using Spring prefer to have actual JavaBeans (having just a default
(no-argument) constructor and appropriate setters and getters modeled
after the properties) in the BeanFactory, but it it's also possible to
have more exotic non-bean-style classes in your BeanFactory. If, for
example, you need to use a legacy connection pool that absolutely does
not adhere to the JavaBean specification, no worries, Spring can
manage it as well. | De plus, la BeanFactory n'est uniquement limitée à gérer
de véritable JavaBeans, elle est également capable de gérer pratiquement
n'importe quelle classe voulue. La plupart des
utilisateurs de Spring préfèrent avoir de vrais JavaBeans (ayant uniquement
un constructeur par défaut (sans argument) et des accesseurs en lecture
et écriture appropriés modélisés après les propriétés) dans
la BeanFactory, mais il est également possible d'avoir, dans la BeanFactory,
des classes plus exotiques n'adhérant pas au styles des beans. Si, par exemple,
vous avez besoin d'utiliser un pool de connexion qui n'adhère pas à la
spécification JavaBean, ne vous inquiètez pas, Spring peut quand même les
gérer.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[1]/translation[4] |
| Original | Traduction | Using the XmlBeanFactory you can specify your bean class as
follows: | En utilisant XmlBeanFactory, la classe de votre bean peut
être spécifiée de la manière suivante: |
| + programlisting | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[1]/programlisting[1] |
| Original | Traduction | <bean id="exampleBean"
class="examples.ExampleBean"/>
<bean name="anotherExample"
class="examples.ExampleBeanTwo"/> |
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[1]/translation[5] |
| Original | Traduction | The mechanism for supplying (optional) arguments to the
constructor, or setting properties of the object instance after it has
been constructed, will be described shortly. | Le méchanisme pour positionner (optionnel) les arguments d'un
constructeur ou les propriétés d'une instance d'un objet après que
celui-ci ait été créé, sera décrit sous peu.
|
| + title | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[2]/translation[1] |
| Original | Traduction | Bean creation via static factory method | Création d'un bean via une methode de fabrique statique |
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[2]/translation[2] |
| Original | Traduction | When defining a bean which is to be created using a static
factory method, along with the class attribute
which specifies the class containing the static factory method,
another attribute named factory-method is needed to
specify the name of the factory method itself. Spring expects to be
able to call this method (with an optional list of arguments as
described later) and get back a live object, which from that point on
is treated as if it had been created normally via a constructor. One
use for such a bean definition is to call static factories in legacy
code. | Au moment de définit un bean qui est créé en utilisant un méthode
statique de fabrique, en parallèle de l'attribut class
qui spécifie le nom de la classe la contenant, un autre attribut nommé
factory-method est nécessaire pour déterminer le nom
de la méthode de fabrique. Spring prévoit d'être capable de l'appeler
(avec une liste optionelle d'arguments comme décrit plus tard) et de
récupérer une instance qui pourra, à partir de ce moment, être traité
comme s'il avait été créé normalement via un constructeur. Une des
utilisations de ce type de définition est d'appeler des fabriques
statiques dans du code.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[2]/translation[3] |
| Original | Traduction | Following is an example of a bean definition which specifies
that the bean is to be created by calling a factory-method. Note that
the definition does not specify the type (class) of the returned
object, only the class containing the factory method. In this example,
createInstance must be a
static method. | L'exemple suivant décrit une définition de bean qui spécifie
que celui-ci doit être créé en appelant une méthode fabrique. Il est à
noter que la définition ne spécifie pas le type (classe) de retour de
l'objet mais seulement la classe contenant la méthode. Dans cet exemple,
createInstance doit être une méthode static.
|
| + programlisting | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[2]/programlisting[1] |
| Original | Traduction | <bean id="exampleBean"
class="examples.ExampleBean2"
factory-method="createInstance"/> |
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[2]/translation[4] |
| Original | Traduction | The mechanism for supplying (optional) arguments to the factory
method, or setting properties of the object instance after it has been
returned from the factory, will be described shortly. | Le méchanisme pour positionner (optionnel) les arguments d'un
constructeur ou les propriétés d'une instance d'un objet après que
celui-ci ait été créé, sera décrit sous peu.
|
| + title | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[3]/translation[1] |
| Original | Traduction | Bean creation via instance factory method | Creation d'un bean via une méthode de fabrique d'instance |
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[3]/translation[2] |
| Original | Traduction | Quite similar to using a static factory method to create a bean,
is the use of an instance (non-static) factory method, where a factory
method of an existing bean from the factory is called to create the
new bean. | La façon de créer un bean en utilisant une méthode de fabrique
d'instance est similaire à celle pour une méthode statique, où une
méthode d'un bean existant correspondant à une fabrique est appelé
pour créer un nouveau bean.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[3]/translation[3] |
| Original | Traduction | To use this mechanism, the class attribute
must be left empty, and the factory-bean attribute
must specify the name of a bean in the current or an ancestor bean
factory which contains the factory method. The factory method itself
should still be set via the factory-method
attribute. | Pour utiliser ce mécanisme, l'attribut class
doit être laissé vide et l'attribut factory-bean
doit spécifier le nom du bean une BeanFactory courante ou parente
qui contient une méthode de fabrique. Celle-ci devrait encore elle-même
être positionner via l'attribut factory-method.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[3]/translation[4] |
| Original | Traduction | Following is an example:
| Ce qui suite, illustre cela:
|
| + programlisting | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[3]/programlisting[1] |
| Original | Traduction | <!-- The factory bean, which contains a method called
createInstance -->
<bean id="myFactoryBean"
class="...">
...
</bean>
<!-- The bean to be created via the factory bean -->
<bean id="exampleBean"
factory-bean="myFactoryBean"
factory-method="createInstance"/> |
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[3]/sect3[3]/translation[5] |
| Original | Traduction | Although the mechanisms for setting bean properties are still to
be discussed, one implication of this approach is that the factory
bean itself can be managed and configured via Dependency Injection, by
the container. | Bien que les mécanismes pour positionner les propriétés des
beans doivent être encore détaillés, une implication de cette approche est que
la BeanFactory peut être gérée et configurée via l'Injection de Dépendence
par le conteneur.
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[2]/sect2[4]/translation[1] |
| Original | Traduction | The bean identifiers (id and
name) | Les identifiants d'un bean (id et
name) |
| + para | Ref. /chapter[1]/sect1[2]/sect2[4]/translation[2] |
| Original | Traduction | Every bean has one or more ids (also called identifiers, or names;
these terms refer to the same thing). These ids must be unique within
the BeanFactory or ApplicationContext the bean is hosted in. A bean will
almost always have only one id, but if a bean has more than one id, the
extra ones can essentially be considered aliases. | Chaque bean possède un ou plusieurs ids (également appelés
identifiants, ou noms; ces termes se réfèrent à la même chose). Ces ids
doivent être unique dans la BeanFactory ou l'ApplicationContext où le
bean se trouve. Un bean aura presque toujours un id, mais si un bean a plus
d'un id, ceux supplémentaires seront considérés comme des alias.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[4]/translation[3] |
| Original | Traduction | In an XmlBeanFactory (including ApplicationContext variants), you
use the id or name attributes to
specify the bean id(s), and at least one id must be specified in one or
both of these attributes. The id attribute allows you
to specify one id, and as it is marked in the XML DTD (definition
document) as a real XML element ID attribute, the parser is able to do
some extra validation when other elements point back to this one. As
such, it is the preferred way to specify a bean id. However, the XML
spec does limit the characters which are legal in XML IDs. This is
usually not really a constraint, but if you have a need to use one of
these characters, or want to introduce other aliases to the bean, you
may also or instead specify one or more bean ids (separated by a comma
(,) or semicolon (;) via the
name attribute. | Dans une XmlBeanFactory (incluant les variantes de ApplicationContext),
les attributs id ou name sont utilisés
pour spécifier l'(es) id(s) du bean et enfin un id doit être spécifié dans un
ou les deux attributs. L'attribut id vous permet de
spécifier un id, et comme cela est marqué dans la DTD XML (document de
définition) comme un, le parseur est capable de faire quelques validations
supplémentaires quand d'autres éléments pointent sur lui. En tant que tels,
il s'agit de la manière recommandée de spécifier l'id d'un bean. Cependant,
la spécification XML limite les caractères qui sont autorisés pour les
IDs XML. Ce n'est pas habituellement une limitation, mais si vous devez utiliser
l'un de ces caractères ou voulez ajouter d'autres alias au bean, vous pouvez
également ou au lieu spécifier un ou plusieurs ids (séparés une virgule
(,) ou un point virgule (;) avec
l'attribut name.
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[2]/sect2[5]/translation[1] |
| Original | Traduction | To singleton or not to singleton | singleton ou pas singleton |
| + para | Ref. /chapter[1]/sect1[2]/sect2[5]/translation[2] |
| Original | Traduction | Beans are defined to be deployed in one of two modes: singleton or
non-singleton. (The latter is also called a prototype, although the term
is used loosely as it doesn't quite fit). When a bean is a singleton,
only one shared instance of the bean will be
managed and all requests for beans with an id or ids matching that bean
definition will result in that one specific bean instance being
returned. | Les beans sont définis pour être déployés dans l'un des deux modes
suivants: singleton ou non-singleton. (Le dernier est également appelé
un prototype, bien que le terme ne soit pas tout à fait adéquat). Quand
un bean est un singleton, seulement une instance partagée
du bean sera gérée et toutes les requêtes sur les beans dont le ou les ids
correspondent à cette défintion utiliseront une instance spécifique retournée.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[5]/translation[3] |
| Original | Traduction | The non-singleton, prototype mode of a bean deployment results in
the creation of a new bean instance every time a
request for that specific bean is done. This is ideal for situations
where for example each user needs an independent user object or
something similar. | Le mode non-singleton ou prototype de déploiment d'un bean crée
une nouvelle instance du bean à chaque fois qu'une requête
sur un bean spécifique est faite. Ceci est idéal pour les situations où,
par exemple, chaque utilisateur a besoin d'un objet indépendant
de l'utilisateur ou une utilisation similaire.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[5]/translation[4] |
| Original | Traduction | Beans are deployed in singleton mode by default, unless you
specify otherwise. Keep in mind that by changing the type to
non-singleton (prototype), each request for a bean will result in a
newly created bean and this might not be what you actually want. So only
change the mode to prototype when absolutely necessary. | Les beans sont déployés en mode singleton par défaut, à moins
qu'il ne soit spécifié autre chose. Il faut garder à l'esprit qu'en changeant
le type à non-singleton (prototype), chaque requête pour un bean resultera
dans la création d'un bean nouvellement créé et ne sera pas peut-être
ce qui est réellement voulu. De ce fait, changer le mode à prototype
quand c'est absolument nécessaire.
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[5]/translation[5] |
| Original | Traduction | In the example below, two beans are declared of which one is
defined as a singleton, and the other one is a non-singleton
(prototype). exampleBean is created each and every
time a client asks the BeanFactory for this bean, while
yetAnotherExample is only created once; a reference
to the exact same instance is returned on each request for this
bean. | Dans l'exemple ci-dessous, deux beans sont déclarés dont l'un
est défini comme singleton, et l'autre est a non-singleton (prototype).
exampleBean est créé à chaque fois qu'un client demande
à la BeanFactory ce bean alors que yetAnotherExample
est créé une seule fois; une référence à la même instance est retourné
pour chaque requête sur le bean.
|
| + programlisting | Ref. /chapter[1]/sect1[2]/sect2[5]/programlisting[1] |
| Original | Traduction | <bean id="exampleBean"
class="examples.ExampleBean" singleton="false"/>
<bean name="yetAnotherExample"
class="examples.ExampleBeanTwo" singleton="true"/> |
|
| + para | Ref. /chapter[1]/sect1[2]/sect2[5]/translation[6] |
| Original | Traduction | Note: when deploying a bean in the prototype mode, the lifecycle
of the bean changes slightly. By definition, Spring cannot manage the
complete lifecycle of a non-singleton/prototype bean, since after it is
created, it is given to the client and the container does not keep track
of it at all any longer. You can think of Spring's role when talking
about a non-singleton/prototype bean as a replacement for the 'new'
operator. Any lifecycle aspects past that point have to be handled by
the client. The lifecycle of a bean in the BeanFactory is further
described in . | Note: quand a un bean est déployé dans le mode prototype, le
cycle de vie du bean change lègerement. Par définition, Spring ne peut
pas géré le cycle complet de vie d'un bean de type non-singleton/prototype
puisque, après qu'il soit créé, il est donné au client et le conteneur
ne garde plus de trace de lui. Vous pouvez voir le rôle de Spring comme
une remplacement de l'opération 'new'. Les aspects de cycle de vie doivent
être gérés par le client. Le cycle de vie d'un bean dans la BeanFactory
est décrit dans .
|
| |
| | sect1
| | + title | Ref. /chapter[1]/sect1[3]/translation[1] |
| Original | Traduction | Properties, collaborators, autowiring and dependency checking | Propriétés, collaborateurs, détection automatique et vérification de dépendance | sect2
| | + title | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[1] |
| Original | Traduction | Setting bean properties and collaborators | Positionnement des propriétés de beans et collaborateurs |
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[2] |
| Original | Traduction | Inversion of Control has already been referred to as
Dependency Injection. The basic principle is that
beans define their dependencies (i.e. the other objects they work with)
only through constructor arguments, arguments to a factory method, or
properties which are set on the object instance after it has been
constructed or returned from a factory method. Then, it is the job of
the container to actually inject those dependencies
when it creates the bean. This is fundamentally the inverse (hence the
name Inversion of Control) of the bean instantiating or locating its
dependencies on its own using direct construction of classes, or
something like the Service Locator pattern. While
we will not elaborate too much on the advantages of Dependency
Injection, it becomes evident upon usage that code gets much cleaner and
reaching a higher grade of decoupling is much easier when beans do not
look up their dependencies, but are provided with them, and additionally
do not even know where the dependencies are located and of what actual
type they are. | L'Inversion de Contrôle a déjà été désigné comme Injection
de Dépendance. Le principe de base est que les beans définissent
leurs dépendances (i.e. les autres objets avec lesquels ils travaillent)
uniquement par le biais d'arguments de constructeurs, arguments d'une
méthode de fabrique ou propriétés qui sont positionnées sur l'instance
de l'objet qu'il ait été instancié ou retourné par une méthode de
fabrique. Puis, le conteneur a réellement la responsabilité
d'injecter ces dépendances au moment il crée le
bean. Ceci est fondamentalement l'inversion (par conséquent le nom
d'Inversion de Contrôle) de l'instanciation du bean ou de la localisation de
ses dépendances par lui-même en utilisant l'instanciation direct de
classes, ou un pattern comme le Service de Localication.
...
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[3] |
| Original | Traduction | As touched on in the previous paragraph, Inversion of
Control/Dependency Injection exists in two major variants: | Comme cela a été abordé dans le précédent paragraphe, il existe
deux variantes majeures de l'Inversion de Contrôle/Injection de
Dépendance: |
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/itemizedlist[1]/listitem[1]/translation[1] |
| Original | Traduction | setter-based dependency injection is
realized by calling setters on your beans after invoking a
no-argument constructor or no-argument static factory method to
instantiate your bean. Beans defined in the BeanFactory that use
setter-based dependency injection are true
JavaBeans. Spring generally advocates usage of
setter-based dependency injection, since a large number of
constructor arguments can get unwieldy, especially when some
properties are optional. | L'injection de dépendance basé sur le positionnement
est réalisée en appelant les méthodes de positionnement sur les beans
après l'invocation d'un constructeur sans argument ou une méthode
de fabrique statique sans argument pour instancier le bean. Les beans
qui utilise ce type d'injection de dépendance sont de vrais JavaBeans.
Spring recommande l'usage de ce type d'injection de dépendance, puisqu'un
grand nombre d'arguments de constructeurs peut être difficile à manipuler,
particulièrement quand certaines propriétés sont optionnelles.
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/itemizedlist[1]/listitem[2]/translation[1] |
| Original | Traduction | constructor-based dependency injection
is realized by invoking a constructor with a number of arguments,
each representing a collaborator or property. Additionally,
calling a static factory method with specific arguments, to
construct the bean, can be considered almost equivalent, and the
rest of this text will consider arguments to a constructor and
arguments to a static factory method similarly. Although Spring
generally advocates usage of setter-based dependency injection for
most situations, it does fully support the constructor-based
approach as well, since you may wish to use it with pre-existing
beans which provide only multi-argument constructors, and no
setters. Additionally, for simpler beans, some people prefer the
constructor approach as a means of ensuring beans cannot be
constructed in an invalid state. | L'injection de dépendance basé sur le constructeur
est réalisée en invoquant le constructeur avec un nombre d'arguments,
chacun représentant un collaborateur ou une propriété. En plus, appeler
une méthode de fabrique statique avec des arguments spécifiques, pour
construire le bean, peut être considéré comme presque équivalent, et
le reste de ce qui suit, considérera les arguments d'un constructeur
et d'une méthode de fabrique statique comme similaire. Bien que Spring
préconise l'utilisation de l'injection de dépendance basée sur le
positionnement, il supporte complètement cette approche, puisqu'il se
peut que vous ayez à utiliser des beans pré-existants qui fournissent
uniquement des constructeurs pour passer les arguments et aucune
méthode pour les positionner. De plus, pour des beans plus simples,
certaines personnes préfèrent l'approche constructeur comme un moyen de
s'assurer que les beans ne puissent pas être dans un état invalides.
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[4] |
| Original | Traduction | The BeanFactory supports both of these
variants for injecting dependencies into beans it manages. (It in fact
also supports injecting setter-based dependencies after some
dependencies have already been supplied via the constructor approach.)
The configuration for the dependencies comes in the form of a
BeanDefinition, which is used together with JavaBeans
PropertyEditors to know how to convert properties
from one format to another. The actual values being passed around are
done in the form of PropertyValue objects. However,
most users of Spring will not be dealing with these classes directly
(i.e. programmatically), but rather with an XML definition file which
will be converted internally into instances of these classes, and used
to load an entire BeanFactory or ApplicationContext. | La interface BeanFactory supportent ces
deux variantes pour injecter les dépendances dans les beans qu'elle gère.
(En fait elle supporte également l'injection de dépendances basé sur
le positionnement après que certaines dépendances aient été renseignées
avec l'approche basée sur le constructeur.) La configuration des dépendances
se réalise via une BeanDefinition, qui est utilisée
de concert avec des PropertyEditors JavaBeans pour savoir
comment convertir les propriétés d'un format à un autre. Les véritables
valeurs passées, sont fournies sous la forme d'objets PropertyValue.
Cependant, la plupart des utilisateurs de Spring n'auront pas à se préoccuper
de ces classes directement (i.e. par la programmation), mais utiliserons plutôt
un fichier de définition XML qui sera converti en interne en des instances
de ces classes, et utilisé pour charger une BeanFactory ou un
ApplicationContext entier.
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[5] |
| Original | Traduction | Bean dependency resolution generally happens as
follows: | La résolution des dépendaces d'un bean se produit
générallement de la manière suivante: |
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/orderedlist[1]/listitem[1]/translation[1] |
| Original | Traduction | The BeanFactory is created and initialized with a
configuration which describes all the beans. Most Spring users use
a BeanFactory or ApplicationContext variant which supports XML
format configuration files. | La BeanFactory est créée et initialisée avec une
configuration qui décrit tous les beans. La plupart des utilisateurs
de Spring utilisent une variante de BeanFactory ou ApplicationContext
qui supporte les fichiers de configuration au format XML.
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/orderedlist[1]/listitem[2]/translation[1] |
| Original | Traduction | Each bean has dependencies expressed in the form of
properties, constructor arguments, or arguments to the
static-factory method when that is used instead of a normal
constructor. These dependencies will be provided to the bean,
when the bean is actually created. | Chaque bean a ses dépendances exprimés sous forme
de propriétés, arguments de constructeur ou arguments
d'une méthode de fabrique statique quand cela est utilisé
au lieu du constructeur normal.
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/orderedlist[1]/listitem[3]/translation[1] |
| Original | Traduction | Each property or constructor-arg is either an actual
definition of the value to set, or a reference to another bean in
the BeanFactory. In the case of the ApplicationContext, the
reference can be to a bean in a parent ApplicationContext. | Chaque propriété ou argument de constructeur est soit
une réelle définition d'une valeur à positionner, soit une
référence à un autre bean dans la BeanFactory. Dans le cas de
l'ApplicationContext, la référence peut être vers un
ApplicationContext parent. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/orderedlist[1]/listitem[4]/translation[1] |
| Original | Traduction | Each property or
constructor argument which is a value must be able to be converted
from whatever format it was specified in, to the actual type of
that property or constructor argument. By default Spring can
convert a value supplied in string format to all built-in types,
such as int, long,
String, boolean, etc.
Additionally, when talking about the XML based BeanFactory
variants (including the ApplicationContext variants), these have
built-in support for defining Lists, Maps, Sets, and Properties
collection types. Additionally, Spring uses JavaBeans
PropertyEditor definitions to be able to
convert string values to other, arbitrary types. (You can provide
the BeanFactory with your own PropertyEditor
definitions to be able to convert your own custom types; more
information about PropertyEditors and how to manually add custom
ones, can be found in ). When a bean
property is a Java Class type, Spring allows you to specify the
value for that property as a string value which is the name of the
class, and the ClassEditor PropertyEditor,
which is built-in, will take care of converting that class name to
an actual Class instance. | Chaque propriété
ou argument de constructeur qui a une valeur doit pouvoir être
converti de n'importe quel format spécifié vers le type réel de la
propriété ou de l'argument. Par défaut Spring peut convertir une
valeur fournie sous forme de chaînes de caractères dans n'importe
quel type intégré, comme int,
long, String, boolean,
etc. De plus, quand on parle des variants de la BeanFactory basées
sur XML (incluant les variantes d'ApplicationContext), il y a des
supports intégrés pour les types de collection Lists, Maps, Sets, et
Properties. Par ailleurs, Spring utilisent les définitions de
PropertyEditor des JavaBeans pour être capable
de convertir des chaînes de caractères dans d'autres types de
manière arbitraire. (Vous pouvez fournir à la BeanFactory vos propres
définitions de PropertyEditor pour convertir vos
propres types. Plus d'information à ce sujet et comment les ajouter
manuellement peuvent être trouvées dans ). Quand une propriété
d'un bean est une classe Java, Spring vous permettent de spécifier la
valeur de cette propriété en tant que chaîne qui représente le nom
de la classe et le PropertyEditor ClassEditor qui
est intégré, et prend en charge la conversion du nom de la classe
en une instance réelle de la classe. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/orderedlist[1]/listitem[5]/translation[1] |
| Original | Traduction | It is important to realize that Spring validates the
configuration of each bean in the BeanFactory when the BeanFactory
is created, including the validation that properties which are
bean references are actually referring to valid beans (i.e. the
beans being referred to are also defined in the BeanFactory, or in
the case of ApplicationContext, a parent context). However, the
bean properties themselves are not set until the bean is
actually created. For beans which are singleton and set
to be pre-instantiated (such as singleton beans in an
ApplicationContext), creation happens at the time that the
BeanFactory is created, but otherwise this is only when the bean
is requested. When a bean actually has to be created, this will
potentially cause a graph of other beans to be created, as its
dependencies and its dependencies' dependencies (and so on) are
created and assigned. | Il est important d'être conscient que Spring validate la
configuration de chaque bean de la BeanFactory quand celle-ci est
créée, incluant la validation des propriétés qui font référence à
des beans valides (i.e. les beans dont on fait référence, sont
également définis dans la BeanFactory, ou dans le cas d'ApplicationContext,
dans un contexte parent). Cependant, les propriétés elles-mêmes du
bean ne sont pas positionnées jusqu'à ce que le bean soit
réellement créé. Pour les beans qui sont des singletons
et configurés pour être préinstanciés (comme les beans de type singleton
dans un ApplicationContext), la création survient au moment où la
BeanFactory est créée, mais autrement cela se produit uniquement
quand le bean est demandé. Quand un bean doit réellement être créé,
cela pourra potientiellement résulter dans un graph d'objets à
créer comme les dépendances et les dépendances de ces dépendances
(et ainsi de suite) doivent être créées et assignées. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/orderedlist[1]/listitem[6]/translation[1] |
| Original | Traduction | You can generally trust Spring to do the right thing. It
will pick up configuration issues, including references to
non-existent beans and circular dependencies, at BeanFactory
load-time. It will actually set properties and resolve
dependencies (i.e. create those dependencies if needed) as late as
possible, which is when the bean is actually created. This does
mean that a BeanFactory which has loaded correctly, can later
generate an exception when you request a bean, if there is a
problem creating that bean or one of its dependencies. This could
happen if the bean throws an exception as a result of a missing or
invalid property, for example. This potentially delayed visibility
of some configuration issues is why ApplicationContext by default
pre-instantiates singleton beans. At the cost of some upfront time
and memory to create these beans before they are actually needed,
you find out about configuration issues when the
ApplicationContext is created, not later. If you wish, you can
still override this default behavior and set any of these
singleton beans to lazy-load (not be pre-instantiated). | Vous pouvez généralement avoir confiance en Spring pour
faire le bon choix. Il ... les problèmes de configuration, incluant
les beans qui n'existent pas and les dépendences circulaires au
chargement de la BeanFactory. Il va réellement positionner les
propriétés et résoudre les dépendences (i.e. créer ces dépendences
si necessaire) le plus tard possible c'est-à-dire quand le bean
est réellement créé. Cela signifie qu'une BeanFactory qui s'est
correctement chargée, peut par la suite générer une exception quand
un bean est demandé, s'il y a un problème pour créer un bean ou
une de ces dépendences. Cela peut arriver si le bean lève une exception
en réponse à une propriété invalide ou manquante, par exemple.
Cela retarde potentiellement la visibilité de ces problématiques
de configuration et c'est pour cette raison que l'ApplicationContext
pré-instancie par défaut les beans de type singleton. Au prix d'un
surcout en terme de time et de mémoire pour créer ces beans avant
d'en avoir besoin, vous découvrez les éventuels problèmes de configuration
quand l'ApplicationContext est créé, pas après. Si vous le désirez,
vous pouvez également surcharger ce comportement par défaut et
spécifier n'importe quel de ces singletons d'être charger à la
demande (lazy-load) (ils ne sont pas préinstanciés).
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[6] |
| Original | Traduction | Some examples: | Quelques exemples: |
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[7] |
| Original | Traduction | First, an example of using the BeanFactory for setter-based
dependency injection. Below is a small part of an
XmlBeanFactory configuration file specifying some
bean definitions. Following is the code for the actual main bean itself,
showing the appropriate setters declared. | Premièrement, voici un exemple d'utilisation de la BeanFactory
pour une injection de dépendences basée sur le positionnement.
En dessous se trouve une petite partie d'un fichier de configuration
d'une XmlBeanFactory, spécifiant quelques définitions
de beans. Ensuite se trouve le code du bean principal lui-même,
montrant les méthodes de positionnement appropriées.
|
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[1]/programlisting[1] |
| Original | Traduction | <bean id="exampleBean" class="examples.ExampleBean">
<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<property name="beanTwo"><ref bean="yetAnotherBean"/></property>
<property name="integerProperty"><value>1</value></property>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/> |
|
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[1]/programlisting[2] |
| Original | Traduction | public class ExampleBean {
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;
public void setBeanOne(AnotherBean beanOne) {
this.beanOne = beanOne;
}
public void setBeanTwo(YetAnotherBean beanTwo) {
this.beanTwo = beanTwo;
}
public void setIntegerProperty(int i) {
this.i = i;
}
} |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[8] |
| Original | Traduction | As you can see, setters have been declared to match against
the properties specified in the XML file. (The properties from the XML
file, directly relate to the PropertyValues object
from the RootBeanDefinition) | Comme vous pouvez le voir, les méthodes de positionnement
ont été déclarées pour correspondre exactement aux propriétés
spécifiées dans le fichier XML. (Les propriétés du fichier XML,
font directement référence à l'objet PropertyValues
de RootBeanDefinition). |
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[9] |
| Original | Traduction | Now, an example of using the BeanFactory for IoC type 3
(constructor-based dependency injection). Below is a snippet from an XML
configuration that specifies constructor arguments and the actual bean
code, showing the constructor: | Maintenant, voici un exemple de BeanFactory pour l'utilisation
d'IoC type 3 (injection de dépendence basée sur les constructeurs). En
dessous se trouve un extrait de la configuration XML qui spécifie les
arguments du constructeur et le code réel du bean en montrant bien
le constructeur: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[1]/programlisting[3] |
| Original | Traduction | <bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg><ref bean="anotherExampleBean"/></constructor-arg>
<constructor-arg><ref bean="yetAnotherBean"/></constructor-arg>
<constructor-arg type="int"><value>1</value></constructor-arg>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/> |
|
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[1]/programlisting[4] |
| Original | Traduction | public class ExampleBean {
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;
public ExampleBean(AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {
this.beanOne = anotherBean;
this.beanTwo = yetAnotherBean;
this.i = i;
}
} |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[10] |
| Original | Traduction | As you can see, the constructor arguments specified in the
bean definition will be used to pass in as arguments to the constructor
of the ExampleBean. | Comme vous pouvez le voir, les arguments du constructeur
spécifiés dans la définition du bean seront utilisés pour injecter
des arguments au constructeur de la classe ExampleBean. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[11] |
| Original | Traduction | Now consider a variant of this where instead of using a
constructor, Spring is told to call a static factory method to return an
instance of the object.: | Désormais considérons une variante de cela où, au lieu
d'utiliser un constructeur, on demande à Spring d'appeler une
méthode de fabrique statique pour retourner une instance de
l'objet: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[1]/programlisting[5] |
| Original | Traduction | <bean id="exampleBean" class="examples.ExampleBean"
factory-method="createInstance">
<constructor-arg><ref bean="anotherExampleBean"/></constructor-arg>
<constructor-arg><ref bean="yetAnotherBean"/></constructor-arg>
<constructor-arg><value>1</value></constructor-arg>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/> |
|
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[1]/programlisting[6] |
| Original | Traduction | public class ExampleBean {
...
// a private constructor
private ExampleBean(...) {
...
}
// a static factory method
// the arguments to this method can be considered the dependencies of the bean that
// is returned, regardless of how those arguments are actually used.
public static ExampleBean createInstance(
AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {
ExampleBean eb = new ExampleBean(...);
// some other operations
...
return eb;
}
} |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[1]/translation[12] |
| Original | Traduction | Note that arguments to the static factory method are supplied via
constructor-arg elements, exactly the same as if a
constructor had actually been used. These arguments are optional. Also,
it is important to realize that the type of the class being returned by
the factory method does not have to be of the same type as the class
which contains the static factory method, although in this example it
is. An instance (non-static) factory method, mentioned previously, would
be used in an essentially identical fashion (aside from the use of the
factory-bean attribute instead of the
class attribute), so will not be detailed
here. | Il est à noter que les arguments de la méthode de fabrique
statique sont fournis via les éléments constructor-arg
exactement de la même manière que si un constructeur avait été utilisé
en réalité. Ces arguments sont optionnels. En outre, il est important
de comprendre que les type de la classe retournée par cette méthode
ne doit pas être obligatoirement du même type que la classe qui contient
la méthode de fabrique statique, même si c'est le cas dans cet exemple.
Une méthode de fabrique d'instance (non statique), mentionnée précédemment,
serait utilisée essentiellement d'une manière identique (si ce n'est
l'utilisation de l'attribut factory-bean à la place de
l'attribut class), et ne sera donc pas détaillé ici. |
| | sect2
| | + title | Ref. /chapter[1]/sect1[3]/sect2[2]/translation[1] |
| Original | Traduction | Constructor Argument Resolution | Résolution des Arguments de Constructeur |
| + para | Ref. /chapter[1]/sect1[3]/sect2[2]/translation[2] |
| Original | Traduction | Constructor argument resolution matching occurs using the
argument's type. When another bean is referenced, the type is known, and
matching can occur. When a simple type is used, such as
<value>true<value>, Spring cannot
determine the type of the value, and so cannot match by type without
help. Consider the following class, which is used for the following two
sections: | La résolution des arguments du constructeur se réalise en utilisant
leur type. Quand un autre bezn est référencé, le type est connu et la
correspondance peut être effectuée. Quand un type simple est utilisé, comme
<value>true<value>, Spring ne peut déterminer
le type correspondant à la valeur et ne peut donc pas faire la correspondance
par type sans aide. Considérons la classe suivante, qui est utilisée dans
les deux sections suivantes: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[2]/programlisting[1] |
| Original | Traduction | package examples;
public class ExampleBean {
private int years; //No. of years to the calculate the Ultimate Answer
private String ultimateAnswer; //The Answer to Life, the Universe, and Everything
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
} |
|
| + title | Ref. /chapter[1]/sect1[3]/sect2[2]/sect3[1]/translation[1] |
| Original | Traduction | Constructor Argument Type Matching | Correspondance des Types des Arguments de Constructeur |
| + para | Ref. /chapter[1]/sect1[3]/sect2[2]/sect3[1]/translation[2] |
| Original | Traduction | The above scenario can use type matching
with simple types by explicitly specifying the type of the constructor
argument using the type attribute. For example: | Le scénario ci-dessus peut utiliser la
correpondance de type avec des types simples en spécifiant explicitement
le type des arguments du constructeur en utilisant l'attribut
type. Par exemple: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[2]/sect3[1]/programlisting[1] |
| Original | Traduction | <bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int"><value>7500000</value></constructor-arg>
<constructor-arg type="java.lang.String"><value>42</value></constructor-arg>
</bean> |
|
| + title | Ref. /chapter[1]/sect1[3]/sect2[2]/sect3[2]/translation[1] |
| Original | Traduction | Constructor Argument Index | Index des Arguments de Constructeur |
| + para | Ref. /chapter[1]/sect1[3]/sect2[2]/sect3[2]/translation[2] |
| Original | Traduction | Constructor arguments can have their index specified explicitly
by use of the index attribute. For example: | Les arguments de constructeur peuvent avoir leur index
spécifié explicitement en utilisant l'attribut index.
Par exemple: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[2]/sect3[2]/programlisting[1] |
| Original | Traduction | <bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0"><value>7500000</value></constructor-arg>
<constructor-arg index="1"><value>42</value></constructor-arg>
</bean> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[2]/sect3[2]/translation[3] |
| Original | Traduction | As well as solving the ambiguity problem of
multiple simple values, specifying an index also solves the problem of
ambiguity where a constructor may have two arguments of the same type.
Note that the index is 0 based. | De la même manière qu'il résout l'ambiguité liée
à de multiples valeurs simples, spécifier un index résoud également
l'ambiguité quand un constructeur a deux arguments du même type.
Il est à noter que l'index démarre à 0. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[2]/sect3[2]/translation[4] |
| Original | Traduction | Specifying a constructor argument index is the preferred way of
performing constructor IoC. | Spécifier l'index d'un argument de constructeur est la façon
recommandée pour réaliser l'IoC basée sur les constructeurs. |
| | sect2
| | + title | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[1] |
| Original | Traduction | Bean properties and constructor arguments detailed | Les propriétés de bean et les arguments de constructeur détaillés |
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[2] |
| Original | Traduction | As mentioned in the previous section, bean properties and
constructor arguments can be defined as either references to other
managed beans (collaborators), or values defined inline. The
XmlBeanFactory supports a number of sub-element types
within its property and
constructor-arg elements for this purpose. | Comme mentionné dans la section précédante, les propriétés
de bean et les arguments de construteur peuvent être définies comme
étant soit des références à d'autres beans gérés par Spring
(collaborateurs) ou des valeurs définies directement à ce niveau.
La XmlBeanFactory supporte un grand nombre de
types de sous-éléménets dans ses éléments property
et constructor-arg pour réaliser cela. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[3] |
| Original | Traduction | The value element specifies a property or
constructor argument as a human-readable string representation. As
mentioned in detail previously,
JavaBeans PropertyEditors are used to convert these string values from a
java.lang.String to the actual property or argument
type. | L'élément value spécifie une propriété ou
un argument de constructeur dans sa représentation sous forme de chaînes
de caractères (directement lisible). Comme mentionné en détail précédemment,
les PropertyEditors JavaBeans sont utilisés pour convertir ces valeurs
sous forme de chaînes d'un type java.lang.String vers
le type réel de la propriété ou de l'arument.
|
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[1] |
| Original | Traduction | <beans>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<!-- results in a setDriverClassName(String) call -->
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/mydb</value>
</property>
<property name="username">
<value>root</value>
</property>
</bean>
</beans> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[4] |
| Original | Traduction | The null element is used to handle null values.
Spring treats empty arguments for properties and the like as empty
Strings. The following XmlBeanFactory configuration: | L'élément null est utilisé pour réaliser
des valeurs nulles. Spring traite les arguments vides pour les
propriétés comme des chaînes vides. La configuration suivante: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[2] |
| Original | Traduction | <bean class="ExampleBean">
<property name="email"><value></value></property>
</bean> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[5] |
| Original | Traduction | in the email property being set
to "", equivalent to the java code:
exampleBean.setEmail(""). The special
<null> element may be used to indicate a null
value, so that: | dans la propriété email positionnée à "" est équivalente au
code java: exampleBean.setEmail(""). L'élément
spécial <null> peut être utilisé pour indiquer
une valeur nulle et de ce fait: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[3] |
| Original | Traduction | <bean class="ExampleBean">
<property name="email"><null/></property>
</bean> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[6] |
| Original | Traduction | equivalent to the java code:
exampleBean.setEmail(null). | est équivalent au code java: exampleBean.setEmail(null). |
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[7] |
| Original | Traduction | The list, set,
map, and props elements allow
properties and arguments of Java type List,
Set, Map, and
Properties, respectively, to be defined and
set. | Les éléments list, set,
map, et props permettent définir
et de positionner des propriétés et des arguments de type Java
list, set, map,
and props respectivement. |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[4] |
| Original | Traduction | <beans>
...
<bean id="moreComplexObject" class="example.ComplexObject">
<!-- results in a setPeople(java.util.Properties) call -->
<property name="people">
<props>
<prop key="HarryPotter">The magic property</prop>
<prop key="JerrySeinfeld">The funny property</prop>
</props>
</property>
<!-- results in a setSomeList(java.util.List) call -->
<property name="someList">
<list>
<value>a list element followed by a reference</value>
<ref bean="myDataSource"/>
</list>
</property>
<!-- results in a setSomeMap(java.util.Map) call -->
<property name="someMap">
<map>
<entry key="yup an entry">
<value>just some string</value>
</entry>
<entry key="yup a ref">
<ref bean="myDataSource"/>
</entry>
</map>
</property>
<!-- results in a setSomeSet(java.util.Set) call -->
<property name="someSet">
<set>
<value>just some string</value>
<ref bean="myDataSource"/>
</set>
</property>
</bean>
</beans> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[8] |
| Original | Traduction | Note that the value of a Map entry, or a set value, can
also again be any of the elements: | Il est à noter que la valeur d'une entrée dans une Map
peut être n'importe lequel de ces éléments: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[5] |
| Original | Traduction | (bean | ref | idref | list | set | map | props | value | null) |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[9] |
| Original | Traduction | A bean element inside the
property element is used to define a bean value
inline, instead of referring to a bean defined elsewhere in the
BeanFactory. The inline bean definition does not need to have any id
defined. | Un élément bean dans un élément
property est utilisé pour définir un bean
directement, au lieu de faire une référence déjà défini quelque
part dans la BeanFactory. Cette définition ne nécessite de ne
définir aucun attribut id. |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[6] |
| Original | Traduction | <bean id="outer" class="...">
<!-- Instead of using a reference to target, just use an inner bean -->
<property name="target">
<bean class="com.mycompany.PersonImpl">
<property name="name"><value>Tony</value></property>
<property name="age"><value>51</value></property>
</bean>
</property>
</bean> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[10] |
| Original | Traduction | idref element is simply a shorthand and
error-proof way to set a property to the String id
or name of another bean in the
container. | L'élément idref est simplement un raccourci et un moyen infaillible
pour positionner une propriété avec un id ou un
name, sous forme de chaîne de caractères, d'un autre
bean dans le conteneur. |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[7] |
| Original | Traduction | <bean id="theTargetBean" class="...">
</bean>
<bean id="theClientBean" class="...">
<property name="targetName">
<idref bean="theTargetBean"/>
</property>
</bean> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[11] |
| Original | Traduction | This is exactly equivalent at runtime to the
following fragment: | Ceci est exactement équivalent à l'exécution
à la configuration suivante; |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[8] |
| Original | Traduction | <bean id="theTargetBean" class="...">
</bean>
<bean id="theClientBean" class="...">
<property name="targetName">
<value>theTargetBean</value>
</property>
</bean> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[12] |
| Original | Traduction | The main reason the first form is preferable to
the second is that using the idref tag will allow
Spring to validate at deployment time that the other bean actually
exists. In the second variation, the class who's
targetName property is forced to do its own
validation, and that will only happen when that class is actually
instantiated by Spring, possibly long after the container is actually
deployed. | La raison principale pour laquelle la première formulation
est préférable, est que l'utilisation de la balise idref
permet à Spring de valider au moment du déploiement que l'autre
bean existe réellement. Dans la seconde forme, la classe qui a
la propriété targetName est obligée de faire
sa propre validation, ce qui se produira uniquement quand celle-ci
sera réellement instanciée par Spring, probablement longtemps
après que le conteneur ait été déployé. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[13] |
| Original | Traduction | Additionally, if the bean being referred to is in the same actual
XML file, and the bean name is the bean id, the
local attribute may be used, which will allow the XML
parser itself to validate the bean name even earlier, at XML document
parse time. | De plus, si le bean référencé est dans le même fichier XML, et que
le nom du bean est l'id du bean, l'attribut
local peut être utilisé, ce qui permettra au parseur
XML lui-même de valider le nom du bean au moment du parcours du document
XML. |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[9] |
| Original | Traduction | <property name="targetName">
<idref local="theTargetBean"/>
</property> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[14] |
| Original | Traduction | The ref element is the final element allowed
inside a property definition element. It is used to
set the value of the specified property to be a reference to another
bean managed by the container, a collaborator, so to speak. As mentioned
in a previous section, the referred-to bean is considered to be a
dependency of the bean who's property is being set, and will be
initialized on demand as needed (if it is a singleton bean it may have
already been initialized by the container) before the property is set.
All references are ultimately just a reference to another object, but
there are 3 variations on how the id/name of the other object may be
specified, which determines how scoping and validation is
handled. | L'élément ref est le dernier élément autorisé
dans une définition de l'élément property. Il est
utilisé pour positionner la valeur de la propriété spécifiée comme
étant une référence à un autre bean géré par le conteneur, un collaborateur,
pour ainsi dire. Comme cela a été mentionné dans la précédente section,
le bean referred-to est considéré comme étant une dépendence du bean
dont la propriété a été positionné et sera initialisé à la demande
quand cela sera nécessaire (s'il s'agit d'un singleton, il peut déjà
avoir été initialisé par le conteneur) avant que la propriété soit
positionnée. Toutes les références sont finalement uniquement une référence
à un autre objet, mais il y a trois variantes sur la façon dont id/name
de l'autre objet peuvent être spécifiés, ce qui déterminent la façon
dont la portée et la validation sont prises en compte. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[15] |
| Original | Traduction | Specifying the target bean by using the bean
attribute of the ref tag is the most general form,
and will allow creating a reference to any bean in the same
BeanFactory/ApplicationContext (whether or not in the same XML file), or
parent BeanFactory/ApplicationContext. The value of the
bean attribute may be the same as either the
id attribute of the target bean, or one of the values
in the name attribute of the target
bean. | Spécifier le bean cible en utilisant l'attribut bean
de la balise ref est la façon la plus courante,
et permettra de créer une référence sur n'importe quel bean dans les
mêmes BeanFactory/ApplicationContext (s'ils se trouvent ou non dans
le même fichier XML), ou des BeanFactory/ApplicationContext parents.
La valeur de l'attribut bean peut être le même que
l'attribut id du bean cible, ou une des valeurs
de l'attribut name de ce même bean. |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[10] |
| Original | Traduction | <ref bean="someBean"/> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[16] |
| Original | Traduction | Specifying the target bean by using the local
attribute leverages the ability of the XML parser to validate XML id
references within the same file. The value of the
local attribute must be the same as the
id attribute of the target bean. The XML parser will
issue an error if no matching element is found in the same file. As
such, using the local variant is the best choice (in order to know about
errors are early as possible) if the target bean is in the same XML
file. | Spécifier le bean cible en utilisant l'attribut local
permet au parseur XML de valider les références des id XML dans le même
fichier. La valeur de l'attribut local doit la même
que l'attribut id du bean cible. Le parseur XML
remontera une erreur si aucun élément correspondant n'est trouvé dans le
même fichier. De ce fait, utiliser local est le meilleur choix (pour connaître
les erreurs le plus tôt possible) si le bean cibl est dans le même
fichier XML. |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[11] |
| Original | Traduction | <ref local="someBean"/> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[3]/translation[17] |
| Original | Traduction | Specifying the target bean by using the parent
attribute allows a reference to be created to a bean which is in a
parent BeanFactory (or ApplicationContext) of the current BeanFactory
(or ApplicationContext). The value of the parent
attribute may be the same as either the id attribute
of the target bean, or one of the values in the name
attribute of the target bean, and the target bean must be in a parent
BeanFactory or ApplicationContext to the current one. The main use of
this bean reference variant is when there is a need to wrap an existing
bean in a parent context with some sort of proxy (which may have the
same name as the parent), and needs the original object so it may wrap
it. | Spécifier le bean cible en utilisant l'attribut parent
permet à une référence d'être créée sur un bean qui est dans une BeanFactory
parente (ou ApplicationContext) de la BeanFactory courante (or ApplicationContext).
La valeur de l'attribut parent peut être le même que
l'attribut id du bean cible, ou une des valeurs
de l'attribut name de ce même bean, et le bean cible
doit être dans une BeanFactory ou un ApplicationContext parent par rapport
au courant. L'utilisation principale de cette variante de référence
à un bean est quand il y a un besoin d'envelopper un bean existant dans
un contexte parent avec des proxies (qui peuvent avoir le même nom
que le parent), et ont besoin du l'objet original à cet effet. |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[3]/programlisting[12] |
| Original | Traduction | <ref parent="someBean"/> |
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[3]/sect2[4]/translation[1] |
| Original | Traduction | Method Injection | Injection par Méthode |
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/translation[2] |
| Original | Traduction | For most users, the majority of the beans in the container will be
singletons. When a singleton bean needs to collaborate with (use)
another singleton bean, or a non-singleton bean needs to collaborate
with another non-singleton bean, the typical and common approach of
handling this dependency by defining one bean to be a property of the
other, is quite adequate. There is however a problem when the bean
lifecycles are different. Consider a singleton bean A which needs to use
a non-singleton (prototype) bean B, perhaps on each method invocation on
A. The container will only create the singleton bean A once, and thus
only get the opportunity to set its properties once. There is no
opportunity for the container to provide bean A with a new instance of
bean B every time one is needed. | Pour la plupart des utilisateursn la majorité des beans dans le
conteneur seront des singletons. Quand un singleton a besoin de collaborer
ou utiliser un autre singleton, ou un non-singleton a
besoin avec un autre, l'approche typique et communément utilisée pour traiter cette
dépendance en définisant un bean comme étant un propriété de l'autre,
est appropriée. Il y a cependant un problème quand les cycles de vie
des beans sont différent. Considérons un singleton A qui a besoin d'utiliser un
non-singleton (prototype) B, peut-être sur chaque invocation
de méthodes de A. Le conteneur créera seulement le singleton A une fois, et
ainsi aura la possibilité de positionner ces propriétés une fois. Il n'y a
pas de possibilité pour le conteneur de fournir une bean A avec une nouvelle
instance de B à chaque fois qu'une nouvelle est nécessaire. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/translation[3] |
| Original | Traduction | One solution to this problem is to forgo some inversion of
control. Bean A can be aware of the container (as described here) by
implementing BeanFactoryAware, and use programmatic
means (as described here) to
ask the container via a getBean("B") call for (a new)
bean B every time it needs it. This is generally not a desirable
solution since the bean code is then aware of and coupled to
Spring. | Une solution pour résoudre ce problème est de rénoncer à
quelques inversions de contrôle. Le bean A peut être conscient
du conteneur (comme décrit ici) en
implémentant l'interface BeanFactoryAware, et
utiliser la programmation (comme décrit
here) pour pour demander
directement au conteneur via l'appel getBean("B") un
(nouveau) bean B chaque fois que A en a besoin. De manière générale,
il ne s'agit pas d'une solution souhaitable puisque le code du bean est
ensuite conscient et couplé à Spring. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/translation[4] |
| Original | Traduction | Method Injection, an advanced feature of the BeanFactory, allows
this use case to be handled in a clean fashion, along with some other
scenarios. | L'Injection par méthode, un dispositif avancé de la BeanFactory, permet ce
cas d'utilisation pour traiter d'une manière propre de même que d'autres scénarios. |
| + title | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[1]/translation[1] |
| Original | Traduction | Lookup method Injection | Injection par méthode de recherche |
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[1]/translation[2] |
| Original | Traduction | Lookup method injection refers to the ability of the container
to override abstract or concrete methods on managed beans in the
container, to return the result of looking up another named bean in
the container. The lookup will typically be of a non-singleton bean as
per the scenario described above (although it can also be a
singleton). Spring implements this through a dynamically generated
subclass overriding the method, using bytecode generation via the
CGLIB library. | L'injection par méthode de recherche se réfère à la possibilité
du conteneur de surcharger des méthodes abstraites ou concrètes sur
des beans gérés par le conteneur, pour retourner le résultat d'une
recherche d'une autre bean défini dans le conteneur. Cela se fera typiquement
pour la recherche d'un non-singleton aussi bien
que pour le scéario décrit précédemment (bien qu'il puisse également
être un singleton). Spring implémente cela au moyen d'une sous-classe
générée dynamiquement qui surcharge la méthode en utilisant la génération
de bytecode via la bibliothèque CGLIB. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[1]/translation[3] |
| Original | Traduction | In the client class containing the method to be injected, the
method definition must be an abstract (or concrete) definition in this
form: | Dans la classe cliente contenant la méthode à injecter, la définition
de la méthode doit être défini de manière abstraite (ou concrète) de cette
manière: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[1]/para[1]/programlisting[1] |
| Original | Traduction | protected abstract SingleShotHelper createSingleShotHelper(); |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[1]/translation[4] |
| Original | Traduction | If the method is not abstract, Spring will simply override the
existing implementation. In the XmlBeanFactory case, you instruct
Spring to inject/override this method to return a particular bean from
the container, by using the lookup-method element
inside the bean definition. For example: | Si la méthode n'est pas abstraite, Spring surchargera simplement
l'implémentation existante. Dans le cas de XmlBeanFactory, vous spécifiez à
Spring pour injecter/surcharger la méthode retournant un bean
particulier à partir du conteneur, en utilisant l'élément lookup-method
dans la définition du bean. Par exemple: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[1]/programlisting[1] |
| Original | Traduction | <!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="singleShotHelper class="..." singleton="false">
</bean>
<!-- myBean uses singleShotHelper -->
<bean id="myBean" class="...">
<lookup-method name="createSingleShotHelper"
bean="singleShotHelper"/>
<property>
...
</property>
</bean> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[1]/translation[5] |
| Original | Traduction | The bean identified as myBean will call its
own method createSingleShotHelper whenever it needs
a new instance of the singleShotHelper bean. It
is important to note that the person deploying the beans must be
careful to deploy singleShotHelper as a
non-singleton (if that is actually what is needed). If it is deployed
as a singleton (either explicitly, or relying on the default
true setting for this flag), the same instance of
singleShotHelper will be returned each time! | Le bean identifié par myBean appellera sa
propre méthode createSingleShotHelper toutes les fois
qu'il aura besoin d'une nouvelle instance du bean singleShotHelper.
Il est important de noter que la personne déployant les beans doit
faire attention à déplouer singleShotHelper
comme un non-singleton (si c'est ce qui est voulu). S'il est déployé
comme un singleton (soit explicitement, ou en comptant sur la valeur
par défaut true pour ce paramètre), la même instance
de singleShotHelper sera retournée à chaque fois! |
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[1]/translation[6] |
| Original | Traduction | Note that lookup method injection can be combined with
Constructor Injection (supplying optional constructor arguments to the
bean being constructed), and also with Setter Injection (settings
properties on the bean being constructed). | Noter que la méthode d'injection par recherche peut être
combinée avec l'Injection par Constructeur (fournissant des arguments
optionnels au bean étant construit), et également avec l'Injection
par Positionnement (positionnant les propriétés sur le bean étant
construits). |
| + title | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[2]/translation[1] |
| Original | Traduction | Arbitrary method replacement | Remplacement arbitraire de méthode |
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[2]/translation[2] |
| Original | Traduction | A less commonly useful form of method injection than Lookup
Method Injection is the ability to replace arbitrary methods in a
managed bean with another method implementation. Users may safely skip
the rest of this section (which describes this somewhat advanced
feature), until this functionality is actually needed. | Une forme d'injection moins utilisée communément que l'Injection
par Méthode de Recherche est la possibilité de remplacer arbitrairement
des méthodes d'un bean par une autre implémentation de celle-ci. Les
utilisateurs peuvent sans risque passer le reste de la section (qui
décrit cette fonctionnalité avancée), à moins qu'il n'en ait réellement
besoin. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[2]/translation[3] |
| Original | Traduction | In an XmlBeanFactory, the replaced-method
element may be used to replace an existing method implementation with
another, for a deployed bean. Consider the following class, with a
method computeValue, which we want to override: | Dans une XmlBeanFactory, l'élément replaced-method
peut être utilisé pour remplacer une implémentation d'une méthode
existante par une autre, pour un bean déployé. Considérons la classe
suivante, avec une méthode computeValue, que l'on veut surcharger: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[2]/programlisting[1] |
| Original | Traduction | ...
public class MyValueCalculator {
public String computeValue(String input) {
... some real code
}
... some other methods
} |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[2]/translation[4] |
| Original | Traduction | A class implementing the
org.springframework.beans.factory.support.MethodReplacer
interface is needed to provide the new method
definition. | Une classe implémentant l'interface
org.springframework.beans.factory.support.MethodReplacer
est nécessaire pour fournir la définition de la nouvelle méthode. |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[2]/programlisting[2] |
| Original | Traduction | /** meant to be used to override the existing computeValue
implementation in MyValueCalculator */
public class ReplacementComputeValue implements MethodReplacer {
public Object reimplement(Object o, Method m, Object[] args) throws Throwable {
// get the input value, work with it, and return a computed result
String input = (String) args[0];
...
return ...;
} |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[2]/translation[5] |
| Original | Traduction | The BeanFactory deployment definition to deploy the original
class and specify the method override would look like: | La définition dans la BeanFactory pour déployer la classe
de base et spécifier la méthode à surcharger ressemblera à cela: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[2]/programlisting[3] |
| Original | Traduction | <bean id="myValueCalculator class="x.y.z.MyValueCalculator">
<!-- arbitrary method replacement -->
<replaced-method name="computeValue" replacer="replacementComputeValue">
<arg-type>String</arg-type>
</replaced-method>
</bean>
<bean id="replacementComputeValue" class="a.b.c.ReplaceMentComputeValue">
</bean> |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[2]/translation[6] |
| Original | Traduction | One or more contained
arg-type elements within the
replaced-method element may be used to indicate the
method signature of the method being overridden. Note that the
signature for the arguments is actually only needed in the case that
the method is actually overloaded and there are multiple variants
within the class. For convenience, the type string for an argument may
be a substring of the fully qualified type name. For example, all the
following would match
java.lang.String. | Un ou plusieurs sous-éléments arg-type
de l'élément replaced-method peuvent être utilisés
pour indiquer la signature de la méthode à surcharger. Noter que cette
signature est seulement nécessaire réellement dans le cas où la méthode
est réellement surchargée et qu'il y a plusieurs variantes dans la classe.
Par convenance, la chaîne décrivant le type pour un argument peut être
une sous-chaîne du nom complet du type. Par exemple, tous les formes
suivantes correspondront à java.lang.String. |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[2]/programlisting[4] |
| Original | Traduction | java.lang.String
String
Str |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[4]/sect3[2]/translation[7] |
| Original | Traduction | Since the number of arguments is often enough to
distinguish between each possible choice, this shortcut can save a lot
of typing, by just using the shortest string which will match an
argument. | Puisque le nombre des arguments est parfois suffisant pour distinguer
les différents choix possibles, ce raccourci peut alléger la définition
en utilisant juste la plus courte chaîne correspondant à un type. |
| | sect2
| | + title | Ref. /chapter[1]/sect1[3]/sect2[5]/translation[1] |
| Original | Traduction | Using depends-on | Utilisation de depends-on |
| + para | Ref. /chapter[1]/sect1[3]/sect2[5]/translation[2] |
| Original | Traduction | For most situations, the fact that a bean is a dependency of
another is expressed simply by the fact that one bean is set as a
property of another. This is typically done with the
ref element in the XmlBeanFactory. In a variation of
this, sometimes a bean which is aware of the container is simply given
the id of its dependency (using a string value or alternately the
idref element, which evaluates the same as a string
value). The first bean then programmatically asks the container for its
dependency. In either case, the dependency is properly initialized
before the dependent bean. | Dans la plupart des situations, le fait qu'un bean soit dépendant
d'un autre, exprime simplement le fait qu'un bean est positionné
comme une propriété d'un autre. Cela est typiquement réalisé avec
l'élément ref dans la XmlBeanFactory. Comme variante
de celle, souvent un bean qui utilise le conteneur, reçoit simplement
l'identifiant de sa dépendance (en utilisant la valeur sous forme de
chaîne, ou l'élément idref qui évalue cette même
chaîne). Le premier bean demande ensuite par la programmation au
conteneur ses dépendances. Dans les deux cas, la dépendance est correctement
initialisée avant le bean dépendant. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[5]/translation[3] |
| Original | Traduction | For the relatively infrequent situations where dependencies
between beans are less direct (for example, when a static initializer in
a class needs to be triggered, such as database driver registration),
the depends-on element may be used to explicitly
force one or more beans to be initialized before the bean using this
element is initialized. | Pour les situations peu fréquentes où les dépendances entre les
beans sont moins directes (par exemple, quand un initialiseur
statique dans une classe a besoin d'être déclenché, comme l'enregistrement
d'un pilote de base de données), l'élément depends-on
peut être utilisé pour forcer explicitement un ou plusieurs beans
à être initialisés avant l'initialisation du bean utilisant cet élément. |
| + para | Ref. /chapter[1]/sect1[3]/sect2[5]/translation[4] |
| Original | Traduction | Following is an example configuration: | Ce qui suit est un exemple de configuration: |
| + programlisting | Ref. /chapter[1]/sect1[3]/sect2[5]/programlisting[1] |
| Original | Traduction | <bean id="beanOne" class="ExampleBean" depends-on="manager">
<property name="manager"><ref local="manager"/></property>
</bean>
<bean id="manager" class="ManagerBean"/> |
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[3]/sect2[6]/title[1] |
| Original | Traduction | Autowiring collaborators |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1] |
| Original | Traduction | A BeanFactory is able to autowire
relationships between collaborating beans. This means it's possible to
automatically let Spring resolve collaborators (other beans) for your
bean by inspecting the contents of the BeanFactory. The autowiring
functionality has five modes. Autowiring is specified
per bean and can thus be enabled for some beans,
while other beans won't be autowired. Using autowiring, it is possible
to reduce or eliminate the need to specify properties or constructor
arguments, saving a significant amount of typing.
| + para | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/footnote[1]/para[1] |
| Original | Traduction | See |
|
In an XmlBeanFactory, the autowire mode for a bean
definition is specified by using the autowire
attribute of the bean element. The following values are allowed.
| + title | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/title[1] |
| Original | Traduction | Autowiring modes |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/thead[1]/row[1]/entry[1] |
| Original | Traduction | Mode |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/thead[1]/row[1]/entry[2] |
| Original | Traduction | Explanation |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/tbody[1]/row[1]/entry[1] |
| Original | Traduction | no |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/tbody[1]/row[1]/entry[2] |
| Original | Traduction | No autowiring at all. Bean references must be defined
via a ref element. This is the default, and
changing this is discouraged for larger deployments, since
explicitly specifying collaborators gives greater control and
clarity. To some extent, it is a form of documentation about
the structure of a system. |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/tbody[1]/row[2]/entry[1] |
| Original | Traduction | byName |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/tbody[1]/row[2]/entry[2] |
| Original | Traduction | Autowiring by property name. This option will inspect
the BeanFactory and look for a bean named exactly the same as
the property which needs to be autowired. For example, if you
have a bean definition which is set to autowire by name, and
it contains a master property (that is,
it has a setMaster(...) method), Spring
will look for a bean definition named master, and use it to
set the property. |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/tbody[1]/row[3]/entry[1] |
| Original | Traduction | byType |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/tbody[1]/row[3]/entry[2] |
| Original | Traduction | Allows a property to be autowired if there is exactly
one bean of the property type in the BeanFactory. If there is
more than one, a fatal exception is thrown, and this indicates
that you may not use byType autowiring
for that bean. If there are no matching beans, nothing
happens; the property is not set. If this is not desirable,
setting the dependency-check="objects"
attribute value specifies that an error should be thrown in
this case. |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/tbody[1]/row[4]/entry[1] |
| Original | Traduction | constructor |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/tbody[1]/row[4]/entry[2] |
| Original | Traduction | This is analogous to byType, but
applies to constructor arguments. If there isn't exactly one
bean of the constructor argument type in the bean factory, a
fatal error is raised. |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/tbody[1]/row[5]/entry[1] |
| Original | Traduction | autodetect |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[6]/para[1]/table[1]/tgroup[1]/tbody[1]/row[5]/entry[2] |
| Original | Traduction | Chooses constructor or
byType through introspection of the bean
class. If a default constructor is found, byType gets
applied. |
|
|
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[6]/para[2] |
| Original | Traduction | Note that explicit dependencies, i.e. property
and constructor-arg elements, always override
autowiring. Autowire behavior can be combined with dependency checking,
which will be performed after all autowiring has been completed. |
| Note: as has already been mentioned, for larger
applications, it is discouraged to use autowiring because it removes the
transparency and the structure from your collaborating
classes. | | sect2
| | + title | Ref. /chapter[1]/sect1[3]/sect2[7]/title[1] |
| Original | Traduction | Checking for dependencies |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[7]/para[1] |
| Original | Traduction | Spring has the ability to try to check for the existence of
unresolved dependencies of a bean deployed into the BeanFactory. These
are JavaBeans properties of the bean, which do not have actual values
set for them in the bean definition, or alternately provided
automatically by the autowiring feature. |
|
| + para | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2] |
| Original | Traduction | This feature is sometimes useful when you want to ensure that all
properties (or all properties of a certain type) are set on a bean. Of
course, in many cases a bean class will have default values for many
properties, or some properties do not apply to all usage scenarios, so
this feature is of limited use. Dependency checking can also be enabled
and disabled per bean, just as with the autowiring functionality. The
default is to not check dependencies. Dependency
checking can be handled in several different modes. In an
XmlBeanFactory, this is specified via the
dependency-check attribute in a bean definition,
which may have the following values.
| + title | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2]/table[1]/title[1] |
| Original | Traduction | Dependency checking modes |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2]/table[1]/tgroup[1]/thead[1]/row[1]/entry[1] |
| Original | Traduction | Mode |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2]/table[1]/tgroup[1]/thead[1]/row[1]/entry[2] |
| Original | Traduction | Explanation |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2]/table[1]/tgroup[1]/tbody[1]/row[1]/entry[1] |
| Original | Traduction | none |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2]/table[1]/tgroup[1]/tbody[1]/row[1]/entry[2] |
| Original | Traduction | No dependency checking. Properties of the bean which
have no value specified for them are simply not set. |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2]/table[1]/tgroup[1]/tbody[1]/row[2]/entry[1] |
| Original | Traduction | simple |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2]/table[1]/tgroup[1]/tbody[1]/row[2]/entry[2] |
| Original | Traduction | Dependency checking is performed for primitive types
and collections (everything except collaborators, i.e. other
beans) |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2]/table[1]/tgroup[1]/tbody[1]/row[3]/entry[1] |
| Original | Traduction | object |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2]/table[1]/tgroup[1]/tbody[1]/row[3]/entry[2] |
| Original | Traduction | Dependency checking is performed for
collaborators |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2]/table[1]/tgroup[1]/tbody[1]/row[4]/entry[1] |
| Original | Traduction | all |
|
| + entry | Ref. /chapter[1]/sect1[3]/sect2[7]/para[2]/table[1]/tgroup[1]/tbody[1]/row[4]/entry[2] |
| Original | Traduction | Dependency checking is done for collaborators,
primitive types and collections |
|
|
|
| |
| | sect1
| | + title | Ref. /chapter[1]/sect1[4]/title[1] |
| Original | Traduction | Customizing the nature of a bean |
| sect2
| | + title | Ref. /chapter[1]/sect1[4]/sect2[1]/title[1] |
| Original | Traduction | Lifecycle interfaces |
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[1]/para[1] |
| Original | Traduction | Spring provides several marker interfaces to change the behavior
of your bean in the BeanFactory. They include
InitializingBean and
DisposableBean. Implementing these interfaces will
result in the BeanFactory calling
afterPropertiesSet() for the former and
destroy() for the latter to allow the bean to perform
certain actions upon initialization and destruction. |
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[1]/para[2] |
| Original | Traduction | Internally, Spring uses BeanPostProcessors to
process any marker interfaces it can find and call the appropriate
methods. If you need custom features or other lifecycle behavior Spring
doesn't offer out-of-the-box, you can implement a
BeanPostProcessor yourself. More information about
this can be found in . |
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[1]/para[3] |
| Original | Traduction | All the different lifecycle marker interfaces are described below.
In one of the appendices, you can find diagram that show how Spring
manages beans and how those lifecycle features change the nature of your
beans and how they are managed. |
|
| + title | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[1]/title[1] |
| Original | Traduction | InitializingBean / init-method |
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[1]/para[1] |
| Original | Traduction | Implementing the
org.springframework.beans.factory.InitializingBean
allows a bean to perform initialization work after all necessary
properties on the bean are set by the BeanFactory. The
InitializingBean interface specifies exactly one
method: | + programlisting | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[1]/para[1]/programlisting[1] |
| Original | Traduction | * Invoked by a BeanFactory after it has set all bean properties supplied
* (and satisfied BeanFactoryAware and ApplicationContextAware).
* <p>This method allows the bean instance to perform initialization only
* possible when all bean properties have been set and to throw an
* exception in the event of misconfiguration.
* @throws Exception in the event of misconfiguration (such
* as failure to set an essential property) or if initialization fails.
*/
void afterPropertiesSet() throws Exception; |
|
|
|
Note: generally, the use of the
InitializingBean marker interface can be avoided
(and is discouraged since it unnecessarily couples the code to
Spring). A bean definition provides support for a generic
initialization method to be specified. In the case of the
XmlBeanFactory, this is done via the init-method
attribute. For example, the following definition:
| + para | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[1]/para[3] |
| Original | Traduction | | + programlisting | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[1]/para[3]/programlisting[1] |
| Original | Traduction | <bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {
public void init() {
// do some initialization work
}
} |
| Is exactly the same as: | + programlisting | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[1]/para[3]/programlisting[2] |
| Original | Traduction | <bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
} |
| but does not couple the code to Spring. |
|
| + title | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[2]/title[1] |
| Original | Traduction | DisposableBean / destroy-method |
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[2]/para[1] |
| Original | Traduction | Implementing the
org.springframework.beans.factory.DisposableBean
interface allows a bean to get a callback when the BeanFactory
containing it is destroyed. The DisposableBean interface specifies one
method: | + programlisting | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[2]/para[1]/programlisting[1] |
| Original | Traduction | /**
* Invoked by a BeanFactory on destruction of a singleton.
* @throws Exception in case of shutdown errors.
* Exceptions will get logged but not re-thrown to allow
* other beans to release their resources too.
*/
void destroy() throws Exception;
|
|
|
|
Note: generally, the use of the
DisposableBean marker interface can be avoided (and
is discouraged since it unnecessarily couples the code to Spring). A
bean definition provides support for a generic destroy method to be
specified. In the case of the XmlBeanFactory, this is done via the
destroy-method attribute. For example, the
following definition:
| + para | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[2]/para[3] |
| Original | Traduction | | + programlisting | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[2]/para[3]/programlisting[1] |
| Original | Traduction | <bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
public class ExampleBean {
public void cleanup() {
// do some destruction work (like closing connection)
}
} |
| Is exactly the same as: | + programlisting | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[2]/para[3]/programlisting[2] |
| Original | Traduction | <bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements DisposableBean {
public void destroy() {
// do some destruction work
}
} |
| but does not couple the code to Spring. |
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[1]/sect3[2]/para[4] |
| Original | Traduction | Important note: when deploying a bean in the prototype
mode, the lifecycle of the bean changes slightly. By definition,
Spring cannot manage the complete lifecycle of a
non-singleton/prototype bean, since after it is created, it is given
to the client and the container does not keep track of it at all any
longer. You can think of Spring's role when talking about a
non-singleton/prototype bean as a replacement for the 'new' operator.
Any lifecycle aspects past that point have to be handled by the
client. The lifecycle of a bean in the BeanFactory is further
described in . |
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[4]/sect2[2]/title[1] |
| Original | Traduction | Knowing who you are |
|
| + title | Ref. /chapter[1]/sect1[4]/sect2[2]/sect3[1]/title[1] |
| Original | Traduction | BeanFactoryAware |
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[2]/sect3[1]/para[1] |
| Original | Traduction | A class which implements the
org.springframework.beans.factory.BeanFactoryAware
interface is provided with a reference to the BeanFactory that created
it, when it is created by that BeanFactory. | + programlisting | Ref. /chapter[1]/sect1[4]/sect2[2]/sect3[1]/para[1]/programlisting[1] |
| Original | Traduction | public interface BeanFactoryAware {
/**
* Callback that supplies the owning factory to a bean instance.
* <p>Invoked after population of normal bean properties but before an init
* callback like InitializingBean's afterPropertiesSet or a custom init-method.
* @param beanFactory owning BeanFactory (may not be null).
* The bean can immediately call methods on the factory.
* @throws BeansException in case of initialization errors
* @see BeanInitializationException
*/
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
} |
|
|
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[2]/sect3[1]/para[2] |
| Original | Traduction | This allows beans to manipulate the BeanFactory that created
them programmatically, through the
org.springframework.beans.factory.BeanFactory
interface, or by casting the reference to a known subclass of this
which exposes additional functionality. Primarily this would consist
of programmatic retrieval of other beans. While there are cases when
this capability is useful, it should generally be avoided, since it
couples the code to Spring, and does not follow the Inversion of
Control style, where collaborators are provided to beans as
properties. |
|
| + title | Ref. /chapter[1]/sect1[4]/sect2[2]/sect3[2]/title[1] |
| Original | Traduction | BeanNameAware |
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[2]/sect3[2]/para[1] |
| Original | Traduction | If a bean implements the
org.springframework.beans.factory.BeanNameAware
interface and is deployed in a BeanFactory, the BeanFactory will call
the bean through this interface to inform the bean of the
id it was deployed under. The callback will be
Invoked after population of normal bean properties but before an init
callback like InitializingBean's
afterPropertiesSet or a custom
init-method. |
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[4]/sect2[3]/title[1] |
| Original | Traduction | FactoryBean |
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[3]/para[1] |
| Original | Traduction | The
org.springframework.beans.factory.FactoryBean
interface is to be implemented by objects that are themselves
factories. The BeanFactory interface provides three method:
| + para | Ref. /chapter[1]/sect1[4]/sect2[3]/para[1]/itemizedlist[1]/listitem[1]/para[1] |
| Original | Traduction | Object getObject(): has to return an
instance of the object this factory creates. The instance can
possibly be shared (depending on whether this factory returns
singletons or prototypes). |
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[3]/para[1]/itemizedlist[1]/listitem[2]/para[1] |
| Original | Traduction | boolean isSingleton(): has to return
true if this FactoryBean returns singletons,
false otherwise |
|
| + para | Ref. /chapter[1]/sect1[4]/sect2[3]/para[1]/itemizedlist[1]/listitem[3]/para[1] |
| Original | Traduction | Class getObjectType(): has to return
either the object type returned by the
getObject() method or null
if the type isn't known in advance |
|
|
|
| |
| | sect1
| | + title | Ref. /chapter[1]/sect1[5]/title[1] |
| Original | Traduction | Abstract and child bean definitions |
|
| + para | Ref. /chapter[1]/sect1[5]/para[1] |
| Original | Traduction | A bean definition potentially contains a large amount of
configuration information, including container specific information (i.e.
initialization method, static factory method name, etc.) and constructor
arguments and property values. A child bean definition is a bean
definition which inherits configuration data from a parent definition. It
is then able to override some values, or add others, as needed. Using
parent and child bean definitions can potentially save a lot of typing.
Effectively, this is a form of templating. |
|
| + para | Ref. /chapter[1]/sect1[5]/para[2] |
| Original | Traduction | When working with a BeanFactory programmatically, child bean
definitions are represented by the ChildBeanDefinition
class. Most users will never work with them on this level, instead
configuring bean definitions declaratively in something like the
XmlBeanFactory. In an XmlBeanFactory bean definition, a child bean
definition is indicated simply by using the parent
attribute, specifying the parent bean as the value of this
attribute. | + programlisting | Ref. /chapter[1]/sect1[5]/para[2]/programlisting[1] |
| Original | Traduction | <bean id="inheritedTestBean" abstract="true"
class="org.springframework.beans.TestBean">
<property name="name"><value>parent</value></property>
<property name="age"><value>1</value></property>
</bean>
<bean id="inheritsWithDifferentClass" class="org.springframework.beans.DerivedTestBean"
parent="inheritedTestBean" init-method="initialize">
<property name="name"><value>override</value></property>
<!-- age should inherit value of 1 from parent -->
</bean> |
|
|
|
| + para | Ref. /chapter[1]/sect1[5]/para[3] |
| Original | Traduction | A child bean definition will use the bean class from the parent
definition if none is specified, but can also override it. In the latter
case, the child bean class must be compatible with the parent, i.e. it
must accept the parent's property values. |
|
| + para | Ref. /chapter[1]/sect1[5]/para[4] |
| Original | Traduction | A child bean definition will inherit constructor argument values,
property values and method overrides from the parent, with the option to
add new values. If init method, destroy method and/or static factory
method are specified, they will override the corresponding parent
settings. |
|
| + para | Ref. /chapter[1]/sect1[5]/para[5] |
| Original | Traduction | The remaining settings will always be taken
from the child definition: depends on,
autowire mode, dependency check,
singleton, lazy init. |
|
| + para | Ref. /chapter[1]/sect1[5]/para[6] |
| Original | Traduction | Note that in the example above, we have explicitly marked the parent
bean definition as abstract by using the
abstract attribute. In the case that the parent
definition does not specify a class: | + programlisting | Ref. /chapter[1]/sect1[5]/para[6]/programlisting[1] |
| Original | Traduction | <bean id="inheritedTestBeanWithoutClass">
<property name="name"><value>parent</value></property>
<property name="age"><value>1</value></property>
</bean>
<bean id="inheritsWithClass" class="org.springframework.beans.DerivedTestBean"
parent="inheritedTestBeanWithoutClass" init-method="initialize">
<property name="name"><value>override</value></property>
<!-- age should inherit value of 1 from parent -->
</bean> |
|
|
|
| + para | Ref. /chapter[1]/sect1[5]/para[7] |
| Original | Traduction | the parent bean cannot get instantiated on its own since it is
incomplete, and it's also considered abstract. When a definition is
considered abstract like this (explicitly or implicitly), it's usable just
as a pure template or abstract bean definition that will serve as parent
definition for child definitions. Trying to use such an abstract parent
bean on its own (by referring to it as a ref property of another bean, or
doing an explicit getBean() call with the parent bean id, will result in
an error. Similarly, the container's internal
preInstantiateSingletons method will completely
ignore bean definitions which are considered abstract. |
|
| + para | Ref. /chapter[1]/sect1[5]/para[8] |
| Original | Traduction | Important Note: Application contexts (but not
simple bean factories) will by default pre-instantiate all singletons.
Therefore it is important (at least for singleton beans) that if you have
a (parent) bean definition which you intend to use only as a template, and
this definition specifies a class, you must make sure to set the
abstract attribute to true,
otherwise the application context will actually pre-instantiate it. |
|
| | sect1
| | + title | Ref. /chapter[1]/sect1[6]/title[1] |
| Original | Traduction | Interacting with the BeanFactory |
|
| + para | Ref. /chapter[1]/sect1[6]/para[1] |
| Original | Traduction | A BeanFactory is essentially nothing more than the interface for an
advanced factory capable of maintaining a registry of different beans and
their dependencies. The BeanFactory enables you to read bean definitions
and access them using the bean factory. When using just the BeanFactory
you would create one and read in some bean definitions in the XML format
as follows: | + programlisting | Ref. /chapter[1]/sect1[6]/para[1]/programlisting[1] |
| Original | Traduction | InputStream is = new FileInputStream("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(is); |
|
|
|
| + para | Ref. /chapter[1]/sect1[6]/para[2] |
| Original | Traduction | Basically that's all there is to it. Using
getBean(String) you can retrieve instances of your
beans. You'll get a reference to the same bean if you defined it as a
singleton (the default) or you'll get a new instance each time if you set
singleton to false. The
client-side view of the BeanFactory is surprisingly simple. The
BeanFactory interface has only five methods for clients
to call:
| + para | Ref. /chapter[1]/sect1[6]/para[2]/itemizedlist[1]/listitem[1]/para[1] |
| Original | Traduction | boolean containsBean(String): returns true
if the BeanFactory contains a bean definition or bean instance that
matches the given name |
|
| + para | Ref. /chapter[1]/sect1[6]/para[2]/itemizedlist[1]/listitem[2]/para[1] |
| Original | Traduction | Object getBean(String): returns an instance
of the bean registered under the given name. Depending on how the
bean was configured by the BeanFactory configuration, either a
singleton and thus shared instance or a newly created bean will be
returned. A BeansException will be thrown when
either the bean could not be found (in which case it'll be a
NoSuchBeanDefinitionException), or an exception
occurred while instantiating and preparing the bean |
|
| + para | Ref. /chapter[1]/sect1[6]/para[2]/itemizedlist[1]/listitem[3]/para[1] |
| Original | Traduction | Object getBean(String,Class): returns a
bean, registered under the given name. The bean returned will be
cast to the given Class. If the bean could not be cast,
corresponding exceptions will be thrown
(BeanNotOfRequiredTypeException). Furthermore,
all rules of the getBean(String) method apply (see above) |
|
| + para | Ref. /chapter[1]/sect1[6]/para[2]/itemizedlist[1]/listitem[4]/para[1] |
| Original | Traduction | boolean isSingleton(String): determines
whether or not the bean definition or bean instance registered under
the given name is a singleton or a prototype. If no bean
corresponding to the given name could not be found, an exception
will be thrown
(NoSuchBeanDefinitionException) |
|
| + para | Ref. /chapter[1]/sect1[6]/para[2]/itemizedlist[1]/listitem[5]/para[1] |
| Original | Traduction | String[] getAliases(String): Return the
aliases for the given bean name, if any were defined in the bean
definition |
|
|
| sect2
| | + title | Ref. /chapter[1]/sect1[6]/sect2[1]/title[1] |
| Original | Traduction | Obtaining a FactoryBean, not its product |
|
| + para | Ref. /chapter[1]/sect1[6]/sect2[1]/para[1] |
| Original | Traduction | Sometimes there is a need to ask a BeanFactory for an actual
FactoryBean instance itself, not the bean it produces. This may be done
by prepending the bean id with & when calling the
getBean method of BeanFactory (including
ApplicationContext). So for a given FactoryBean with an id
myBean, invoking getBean("myBean")
on the BeanFactory will return the product of the FactoryBean, but
invoking getBean("&myBean") will return the
FactoryBean instance itself. |
|
| |
| | sect1
| | + title | Ref. /chapter[1]/sect1[7]/title[1] |
| Original | Traduction | Customizing beans with BeanPostprocessors |
|
| + para | Ref. /chapter[1]/sect1[7]/para[1] |
| Original | Traduction | A bean post-processor is a java class which implements the
org.springframework.beans.factory.config.BeanPostProcessor
interface, which consists of two callback methods. When such a class is
registered as a post-processor with the BeanFactory, for each bean
instance that is created by the BeanFactory, the post-processor will get a
callback from the BeanFactory before any initialization methods
(afterPropertiesSet and any declared init method) are
called, and also afterwords. The post-processor is free to do what it
wishes with the bean, including ignoring the callback completely. A bean
post-processor will typically check for marker interfaces, or do something
such as wrap a bean with a proxy. Some Spring helper classes are
implemented as bean post-processors. |
|
| + para | Ref. /chapter[1]/sect1[7]/para[2] |
| Original | Traduction | It is important to know that a BeanFactory treats bean
post-processors slightly differently than an ApplicationContext. An
ApplicationContext will automatically detect any beans which are deployed
into it which implement the BeanPostProcessor
interface, and register them as post-processors, to be then called
appropriately by the factory on bean creation. Nothing else needs to be
done other than deploying the post-processor in a similar fashion to any
other bean. On the other hand, when using plain BeanFactories, bean
post-processors have to manually be explicitly
registered, with a code sequence such as the following: | + programlisting | Ref. /chapter[1]/sect1[7]/para[2]/programlisting[1] |
| Original | Traduction | ConfigurableBeanFactory bf = new .....; // create BeanFactory
... // now register some beans
// now register any needed BeanPostProcessors
MyBeanPostProcessor pp = new MyBeanPostProcessor();
bf.addBeanPostProcessor(pp);
// now start using the factory
... |
|
|
|
| + para | Ref. /chapter[1]/sect1[7]/para[3] |
| Original | Traduction | Since this manual registration step is not convenient, and
ApplictionContexts are functionally supersets of BeanFactories, it is
generally recommended that ApplicationContext variants are used when bean
post-processors are needed. |
|
| | sect1
| | + title | Ref. /chapter[1]/sect1[8]/title[1] |
| Original | Traduction | Customizing bean factories with BeanFactoryPostprocessors |
|
| + para | Ref. /chapter[1]/sect1[8]/para[1] |
| Original | Traduction | A bean factory post-processor is a java class which implements the
org.springframework.beans.factory.config.BeanFactoryPostProcessor
interface. It is executed manually (in the case of the BeanFactory) or
automatically (in the case of the ApplicationContext) to apply changes of
some sort to an entire BeanFactory, after it has been constructed. Spring
includes a number of pre-existing bean factory post-processors, such as
PropertyResourceConfigurer and
PropertyPlaceHolderConfigurer, both described below,
and BeanNameAutoProxyCreator, very useful for wrapping
other beans transactionally or with any other kind of proxy, as described
later in this manual. The BeanFactoryPostProcessor can be used to add
custom editors (as also mentioned in ). |
|
| + para | Ref. /chapter[1]/sect1[8]/para[2] |
| Original | Traduction | In a BeanFactory, the process of applying a BeanFactoryPostProcessor
is manual, and will be similar to this: |
|
| + programlisting | Ref. /chapter[1]/sect1[8]/para[3]/programlisting[1] |
| Original | Traduction | XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
// create placeholderconfigurer to bring in some property
// values from a Properties file
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("jdbc.properties"));
// now actually do the replacement
cfg.postProcessBeanFactory(factory); |
|
| + para | Ref. /chapter[1]/sect1[8]/para[4] |
| Original | Traduction | An
ApplicationContext will detect any beans which are deployed into it which
implement the BeanFactoryPostProcessor interface, and
automatically use them as bean factory post-processors, at the appropriate
time. Nothing else needs to be done other than deploying these
post-processor in a similar fashion to any other bean. |
|
| + para | Ref. /chapter[1]/sect1[8]/para[5] |
| Original | Traduction | Since this manual step is not convenient, and ApplictionContexts are
functionally supersets of BeanFactories, it is generally recommended that
ApplicationContext variants are used when bean factory post-processors are
needed. |
| sect2
| | + title | Ref. /chapter[1]/sect1[8]/sect2[1]/title[1] |
| Original | Traduction | The PropertyPlaceholderConfigurer |
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[1]/para[1] |
| Original | Traduction | The PropertyPlaceholderConfigurer, implemented
as a bean factory post-processor, is used to externalize some property
values from a BeanFactory definition, into another separate file in Java
Properties format. This is useful to allow the person deploying an
application to customize some key properties (for example database URLs,
usernames and passwords), without the complexity or risk of modifying
the main XML definition file or files for the BeanFactory. |
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[1]/para[2] |
| Original | Traduction | Consider a fragment from a BeanFactory definition, where a
DataSource with placeholder values is defined: |
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[1]/para[3] |
| Original | Traduction | In the example below, a datasource is defined, and we will
configure some properties from an external Properties file. At runtime,
we will apply a PropertyPlaceholderConfigurer to the
BeanFactory which will replace some properties of the datasource: |
|
| + programlisting | Ref. /chapter[1]/sect1[8]/sect2[1]/programlisting[1] |
| Original | Traduction | <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
<property name="url"><value>${jdbc.url}</value></property>
<property name="username"><value>${jdbc.username}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
</bean> |
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[1]/para[4] |
| Original | Traduction | The actual values come from another file in Properties
format: |
|
| + programlisting | Ref. /chapter[1]/sect1[8]/sect2[1]/programlisting[2] |
| Original | Traduction | jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root |
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[1]/para[5] |
| Original | Traduction | To use this with a BeanFactory, the bean factory post-processor is
manually executed on it: |
|
| + programlisting | Ref. /chapter[1]/sect1[8]/sect2[1]/programlisting[3] |
| Original | Traduction | XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("jdbc.properties"));
cfg.postProcessBeanFactory(factory); |
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[1]/para[6] |
| Original | Traduction | Note that ApplicationContexts are able to automatically recognize
and apply beans deployed in them which implement
BeanFactoryPostProcessor. This means that as described here, applying
PropertyPlaceholderConfiguer is much more convenient when using an
ApplicationContext. For this reason, it is recommended that users
wishing to use this or other bean factory postprocessors use an
ApplicationContext instead of a BeanFactory. |
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[1]/para[7] |
| Original | Traduction | The PropertyPlaceHolderConfigurer doesn't only
look for properties in the Properties file you specify, but also checks
against the Java System properties if it cannot find a property you are
trying to use. This behavior can be customized by setting the
systemPropertiesMode property of the configurer. It
has three values, one to tell the configurer to always override, one to
let it never override and one to let it override
only if the property cannot be found in the properties file specified.
Please consult the JavaDoc for the PropertiesPlaceHolderConfigurer for
more information. |
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[8]/sect2[2]/title[1] |
| Original | Traduction | The PropertyOverrideConfigurer |
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[2]/para[1] |
| Original | Traduction | The PropertyOverrideConfigurer, another bean
factory post-processor, is similar to the
PropertyPlaceholderConfigurer, but in contrast to the
latter, the original definitions can have default values or no values at
all for bean properties. If an overriding Properties file does not have
an entry for a certain bean property, the default context definition is
used. |
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[2]/para[2] |
| Original | Traduction | Note that the bean factory definition is not
aware of being overridden, so it is not immediately obvious when looking
at the XML definition file that the override configurer is being used.
In case that there are multiple PropertyOverrideConfigurers that define
different values for the same bean property, the last one will win (due
to the overriding mechanism). |
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[2]/para[3] |
| Original | Traduction | Properties file configuration lines are expected to be in the
format:beanName.property=value |
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[2]/para[4] |
| Original | Traduction | An example properties file could look like: | + programlisting | Ref. /chapter[1]/sect1[8]/sect2[2]/para[4]/programlisting[1] |
| Original | Traduction | dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql:mydb |
|
|
|
| + para | Ref. /chapter[1]/sect1[8]/sect2[2]/para[5] |
| Original | Traduction | This example file would be usable against a BeanFactory definition
which contains a bean in it called dataSource,
which has driver and url
properties. |
|
| |
| | sect1
| | + title | Ref. /chapter[1]/sect1[9]/title[1] |
| Original | Traduction | Registering additional custom PropertyEditors |
|
| + para | Ref. /chapter[1]/sect1[9]/para[1] |
| Original | Traduction | When setting bean properties as a string value, a BeanFactory
ultimately uses standard JavaBeans PropertyEditors to convert these
Strings to the complex type of the property. Spring pre-registers a number
of custom PropertyEditors (for example, to convert a classname expressed
as a string into a real Class object). Additionally, Java's standard
JavaBeans PropertyEditor lookup mechanism allows a PropertyEditor for a
class to be simply named appropriately and placed in the same package as
the class it provides support for, to be found automatically. |
|
| + para | Ref. /chapter[1]/sect1[9]/para[2] |
| Original | Traduction | If there is a need to register other custom PropertyEditors, there
are several mechanisms available. |
|
| + para | Ref. /chapter[1]/sect1[9]/para[3] |
| Original | Traduction | The most manual approach, which is not normally convenient or
recommended, is to simply use the
registerCustomEditor() method of the
ConfigurableBeanFactory interface, assuming you have a
BeanFactory reference. |
|
| + para | Ref. /chapter[1]/sect1[9]/para[4] |
| Original | Traduction | The more convenient mechanism is to use a special bean factory
post-processor called CustomEditorConfigurer. Although
bean factory post-processors can be used semi-manually with BeanFactories,
this one has a nested property setup, so it is strongly recommended that,
as described here, it is used
with the ApplicationContext, where it may be deployed in similar fashion
to any other bean, and automatically detected and applied. |
|
| + para | Ref. /chapter[1]/sect1[9]/para[5] |
| Original | Traduction | Note that all bean factories and application contexts automatically
use a number of built-in property editors, through their use of something
called a BeanWrapper to handle property conversions.
The standard property editors that the BeanWrapper registers are listed in
the next chapter. Additionally, ApplicationContexts also override or add
an additional 3 editors to handle resource lookups in a manner appropriate
to the specific application context type. Thee are:
InputStreamEditor, ResourceEditor
and URLEditor. |
|
| | sect1
| | + title | Ref. /chapter[1]/sect1[10]/title[1] |
| Original | Traduction | Introduction to the ApplicationContext |
|
| + para | Ref. /chapter[1]/sect1[10]/para[1] |
| Original | Traduction | While the beans package provides basic
functionality for managing and manipulating beans, often in a programmatic
way, the context package adds ApplicationContext,
which enhances BeanFactory functionality in a more
framework-oriented style. Many users will use
ApplicationContext in a completely declarative fashion, not even having to
create it manually, but instead relying on support classes such as
ContextLoader to automatically start an ApplicationContext as part of the
normal startup process of a J2EE web-app. Of course, it is still possible
to programmatically create an ApplicationContext. |
|
| + para | Ref. /chapter[1]/sect1[10]/para[2] |
| Original | Traduction | The basis for the context package is the
ApplicationContext interface, located in the
org.springframework.context package. Deriving from the
BeanFactory interface, it provides all the functionality of BeanFactory.
To allow working in a more framework-oriented fashion, using layering and
hierarchical contexts, the context package also provides the following:
| + para | Ref. /chapter[1]/sect1[10]/para[2]/itemizedlist[1]/listitem[1]/para[1] |
| Original | Traduction | MessageSource, providing access to
messages in, i18n-style |
|
| + para | Ref. /chapter[1]/sect1[10]/para[2]/itemizedlist[1]/listitem[2]/para[1] |
| Original | Traduction | Access to resources, such as URLs and
files |
|
| + para | Ref. /chapter[1]/sect1[10]/para[2]/itemizedlist[1]/listitem[3]/para[1] |
| Original | Traduction | Event propagation to beans implementing
the ApplicationListener interface |
|
| + para | Ref. /chapter[1]/sect1[10]/para[2]/itemizedlist[1]/listitem[4]/para[1] |
| Original | Traduction | Loading of multiple (hierarchical)
contexts, allowing each to be focused on one particular
layer, for example the web layer of an application |
|
|
|
| + para | Ref. /chapter[1]/sect1[10]/para[3] |
| Original | Traduction | As the ApplicationContext includes all functionality of the
BeanFactory, it is generally recommended that it be used over the
BeanFactory, except for a few limited situations such as perhaps in an
Applet, where memory consumption might be critical, and a few extra
kilobytes might make a difference. The following sections described
functionality which ApplicationContext adds to basic BeanFactory
capabilities. |
|
| | sect1
| | + title | Ref. /chapter[1]/sect1[11]/title[1] |
| Original | Traduction | Added functionality of the
ApplicationContext |
|
| + para | Ref. /chapter[1]/sect1[11]/para[1] |
| Original | Traduction | As already stated in the previous section, the ApplicationContext
has a couple of features that distinguish it from the BeanFactory. Let us
review them one-by-one. |
| sect2
| | + title | Ref. /chapter[1]/sect1[11]/sect2[1]/title[1] |
| Original | Traduction | Using the MessageSource |
|
| + para | Ref. /chapter[1]/sect1[11]/sect2[1]/para[1] |
| Original | Traduction | The ApplicationContext interface extends an interface called
MessageSource, and therefore provides messaging (i18n
or internationalization) functionality. Together with the
NestingMessageSource, capable of resolving
hierarchical messages, these are the basic interfaces Spring provides to
do message resolution. Let's quickly review the methods defined there:
| + para | Ref. /chapter[1]/sect1[11]/sect2[1]/para[1]/itemizedlist[1]/listitem[1]/para[1] |
| Original | Traduction | String getMessage (String code, Object[] args,
String default, Locale loc): the basic method used to
retrieve a message from the MessageSource. When no message is
found for the specified locale, the default message is used. Any
arguments passed in are used as replacement values, using the
MessageFormat functionality provided by the
standard library. |
|
| + para | Ref. /chapter[1]/sect1[11]/sect2[1]/para[1]/itemizedlist[1]/listitem[2]/para[1] |
| Original | Traduction | String getMessage (String code, Object[] args,
Locale loc): essentially the same as the previous
method, but with one difference: no default message can be
specified; if the message cannot be found, a
NoSuchMessageException is thrown. |
|
| + para | Ref. /chapter[1]/sect1[11]/sect2[1]/para[1]/itemizedlist[1]/listitem[3]/para[1] |
| Original | Traduction | String getMessage(MessageSourceResolvable
resolvable, Locale locale): all properties used in the
methods above are also wrapped in a class named
MessageSourceResolvable, which you can use via
this method. |
|
|
|
| + para | Ref. /chapter[1]/sect1[11]/sect2[1]/para[2] |
| Original | Traduction | When an ApplicationContext gets loaded, it automatically searches
for a MessageSource bean defined in the context. The bean has to have
the name messageSource. If such a bean is found, all
calls to the methods described above will be delegated to the message
source that was found. If no message source was found, the
ApplicationContext attempts to see if it has a parent containing a bean
with the same name. If so, it uses that bean as the MessageSource. If it
can't find any source for messages, an empty
StaticMessageSource will be instantiated in order to
be able to accept calls to the methods defined above. |
|
| + para | Ref. /chapter[1]/sect1[11]/sect2[1]/para[3] |
| Original | Traduction | Spring currently provides two MessageSource
implementations. These are the
ResourceBundleMessageSource and the
StaticMessageSource. Both implement
NestingMessageSource in order to do nested messaging.
The StaticMessageSource is hardly ever used but provides programmatic
ways to add messages to the source. The ResourceBundleMessageSource is
more interesting and is the one we will provides an example for:
| + programlisting | Ref. /chapter[1]/sect1[11]/sect2[1]/para[3]/programlisting[1] |
| Original | Traduction | <beans>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>format</value>
<value>exceptions</value>
<value>windows</value>
</list>
</property>
</bean>
</beans> |
|
|
|
| + para | Ref. /chapter[1]/sect1[11]/sect2[1]/para[4] |
| Original | Traduction | This assumes you have three resource bundles defined on your
classpath called format,
exceptions and windows. Using the
JDK standard way of resolving messages through ResourceBundles, any
request to resolve a message will be handled. TODO: SHOW AN
EXAMPLE |
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[11]/sect2[2]/title[1] |
| Original | Traduction | Propagating events |
|
| + para | Ref. /chapter[1]/sect1[11]/sect2[2]/para[1] |
| Original | Traduction | Event handling in the ApplicationContext is provided through the
ApplicationEvent class and
ApplicationListener interface. If a bean which
implements the ApplicationListener interface is
deployed into the context, every time an
ApplicationEvent gets published to the
ApplicationContext, that bean will be notified. Essentially, this is the
standard Observer design pattern. Spring provides
three standard events:
| + title | Ref. /chapter[1]/sect1[11]/sect2[2]/para[1]/table[1]/title[1] |
| Original | Traduction | Built-in Events |
|
| + entry | Ref. /chapter[1]/sect1[11]/sect2[2]/para[1]/table[1]/tgroup[1]/thead[1]/row[1]/entry[1] |
| Original | Traduction | Event |
|
| + entry | Ref. /chapter[1]/sect1[11]/sect2[2]/para[1]/table[1]/tgroup[1]/thead[1]/row[1]/entry[2] |
| Original | Traduction | Explanation |
|
ContextRefreshedEvent
| + entry | Ref. /chapter[1]/sect1[11]/sect2[2]/para[1]/table[1]/tgroup[1]/tbody[1]/row[1]/entry[2] |
| Original | Traduction | Event published when the ApplicationContext is
initialized or refreshed. Initialized here means that all
beans are loaded, singletons are pre-instantiated and the
ApplicationContext is ready for use |
|
ContextClosedEvent
| + entry | Ref. /chapter[1]/sect1[11]/sect2[2]/para[1]/table[1]/tgroup[1]/tbody[1]/row[2]/entry[2] |
| Original | Traduction | Event published when the ApplicationContext is closed,
using the close() method on the
ApplicationContext. Closed here means that singletons are
destroyed |
|
RequestHandledEvent
| + entry | Ref. /chapter[1]/sect1[11]/sect2[2]/para[1]/table[1]/tgroup[1]/tbody[1]/row[3]/entry[2] |
| Original | Traduction | A web-specific event telling all beans that a HTTP
request has been serviced (i.e. this will be published
after the request has been finished).
Note that this event is only applicable for web applications
using Spring's DispatcherServlet |
|
|
|
| + para | Ref. /chapter[1]/sect1[11]/sect2[2]/para[2] |
| Original | Traduction | Implementing custom events can be done as well. Simply call the
publishEvent() method on the ApplicationContext,
specifying a parameter which is an instance of your custom event class
implementing ApplicationEvent. Let's look at an example. First, the
ApplicationContext: | + programlisting | Ref. /chapter[1]/sect1[11]/sect2[2]/para[2]/programlisting[1] |
| Original | Traduction | <bean id="emailer" class="example.EmailBean">
<property name="blackList">
<list>
<value>black@list.org</value>
<value>white@list.org</value>
<value>john@doe.org</value>
</list>
</property>
</bean>
<bean id="blackListListener" class="example.BlackListNotifier">
<property name="notificationAddress">
<value>spam@list.org</value>
</property>
</bean> |
| and then, the actual beans: | + programlisting | Ref. /chapter[1]/sect1[11]/sect2[2]/para[2]/programlisting[2] |
| Original | Traduction | public class EmailBean implements ApplicationContextAware {
/** the blacklist */
private List blackList;
public void setBlackList(List blackList) {
this.blackList = blackList;
}
public void setApplicationContext(ApplicationContext ctx) {
this.ctx = ctx;
}
public void sendEmail(String address, String text) {
if (blackList.contains(address)) {
BlackListEvent evt = new BlackListEvent(address, text);
ctx.publishEvent(evt);
return;
}
// send email
}
}
public class BlackListNotifier implement ApplicationListener {
/** notification address */
private String notificationAddress;
public void setNotificationAddress(String notificationAddress) {
this.notificationAddress = notificationAddress;
}
public void onApplicationEvent(ApplicationEvent evt) {
if (evt instanceof BlackListEvent) {
// notify appropriate person
}
}
} |
| Of course, this particular example could probably be
implemented in better ways (perhaps by using AOP features), but it
should be sufficient to illustrate the basic event mechanism. |
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[11]/sect2[3]/title[1] |
| Original | Traduction | Using resources within Spring |
|
| + para | Ref. /chapter[1]/sect1[11]/sect2[3]/para[1] |
| Original | Traduction | Many applications need to access resources. Resources could
include files, but also things like web pages or NNTP newsfeeds. Spring
provides a clean and transparent way of accessing resources in a
protocol independent way. The ApplicationContext interface includes a
method (getResource(String)) to take care of
this. |
|
| + para | Ref. /chapter[1]/sect1[11]/sect2[3]/para[2] |
| Original | Traduction | The Resource class defines a couple of methods that are shared
across all Resource implementations:
| + title | Ref. /chapter[1]/sect1[11]/sect2[3]/para[2]/table[1]/title[1] |
| Original | Traduction | Resource functionality |
|
| + entry | Ref. /chapter[1]/sect1[11]/sect2[3]/para[2]/table[1]/tgroup[1]/thead[1]/row[1]/entry[1] |
| Original | Traduction | Method |
|
| + entry | Ref. /chapter[1]/sect1[11]/sect2[3]/para[2]/table[1]/tgroup[1]/thead[1]/row[1]/entry[2] |
| Original | Traduction | Explanation |
|
getInputStream()
| + entry | Ref. /chapter[1]/sect1[11]/sect2[3]/para[2]/table[1]/tgroup[1]/tbody[1]/row[1]/entry[2] |
| Original | Traduction | Opens an InputStream on the resource and returns
it |
|
exists()
| + entry | Ref. /chapter[1]/sect1[11]/sect2[3]/para[2]/table[1]/tgroup[1]/tbody[1]/row[2]/entry[2] |
| Original | Traduction | Checks if the resource exists, returning false if it
doesn't |
|
isOpen()
| + entry | Ref. /chapter[1]/sect1[11]/sect2[3]/para[2]/table[1]/tgroup[1]/tbody[1]/row[3]/entry[2] |
| Original | Traduction | Will return true is multiple streams cannot be opened
for this resource. This will be false for some resources, but
file-based resources for instance, cannot be read multiple
times concurrently |
|
getDescription()
| + entry | Ref. /chapter[1]/sect1[11]/sect2[3]/para[2]/table[1]/tgroup[1]/tbody[1]/row[4]/entry[2] |
| Original | Traduction | Returns a description of the resource, often the fully
qualified file name or the actual URL |
|
|
|
| + para | Ref. /chapter[1]/sect1[11]/sect2[3]/para[3] |
| Original | Traduction | A couple of Resource implementations are provided by Spring. They
all need a String representing the actual location of the resource.
Based upon that String, Spring will automatically choose the right
Resource implementation for you. When asking an ApplicationContext for a
resource first of all Spring will inspect the resource location you're
specifying and look for any prefixes. Depending on the implementation of
the ApplicationContext more or less Resource implementations are
available. Resources can best be configured by using the ResourceEditor
and for example the XmlBeanFactory. |
|
| |
| | sect1
| | + title | Ref. /chapter[1]/sect1[12]/title[1] |
| Original | Traduction | Customized behavior in the ApplicationContext |
|
| + para | Ref. /chapter[1]/sect1[12]/para[1] |
| Original | Traduction | The BeanFactory already offers a number of mechanisms to control the
lifecycle of beans deployed in it (such as marker interfaces like
InitializingBean or DisposableBean,
their configuration only equivalents such as the
init-method and destroy-method
attributes in an XmlBeanFactory config, and bean post-processors. In an
ApplicationContext, all of these still work, but additional mechanisms are
added for customizing behavior of beans and the container. |
| sect2
| | + title | Ref. /chapter[1]/sect1[12]/sect2[1]/title[1] |
| Original | Traduction | ApplicationContextAware marker
interface |
|
| + para | Ref. /chapter[1]/sect1[12]/sect2[1]/para[1] |
| Original | Traduction | All marker interfaces available with BeanFactories still work. The
ApplicationContext does add one extra marker interface which beans may
implement,
org.springframework.context.ApplicationContextAware.
A bean which implements this interface and is deployed into the context
will be called back on creation of the bean, using the interface's
setApplicationContext() method, and provided with a
reference to the context, which may be stored for later interaction with
the context. |
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[12]/sect2[2]/title[1] |
| Original | Traduction | The BeanPostProcessor |
|
| + para | Ref. /chapter[1]/sect1[12]/sect2[2]/para[1] |
| Original | Traduction | Bean post-processors, java classes which implement the
org.springframework.beans.factory.config.BeanPostProcessor
interface, have already
been mentioned. It is worth mentioning again here though, that
post-processors are much more convenient to use in ApplicationContexts
than in plain BeanFactories. In an ApplicationContext, any deployed bean
which implements the above marker interface is automatically detected
and registered as a bean post-processor, to be called appropriately at
creation time for each bean in the factory. |
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[12]/sect2[3]/title[1] |
| Original | Traduction | The BeanFactoryPostProcessor |
|
| + para | Ref. /chapter[1]/sect1[12]/sect2[3]/para[1] |
| Original | Traduction | Bean factory post-processors, java classes which implement the
org.springframework.beans.factory.config.BeanFactoryPostProcessor
interface, have already
been mentioned. It is worth mentioning again here though, that bean
factory post-processors are much more convenient to use in
ApplicationContexts than in plain BeanFactories. In an
ApplicationContext, any deployed bean which implements the above marker
interface is automatically detected as a bean factory post-processor, to
be called at the appropriate time. |
|
| | sect2
| | + title | Ref. /chapter[1]/sect1[12]/sect2[4]/title[1] |
| Original | Traduction | The PropertyPlaceholderConfigurer |
|
| + para | Ref. /chapter[1]/sect1[12]/sect2[4]/para[1] |
| Original | Traduction | The PropertyPlaceholderConfigurer has already been
described, as used with a BeanFactory. It is worth mentioning here
though, that it is generally more convenient to use it with an
ApplicationContext, since the context will automatically recognize and
apply any bean factory post-processors, such as this one, when they are
simply deployed into it like any other bean. There is no need for a
manual step to execute it. |
|
| + programlisting | Ref. /chapter[1]/sect1[12]/sect2[4]/programlisting[1] |
| Original | Traduction | <!-- property placeholder post-processor -->
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>jdbc.properties</value></property>
</bean> |
|
| |
| | sect1
| | + title | Ref. /chapter[1]/sect1[13]/title[1] |
| Original | Traduction | Registering additional custom PropertyEditors |
|
| + para | Ref. /chapter[1]/sect1[13]/para[1] |
| Original | Traduction | As previously
mentioned, standard JavaBeans PropertyEditors are used to convert property
values expressed as strings to the actual complex type of the property.
CustomEditorConfigurer, a bean factory post-processor,
may be used to conveniently add support for additional PropertyEditors to
an ApplicationContext. |
|
| + para | Ref. /chapter[1]/sect1[13]/para[2] |
| Original | Traduction | Consider a user class ExoticType, and another
class DependsOnExoticType which needs ExoticType set
as a property: | + programlisting | Ref. /chapter[1]/sect1[13]/para[2]/programlisting[1] |
| Original | Traduction | public class ExoticType {
private String name;
public ExoticType(String name) {
this.name = name;
}
}
public class DependsOnExoticType {
private ExoticType type;
public void setType(ExoticType type) {
this.type = type;
}
} |
| When things are properly set up, we want to be able to
assign the type property as a string, which a PropertyEditor will behind
the scenes convert into a real ExoticType object.: | + programlisting | Ref. /chapter[1]/sect1[13]/para[2]/programlisting[2] |
| Original | Traduction | <bean id="sample" class="example.DependsOnExoticType">
<property name="type"><value>aNameForExoticType</value></property>
</bean> |
| The PropertyEditor could look similar to this:
| + programlisting | Ref. /chapter[1]/sect1[13]/para[2]/programlisting[3] |
| Original | Traduction | // converts string representation to ExoticType object
public class ExoticTypeEditor extends PropertyEditorSupport {
private String format;
public void setFormat(String format) {
this.format = format;
}
public void setAsText(String text) {
if (format != null && format.equals("upperCase")) {
text = text.toUpperCase();
}
ExoticType type = new ExoticType(text);
setValue(type);
}
} |
| Finally, we use CustomEditorConfigurer to
register the new PropertyEditor with the ApplicationContext, which will
then be able to use it as needed.: | + programlisting | Ref. /chapter[1]/sect1[13]/para[2]/programlisting[4] |
| Original | Traduction | <bean id="customEditorConfigurer"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="example.ExoticType">
<bean class="example.ExoticTypeEditor">
<property name="format">
<value>upperCase</value>
</property>
</bean>
</entry>
</map>
</property>
</bean> |
|
|
|
| | sect1
| | + title | Ref. /chapter[1]/sect1[14]/title[1] |
| Original | Traduction | Setting a bean property or constructor arg from a property
expression |
|
| + para | Ref. /chapter[1]/sect1[14]/para[1] |
| Original | Traduction | PropertyPathFactoryBean is a
FactoryBean that evaluates a property path on a given
target object. The target object can be specified directly or via a bean
name. This value may then be used in another bean definition as a property
value or constructor argument. |
|
| + para | Ref. /chapter[1]/sect1[14]/para[2] |
| Original | Traduction | Here's an example where a path is used against another bean, by
name: | + programlisting | Ref. /chapter[1]/sect1[14]/para[2]/programlisting[1] |
| Original | Traduction | // target bean to be referenced by name
<bean id="person" class="org.springframework.beans.TestBean" singleton="false">
<property name="age"><value>10</value></property>
<property name="spouse">
<bean class="org.springframework.beans.TestBean">
<property name="age"><value>11</value></property>
</bean>
</property>
</bean>
// will result in 11, which is the value of property 'spouse.age' of bean 'person'
<bean id="theAge" class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<property name="targetBeanName"><value>person</value></property>
<property name="propertyPath"><value>spouse.age</value></property>
</bean> |
|
|
|
| + para | Ref. /chapter[1]/sect1[14]/para[3] |
| Original | Traduction | In this example, a path is evaluated against an inner bean: |
|
| + para | Ref. /chapter[1]/sect1[14]/para[4] |
| Original | Traduction | | + programlisting | Ref. /chapter[1]/sect1[14]/para[4]/programlisting[1] |
| Original | Traduction | // will result in 12, which is the value of property 'age' of the inner bean
<bean id="theAge" class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<property name="targetObject">
<bean class="org.springframework.beans.TestBean">
<property name="age"><value>12</value></property>
</bean>
</property>
<property name="propertyPath"><value>age</value></property>
</bean> |
| There is also a shortcut form, where the bean
name is the property path. | + programlisting | Ref. /chapter[1]/sect1[14]/para[4]/programlisting[2] |
| Original | Traduction | // will result in 10, which is the value of property 'age' of bean 'person'
<bean id="person.age" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/> |
|
|
|
| + para | Ref. /chapter[1]/sect1[14]/para[5] |
| Original | Traduction | This form does mean that there is no choice in the name of the bean,
any reference to it will also have to use the same id, which is the path.
Of curse, if used as an inner bean, there is no need to refer to it at
all: |
|
| + para | Ref. /chapter[1]/sect1[14]/para[6] |
| Original | Traduction | | + programlisting | Ref. /chapter[1]/sect1[14]/para[6]/programlisting[1] |
| Original | Traduction | <bean id="..." class="...">
<proprty name="age">
<bean id="person.age"
class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
</property>
</bean> |
| The result type may be specifically set in the
actual definition. This is not necessary for most use cases, but can be of
use for some. Please see the JavaDocs for more info on this
feature. |
|
| | sect1
| | + title | Ref. /chapter[1]/sect1[15]/title[1] |
| Original | Traduction | Setting a bean property or constructor arg from a field
value |
|
| + para | Ref. /chapter[1]/sect1[15]/para[1] |
| Original | Traduction | FileRetrievingFactoryBean is a FactoryBean which retrieves a static
or non-static field value. It is typically used for retrieving public
static final constants, which may then be used to set a property value or
constructor arg for another bean. |
|
| + para | Ref. /chapter[1]/sect1[15]/para[2] |
| Original | Traduction | Here's an example which shows how a static field is exposed, by
using the staticField property: |
|
| + programlisting | Ref. /chapter[1]/sect1[15]/para[3]/programlisting[1] |
| Original | Traduction | <bean id="myField"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="staticField"><value>java.sql.Connection.TRANSACTION_SERIALIZABLE</value></property>
</bean> |
|
| + para | Ref. /chapter[1]/sect1[15]/para[4] |
| Original | Traduction | There's also a convenience usage form where the static field is
specified as a bean name: |
|
| + programlisting | Ref. /chapter[1]/sect1[15]/para[5]/programlisting[1] |
| Original | Traduction | <bean id="java.sql.Connection.TRANSACTION_SERIALIZABLE"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/> |
|
| + para | Ref. /chapter[1]/sect1[15]/para[6] |
| Original | Traduction | This means there is no longer any choice in what the bean id is (so
any other bean that refers to it will also have to use this longer name),
but this form is very concise to define, and very convenient to use as an
inner bean since the id doesn't have to be specified for the bean
reference: | + programlisting | Ref. /chapter[1]/sect1[15]/para[6]/programlisting[1] |
| Original | Traduction | <bean id="..." class="...">
<proprty name="isolation">
<bean id="java.sql.Connection.TRANSACTION_SERIALIZABLE"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/>
</property>
</bean> |
| It's also possible to access a non-static field
of another bean, as described in the JavaDocs. |
|
| | sect1
| | + title | Ref. /chapter[1]/sect1[16]/title[1] |
| Original | Traduction | Invoking another method and optionally using the return
value. |
|
| + para | Ref. /chapter[1]/sect1[16]/para[1] |
| Original | Traduction | it is sometimes necessary to call a static or non-static method in
one class, just to perform some sort of initialization, before some other
class is used. Additionally, it is sometimes necessary to set a property
on a bean, as the result of a method call on another bean in the
container, or a static method call on any arbitrary class. For both of
these purposes, a helper class called
MethodInvokingFactoryBean may be used. This is a
FactoryBean which returns a
value which is the result of a static or instance method
invocation. |
|
| + para | Ref. /chapter[1]/sect1[16]/para[2] |
| Original | Traduction | We would however recommend that for the second use case,
factory-methods, described previously, are a better all around
choice. |
|
| + para | Ref. /chapter[1]/sect1[16]/para[3] |
| Original | Traduction | An example (in an XML based BeanFactory definition) of a bean
definition which uses this class to force some sort of static
initialization: |
|
| + para | Ref. /chapter[1]/sect1[16]/para[4] |
| Original | Traduction | | + programlisting | Ref. /chapter[1]/sect1[16]/para[4]/programlisting[1] |
| Original | Traduction | <bean id="force-init" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"><value>com.example.MyClass.initialize</value></property>
</bean>
<bean id="bean1" class="..." depends-on="force-init">
...
</bean> |
| Note that the definition for
bean1 has used the depends-on
attribute to refer to the force-init bean, which will
trigger initializing force-init first, and thus calling
the static initializer method, when bean1 is first
initialized. |
|
| + para | Ref. /chapter[1]/sect1[16]/para[5] |
| Original | Traduction | Here's an example of a bean definition which uses this class to call
a static factory method: |
|
| + programlisting | Ref. /chapter[1]/sect1[16]/para[6]/programlisting[1] |
| Original | Traduction | <bean id="myClass" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"><value>com.whatever.MyClassFactory.getInstance</value></property>
</bean> |
|
| + para | Ref. /chapter[1]/sect1[16]/para[7] |
| Original | Traduction | An example of calling a static method then an instance method to get
at a Java System property. Somewhat verbose, but it works. |
|
| + programlisting | Ref. /chapter[1]/sect1[16]/para[8]/programlisting[1] |
| Original | Traduction | <bean id="sysProps" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass"><value>java.lang.System</value></property>
<property name="targetMethod"><value>getProperties</value></property>
</bean>
<bean id="javaVersion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject"><ref local="sysProps"/></property>
<property name="targetMethod"><value>getProperty</value></property>
<property name="arguments">
<list>
<value>java.version</value>
</list>
</property>
</bean> |
|
| + para | Ref. /chapter[1]/sect1[16]/para[9] |
| Original | Traduction | Note that as it is expected to be used mostly for accessing factory
methods, MethodInvokingFactoryBean by default operates in a
singleton fashion. The first request by the container
for the factory to produce an object will cause the specified method
invocation, whose return value will be cached and returned for the current
and subsequent requests. An internal singleton property
of the factory may be set to false, to cause it to invoke the target
method each time it is asked for an object. |
|
| + para | Ref. /chapter[1]/sect1[16]/para[10] |
| Original | Traduction | A static target method may be specified by setting the
targetMethod property to a String representing the
static method name, with targetClass specifying the
Class that the static method is defined on. Alternatively, a target
instance method may be specified, by setting the
targetObject property as the target object, and the
targetMethod property as the name of the method to call
on that target object. Arguments for the method invocation may be
specified by setting the args property. |
|
| | sect1
| | + title | Ref. /chapter[1]/sect1[17]/title[1] |
| Original | Traduction | Importing Bean Definitions from One File Into Another |
|
| + para | Ref. /chapter[1]/sect1[17]/para[1] |
| Original | Traduction | It's often useful to split up container definitions into multiple XML
files. One way to then load an application context which is configured
from all these XML fragments is to use the application context constructor
which takes multiple Resource locations. With a bean factory, a bean
definition reader can be used multiple times to read definitions from each
file in turn. |
|
| + para | Ref. /chapter[1]/sect1[17]/para[2] |
| Original | Traduction | Generally, the Spring team prefers the above approach, since it
keeps container configurations files unaware of the fact that they are
being combined with others. However, an alternate approach is to from one
XML bean definition file, use one or more instances of the
import element to load definitions from one or more
other files. Any import elements must be placed before
bean elements in the file doing the importing. Let's
look at a sample: |
|
| + programlisting | Ref. /chapter[1]/sect1[17]/para[3]/programlisting[1] |
| Original | Traduction | <beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
. . . |
|
| + para | Ref. /chapter[1]/sect1[17]/para[4] |
| Original | Traduction | In this example, external bean definitions are being loaded from 3
files, services.xml,
messageSource.xml, and
themeSource.xml. All location paths are considered
relative to the definition file doing the importing, so
services.xml in this case must be in the same directory
or classpath location as the file doing the importing, while
messageSource.xml and
themeSource.xml must be in a
resources location below the location of the importing
file. As you can see, a leading slash is actually ignored, but given that
these are considered relative paths, it is probably better form not to use
the slash at all. |
|
| + para | Ref. /chapter[1]/sect1[17]/para[5] |
| Original | Traduction | The contents of the files being imported must be fully valid XML
bean definition files according to the DTD, including the top level
beans element. |
|
| | sect1
| | + title | Ref. /chapter[1]/sect1[18]/title[1] |
| Original | Traduction | Creating an ApplicationContext from a web application |
|
| + para | Ref. /chapter[1]/sect1[18]/para[1] |
| Original | Traduction | As opposed to the BeanFactory, which will often be created
programmatically, ApplicationContexts can be created declaratively using
for example a ContextLoader. Of course you can also
create ApplicationContexts programmatically using one of the
ApplicationContext implementations. First, let's examine the ContextLoader
and its implementations. |
|
| + para | Ref. /chapter[1]/sect1[18]/para[2] |
| Original | Traduction | The ContextLoader has two implementations: the
ContextLoaderListener and the
ContextLoaderServlet. They both have the same
functionality but differ in that the listener cannot be used in Servlet
2.2 compatible containers. Since the Servlet 2.4 specification, listeners
are required to initialize after startup of a web application. A lot of
2.3 compatible containers already implement this feature. It is up to you
as to which one you use, but all things being equal you should probably
prefer ContextLoaderListener; for more information on
compatibility, have a look at the JavaDoc for the
ContextLoaderServlet. |
|
| + para | Ref. /chapter[1]/sect1[18]/para[3] |
| Original | Traduction | You can register an ApplicationContext using the
ContextLoaderListener as follows: | + programlisting | Ref. /chapter[1]/sect1[18]/para[3]/programlisting[1] |
| Original | Traduction | <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- OR USE THE CONTEXTLOADERSERVLET INSTEAD OF THE LISTENER
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
--> |
| The listener inspects the
contextConfigLocation parameter. If it doesn't exist,
it'll use /WEB-INF/applicationContext.xml as a default.
When it does exist, it'll separate the String using
predefined delimiters (comma, semi-colon and space) and use the values as
locations where application contexts will be searched for. The
ContextLoaderServlet can - as said - be used instead of the
ContextLoaderListener. The servlet will use the contextConfigLocation
parameter just as the listener does. |
|
| | sect1
| | + title | Ref. /chapter[1]/sect1[19]/title[1] |
| Original | Traduction | Glue code and the evil singleton |
|
| + para | Ref. /chapter[1]/sect1[19]/para[1] |
| Original | Traduction | The majority of the code inside an application is best written in a
Dependency Injection (Inversion of Control) style, where that code is
served out of a BeanFactory or ApplicationContext container, has its own
dependencies supplied by the container when it is created, and is
completely unaware of the container. However, for the small glue layers of
code that are sometimes needed to tie other code together, there is
sometimes a need for singleton (or quasi-singleton) style access to a
BeanFactory or ApplicationContext. For example, third party code may try
to construct new objects directly (Class.forName()
style), without the ability to force it to get these objects out of a
BeanFactory. If the object constructed by the third party code is just a
small stub or proxy, which then uses a singleton style access to a
BeanFactory/ApplicationContext to get a real object to delegate to, then
inversion of control has still been achieved for the majority of the code
(the object coming out of the BeanFactory); thus most code is still
unaware of the container or how it is accessed, and remains uncoupled from
other code, with all ensuing benefits. EJBs may also use this stub/proxy
approach to delegate to a plain java implementation object, coming out of
a BeanFactory. While the BeanFactory ideally does not have to be a
singleton, it may be unrealistic in terms of memory usage or
initialization times (when using beans in the BeanFactory such as a
Hibernate SessionFactory) for each bean to use its own, non-singleton
BeanFactory. |
|
| + para | Ref. /chapter[1]/sect1[19]/para[2] |
| Original | Traduction | As another example, in a complex J2EE apps with multiple layers
(i.e. various JAR files, EJBs, and WAR files packaged as an EAR), with
each layer having its own ApplicationContext definition (effectively
forming a hierarchy), the preferred approach when there is only one
web-app (WAR) in the top hierarchy is to simply create one composite
ApplicationContext from the multiple XML definition files from each layer.
All the ApplicationContext variants may be constructed from multiple
definition files in this fashion. However, if there are multiple sibling
web-apps at the top of the hierarchy, it is problematic to create an
ApplicationContext for each web-app which consists of mostly identical
bean definitions from lower layers, as there may be issues due to
increased memory usage, issues with creating multiple copies of beans
which take a long time to initialize (i.e. a Hibernate SessionFactory),
and possible issues due to side-effects. As an alternative, classes such
as ContextSingletonBeanFactoryLocator or
SingletonBeanFactoryLocator
may be used to demand load multiple hierarchical (i.e. one is a parent of
another) BeanFactories or ApplicationContexts in an effectively singleton
fashion, which may then be used as the parents of the web-app
ApplicationContexts. The result is that bean definitions for lower layers
are loaded only as needed, and loaded only once. |
| sect2
| | + title | Ref. /chapter[1]/sect1[19]/sect2[1]/title[1] |
| Original | Traduction | Using SingletonBeanFactoryLocator and
ContextSingletonBeanFactoryLocator |
|
| + para | Ref. /chapter[1]/sect1[19]/sect2[1]/para[2] |
| Original | Traduction | As mentioned in the chapter on EJBs, the Spring convenience base
classes for EJBs normally use a non-singleton
BeanFactoryLocator implementation, which is easily
replaced by the use of SingletonBeanFactoryLocator
and ContextSingletonBeanFactoryLocator if there is a
need. |
|
| |
| |
|