The IoC container
- Introduction
+ Introduction to the Spring IoC container and beans
- This chapter covers the Spring Framework's implementation of the
+ This chapter covers the Spring Framework implementation of the
Inversion of Control (IoC) See the section entitled principle.The org.springframework.beans and
- org.springframework.context packages provide the basis
- for the Spring Framework's IoC container. The org.springframework.context packages are the basis for
+ Spring Framework's IoC container. The BeanFactory
interface provides an advanced configuration mechanism capable of managing
- objects of any nature. The ApplicationContext
- interface builds on top of the BeanFactory
- (it is a sub-interface) and adds other functionality such as easier
- integration with Spring's AOP features, message resource handling (for use
- in internationalization), event propagation, and application-layer in
- internationalization), event publication, and application-layer specific
- contexts such as the WebApplicationContext
- for use in web applications.
+ is a sub-interface of BeanFactory. It adds
+ easier integration with Spring's AOP features; message resource handling
+ (for use in internationalization, event propagation, and application-layer
+ in internationalization); event publication; and application-layer
+ specific contexts such as the
+ WebApplicationContext for use in web
+ applications.In short, the BeanFactory provides
- the configuration framework and basic functionality, while the
+ the configuration framework and basic functionality, and the
ApplicationContext adds more
- enterprise-centric functionality to it. The
+ enterprise-specific functionality. The
ApplicationContext is a complete superset
of the BeanFactory, and is used exclusively
in this chapter when describing Spring's IoC container. For more
- information on using the BeanFactory instead of an
- ApplicationContext refer to the section BeanFactory instead of the
+ ApplicationContext refer to .
+ In Spring, the objects that form the backbone of your application
+ and that are managed by the Spring IoC container
+ are called beans. A bean is an object that is
+ instantiated, assembled, and otherwise managed by a Spring IoC container.
+ Otherwise, a bean is simply one of many objects in your application.
+ Beans, and the dependencies between them, are
+ reflected in the configuration metadata used by a
+ container.
+
This chapter is divided into two parts, with the first part covering Inversion of Control
features and the second part
@@ -46,159 +55,125 @@
publication and internationalization.
-
- Basics - containers and beans
+
+ The Spring IoC container
- In Spring, those objects that form the backbone of your application
- and that are managed by the Spring IoC container
- are referred to as beans. A bean is simply an
- object that is instantiated, assembled and otherwise managed by a Spring
- IoC container; other than that, there is nothing special about a bean (it
- is in all other respects one of probably many objects in your
- application). These beans, and the dependencies
- between them, are reflected in the configuration
- metadata used by a container.
+ The interface
+ org.springframework.context.ApplicationContext
+ represents the Spring IoC container and is responsible for instantiating,
+ configuring, and assembling the aforementioned beans. The container gets
+ its instructions on what objects to instantiate, configure, and assemble
+ by reading configuration metadata. The configuration metadata is
+ represented in XML, Java annotations, or Java code. It allows you to
+ express the objects that compose your application and the rich
+ interdependencies between such objects.
-
- Why... bean?
+ Some implementations of the
+ ApplicationContext interface are supplied
+ out-of-the-box with Spring. In standalone applications it is common to
+ create an instance of ClassPathXmlApplicationContext
+ or FileSystemXmlApplicationContext.
+ This is because XML is the traditional format for defining configuration
+ metadata. To support the mixing of different configuration metadata
+ formats, use the GenericApplicationContext
+ implementation.
- The motivation for using the name 'bean', as
- opposed to 'component' or
- 'object' is rooted in the origins of the Spring
- Framework itself (it arose partly as a response to the complexity of
- Enterprise JavaBeans).
-
+ In most application scenarios, explicit user code is not required to
+ instantiate one or more instances of a Spring IoC container. For example,
+ in a web application scenario, a simple eight (or so) lines of boilerplate
+ J2EE web descriptor XML in the web.xml file of the
+ application will typically suffice (see ).
-
- The container
+ The following diagram is a high-level view of how Spring works. Your
+ application classes are combined with configuration metadata so that after
+ the ApplicationContext is created and initialized,
+ you have a fully configured and executable system or application.
- The interface
- org.springframework.context.ApplicationContext
- represents the Spring IoC container and is responsible for
- instantiating, configuring, and assembling the aforementioned beans. The
- container gets its instructions on what objects to instantiate,
- configure and assemble by reading configuration metadata. The
- configuration metadata can be represented in either XML, Java
- annotations, or Java code and allows you to express the objects that
- compose your application and the rich interdependencies between such
- objects.
+
+
+
+
- There are a number of implementations of the
- ApplicationContext interface that come supplied
- straight out-of-the-box with Spring. In standalone applications it has
- traditionally been common to pragmatically create an instance of ClassPathXmlApplicationContext
- or FileSystemXmlApplicationContext.
- This is because XML has been the traditional format for defining the
- configuration metadata. To support the mixing of different configuration
- metadata formats use the GenericApplicationContext
- implementation.
+
+
+
- In the vast majority of application scenarios, explicit user code
- is not required to instantiate one or more instances of a Spring IoC
- container. For example, in a web application scenario, a simple eight
- (or so) lines of boilerplate J2EE web descriptor XML in the
- web.xml file of the application will typically
- suffice (see ).
+
The Spring IoC container
+
- The high level view of how the Spring works is shown below. Your
- application classes are combined with configuration metadata so that
- once the ApplicationContext is created and
- initialized you have a fully configured and executable system or
- application.
+
+ Configuration metadata
-
-
-
-
+ As the preceding diagram shows, the Spring IoC container consumes
+ a form of configuration metadata; this
+ configuration metadata represents how you as an application developer
+ tell the Spring container to instantiate, configure, and assemble the
+ objects in your application.
-
-
-
+ Configuration metadata is traditionally supplied in a simple and
+ intuitive XML format, which is what most of this chapter uses to convey
+ key concepts and features of the Spring IoC container.
-
The Spring IoC container
-
+
+ XML-based metadata is not the only allowed
+ form of configuration metadata. The Spring IoC container itself is
+ totally decoupled from the format in which this
+ configuration metadata is actually written.
+
-
- Configuration metadata
+ For information about using other forms of metadata with the
+ Spring container, see:
- As can be seen in the above image, the Spring IoC container
- consumes some form of configuration metadata;
- this configuration metadata is nothing more than how you (as an
- application developer) inform the Spring container as to how to
- instantiate, configure, and assemble [the objects in
- your application].
+
+
+ Annotation-based
+ configuration: Spring 2.5 introduced support for
+ annotation-based configuration metadata.
+
- This configuration metadata has historically been supplied in a
- simple and intuitive XML format and so the majority of this chapter
- will use the XML format to convey key concepts and features of the
- Spring IoC container.
+
+ Java-based
+ configuration: Starting with Spring 3.0, many features
+ provided by the Spring JavaConfig
+ project became part of the core Spring Framework. Thus you
+ can define beans external to your application classes by using Java
+ rather than XML files. To use these new features, see the
+ @Configuration, @Bean,
+ @Import and
+ @DependsOn annotations.
+
+
-
- While XML-based metadata has been by far the most commonly
- used form of configuration metadata. It is not
- however the only form of configuration metadata that is allowed. The
- Spring IoC container itself is totally
- decoupled from the format in which this configuration metadata is
- actually written.
-
+ Spring configuration consists of at least one and typically more
+ than one bean definition that the container must manage. XML-based
+ configuration metadata shows these beans configured as
+ <bean/> elements inside a top-level
+ <beans/> element.
- You can find details of other forms of metadata that the Spring
- container can consume in the following sections
+ These bean definitions correspond to the actual objects that make
+ up your application. Typically you define service layer objects, data
+ access objects (DAOs), presentation objects such as Struts
+ Action instances, infrastructure objects
+ such as Hibernate SessionFactories, JMS
+ Queues, and so forth. Typically one does
+ not configure fine-grained domain objects in the container, because it
+ is usually the responsibility of DAOs and business logic to create and
+ load domain objects. However, you can use Spring's integration with
+ AspectJ to configure objects that have been created outside the control
+ of an IoC container. See Using
+ AspectJ to dependency inject domain objects with Spring.
-
-
- Annotation-based
- configuration: Spring 2.5 introduced support for annotation
- based configuration metadata.
-
+ The following example shows the basic structure of XML-based
+ configuration metadata:
-
- Java-based
- configuration: Starting with Spring 3.0 many of the
- features provided by the Spring JavaConfig
- project have been added to the core Spring Framework. This
- allows you to define beans external to your application classes
- using Java rather than XML files. Take a look at the
- @Configuration,
- @Bean, @Import and
- @DependsOn annotations for how to
- use these new features.
-
-
-
- Spring configuration consists of at least one bean definition
- that the container must manage, but typically there will be more than
- one bean definition. When using XML-based configuration metadata,
- these beans are configured as <bean/>
- elements inside a top-level <beans/>
- element.
-
- These bean definitions correspond to the actual objects that
- make up your application. Typically you will have bean definitions for
- your service layer objects, your data access objects (DAOs),
- presentation objects such as Struts
- Action instances, infrastructure
- objects such as Hibernate
- SessionFactories, JMS
- Queues, and so forth. Typically one
- does not configure fine-grained domain objects in the container,
- because it is usually the responsibility of DAOs and business logic to
- create/load domain objects. However, one can use Spring's integration
- with AspectJ to configure objects that have been created outside the
- control of an IoC container. See the section Using AspectJ to dependency inject domain
- objects with Spring for more information.
-
- Find below an example of the basic structure of XML-based
- configuration metadata.
-
- <?xml version="1.0" encoding="UTF-8"?>
+ <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
@@ -216,39 +191,35 @@
</beans>
- The id attribute is a string that you use to
- identify the individual bean definition. The class
- attribute defines the type of the bean and uses the fully qualified
- classname. The value of the id attribute is used as a means to refer
- to collaborating objects. Note the XML for referring to collaborating
- objects is not shown in this example, see the section on Dependencies for more
- information.
-
+ The id attribute is a string that you use to
+ identify the individual bean definition. The class
+ attribute defines the type of the bean and uses the fully qualified
+ classname. The value of the id attribute refers to collaborating
+ objects. The XML for referring to collaborating objects is not shown in
+ this example; see Dependencies
+ for more information.Instantiating a container
- Instantiating a Spring IoC container is straightforward.
+ Instantiating a Spring IoC container is straightforward. The
+ location path or paths supplied to an
+ ApplicationContext constructor are
+ actually resource strings that allow the container to load configuration
+ metadata from a variety of external resources such as the local file
+ system, from the Java CLASSPATH, and so on.ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
- The location path or paths supplied to an
- ApplicationContext constructor are
- actually resource strings that allow the container to load
- configuration metadata from a variety of external resources such as
- the local file system, from the Java CLASSPATH,
- etc.
-
- Once you have learned about Spring's IoC container, you may wish
- to learn a little more about Spring's
- Resource abstraction, as described in
- the chapter entitled .
+ After you learn about Spring's IoC container, you may want to
+ know more about Spring's Resource
+ abstraction, as described in .
- The services.xml configuration file is
+ The following example shows the service layer objects
+ (services.xml) configuration file:<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
@@ -269,7 +240,8 @@
</beans>
- and daos.xml is
+ The following example shows the data access objects
+ daos.xml) file:<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
@@ -290,28 +262,27 @@
</beans>In this example, the service layer consists of the class
- PetStoreServiceImpl and there are two data access
- objects of the type SqlMapAccountDao and
- SqlMapItemDao which are based on the iBatis Object/Relational mapping
- framework. While the details of configuring an object's dependencies is
- discussed in the chapter, Dependencies, it is intuitive to see
- that the property element refers to the name of
- JavaBean property and the ref element refers to the
- name of another bean definition. This linkage between id and ref
- elements expresses the dependency between collaborating objects.
+ PetStoreServiceImpl, and two data access objects
+ of the type SqlMapAccountDao and SqlMapItemDao
+ are based on the iBatis
+ Object/Relational mapping framework. The property
+ name element refers to the name of the JavaBean property, and
+ the ref element refers to the name of another bean
+ definition. This linkage between id and ref elements expresses the
+ dependency between collaborating objects. For details of configuring an
+ object's dependencies, see Dependencies.
Composing XML-based configuration metadata
- It can often be useful to split up bean definitions into
- multiple XML files. Often each individual XML configuration file
- represents a logical layer or module in your architecture. 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 as
- was shown in the previous section.
+ It can be useful to split up bean definitions into multiple XML
+ files. Often each individual XML configuration file represents a
+ logical layer or module in your architecture. One way to then load an
+ application context that is configured from all these XML fragments is
+ to use the application context constructor. This constructor takes
+ multiple Resource locations, as was
+ shown in the previous section.An alternate approach is to use one or more occurrences of the
<import/> element to load bean definitions
@@ -329,7 +300,7 @@
</beans>
In this example, external bean definitions are being loaded from
- 3 files, services.xml,
+ three files, services.xml,
messageSource.xml, and
themeSource.xml. All location paths are considered
relative to the definition file doing the importing, so
@@ -341,28 +312,27 @@
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. The contents of the files
- being imported must be valid XML bean definition files according to
- the Spring Schema or DTD, including the top level
- <beans/> element.
+ being imported, including the top level
+ <beans/> element, must be valid XML bean
+ definitions according to the Spring Schema or DTD.
- It is possible to reference files in parent directories using
- a relative "../" path. However, this is not recommended because it
- creates a dependency on a file that is outside the current
- application. This is in particular not recommended for "classpath:"
- URLs (e.g. "classpath:../services.xml") where the runtime resolution
- process will pick the "nearest" classpath root and then look into
- its parent directory. This is fragile since classpath configuration
- changes may lead to a different directory being picked.
+ It is possible, but not recommended, to reference files in
+ parent directories using a relative "../" path. Doing so creates a
+ dependency on a file that is outside the current application. This
+ is in particular not recommended for "classpath:" URLs (for example,
+ "classpath:../services.xml"), where the runtime resolution process
+ chooses the "nearest" classpath root and then looks into its parent
+ directory. Classpath configuration changes may lead to the choice of
+ a different, incorrect directory.
- Note that you can always use fully qualified resource
- locations instead of relative paths: e.g.
- "file:C:/config/services.xml" or "classpath:/config/services.xml".
- However, be aware that you are coupling your application's
- configuration to specific absolute locations then. It is generally
- preferable to keep an indirection for such absolute locations, e.g.
- through "${...}" placeholders that are resolved against JVM system
- properties at runtime.
+ You can always use fully qualified resource locations instead
+ of relative paths: for example, "file:C:/config/services.xml" or
+ "classpath:/config/services.xml". However, be aware that you are
+ coupling your application's configuration to specific absolute
+ locations. It is generally preferable to keep an indirection for
+ such absolute locations, for example, through "${...}" placeholders
+ that are resolved against JVM system properties at runtime.
@@ -370,15 +340,14 @@
Using the container
- An ApplicationContext is
- essentially nothing more than the interface for an advanced factory
- capable of maintaining a registry of different beans and their
- dependencies. Using the method T getBean(Stringname,
- Class<T> requiredType) you can retrieve instances of
- your beans;
+ The ApplicationContext is the
+ interface for an advanced factory capable of maintaining a registry of
+ different beans and their dependencies. Using the method T
+ getBean(Stringname, Class<T> requiredType) you can
+ retrieve instances of your beans.The ApplicationContext enables you
- to read bean definitions and access them as shown below.
+ to read bean definitions and access them as follows:
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
@@ -390,396 +359,387 @@ PetStoreServiceImpl service = context.getBean("petStore", PetStoreServiceImpl.cl
List userList service.getUsernameList();
- Basically that is all there is to it. Using
- getBean you can retrieve instances of your
- beans; the client-side view of the
- ApplicationContext is simple. The
- ApplicationContext interface has just a
- few other methods for retrieving beans, but ideally your application
- code should never use them... indeed, your application code should have
- no calls to the getBean method at all, and thus
- no dependency on Spring APIs at all. For example, Spring's integration
- with web frameworks provides for dependency injection for various web
- framework classes such as controllers and JSF-managed beans.
+ You use getBean to retrieve instances of
+ your beans. The ApplicationContext
+ interface has a few other methods for retrieving beans, but ideally your
+ application code should never use them. Indeed, your application code
+ should have no calls to the getBean method at
+ all, and thus no dependency on Spring APIs at all. For example, Spring's
+ integration with web frameworks provides for dependency injection for
+ various web framework classes such as controllers and JSF-managed
+ beans.
+
+
+
+
+ The beans
+
+ A Spring IoC container manages one or more
+ beans. These beans are created using the
+ configuration metadata that you supply to the container, typically in the
+ form of XML <bean/> definitions.
+
+ Within the container itself, these bean definitions are represented
+ as BeanDefinition objects, which contain
+ (among other information) the following metadata:
+
+
+
+ A package-qualified class name: typically
+ the actual implementation class of the bean being defined.
+
+
+
+ Bean behavioral configuration elements, which state how the bean
+ should behave in the container (scope, lifecycle callbacks, and so
+ forth).
+
+
+
+ References to other beans that are needed for the bean to do its
+ work; these references are also called
+ collaborators or
+ dependencies.
+
+
+
+ Other configuration settings to set in the newly created object,
+ for example, the number of connections to use in a bean that manages a
+ connection pool, or the size limit of the pool.
+
+
+
+ The preceding concepts translate directly to a set of properties
+ that each bean definition consists of. The following table lists some of
+ these properties, with links to documentation
+
+
+
+ Besides bean definitions that contain information on how to create a
+ specific bean, certain BeanFactory
+ implementations also permit the registration of existing objects that are
+ created outside the factory, by users. The
+ DefaultListableBeanFactory class supports this
+ registration through the registerSingleton(..)
+ method. However, typical applications work solely with beans defined
+ through metadata bean definitions.
+
+
+ Naming beans
+
+
+ Bean naming conventions
+
+ The convention is to use the standard Java convention for
+ instance field names when naming beans. That is, bean names start with
+ a lowercase letter, and are camel-cased from then on. Examples of such
+ names would be (without quotes) 'accountManager',
+ 'accountService', 'userDao',
+ 'loginController', and so forth.
+
+ Naming beans consistently makes your configuration easier to
+ read and understand, and if you are using Spring AOP it helps a lot
+ when applying advice to a set of beans related by name.
+
+
+ Every bean has one or more identifiers. These identifiers must be
+ unique within the container that hosts the bean. A bean usually has only
+ one identifier, but if it requires more than one, the extra ones can be
+ considered aliases.
+
+ When using XML-based configuration metadata, you use the
+ id and/or name attributes to
+ specify the bean identifier(s). The id attribute
+ allows you to specify exactly one id, and because it is a real XML
+ element ID attribute, the XML parser can do some extra validation when
+ other elements reference the id. As such, it is the preferred way to
+ specify a bean identifier. However, the XML specification does limit the
+ characters that are legal in XML ids. This is usually not a constraint,
+ but if you need to use one of these special XML characters, or want to
+ introduce other aliases to the bean, you can also or instead specify
+ them in the name attribute, separated by a comma
+ (,), semicolon (;), or white
+ space.
+
+ You are not required to supply a name for a bean. If no name is
+ supplied explicitly, the container generates a unique name for that
+ bean. The motivations for not supplying a name for a bean will be
+ discussed later (one use case is inner
+ beans).
+
+
+ Aliasing a bean outside the bean definition
+
+ In a bean definition itself, you can supply more than one name
+ for the bean, by using a combination of up to one name specified by
+ the id attribute, and any number of other names in
+ the name attribute. These names can be equivalent
+ aliases to the same bean, and are useful for some situations, such as
+ allowing each component in an application to refer to a common
+ dependency by using a bean name that is specific to that component
+ itself.
+
+ Specifying all aliases where the bean is actually defined is not
+ always adequate, however. It is sometimes desirable to introduce an
+ alias for a bean that is defined elsewhere. In XML-based configuration
+ metadata, you can use of the <alias/> element
+ to accomplish this.
+
+ <alias name="fromName" alias="toName"/>
+
+ In this case, a bean in the same container which is named
+ 'fromName', may also after the use of this alias
+ definition, be referred to as 'toName'.
+
+ For example, component A defines a DataSource bean called
+ componentA-dataSource, in its XML fragment. Component B refers to the
+ DataSource as componentB-dataSource in its XML fragment. The main
+ application, MyApp, defines its own XML fragment, assembles the final
+ application context from all three fragments, refers to the DataSource
+ as myApp-dataSource. To accomplish this scenario, you add to the MyApp
+ XML fragment the following standalone aliases:
+
+ <alias name="componentA-dataSource" alias="componentB-dataSource"/>
+<alias name="componentA-dataSource" alias="myApp-dataSource" />
+
+ Now each component and the main application can refer to the
+ dataSource through a name that is unique and guaranteed not to clash
+ with any other definition (effectively creating a namespace), yet they
+ refer to the same bean.
+
-
- The beans
+
+ Instantiating beans
- A Spring IoC container manages one or more
- beans. These beans are created using the
- configuration metadata that has been supplied to the container
- (typically in the form of XML <bean/>
- definitions).
+
+ Inner class names
- Within the container itself, these bean definitions are
- represented as BeanDefinition objects,
- which contain (among other information) the following metadata:
+ If you want to configure a bean definition for a
+ static inner class, you have to use the
+ binary name of the inner class.
+
+ For example, if you have a class called
+ Foo in the com.example
+ package, and this Foo class has a
+ static inner class called
+ Bar, the value of the
+ 'class' attribute on a bean definition would
+ be...
+
+ com.example.Foo$Bar
+
+ Notice the use of the $ character in the name
+ to separate the inner class name from the outer class name.
+
+
+ A bean definition essentially is a recipe for creating one or more
+ objects. The container looks at the recipe for a named bean when asked,
+ and uses the configuration metadata encapsulated by that bean definition
+ to create (or acquire) an actual object.
+
+ If you use XML-based configuration metadata, you specify the type
+ (or class) of object that is to be instantiated by using the
+ class attribute of the
+ <bean/> element. This class
+ attribute, which internally is a Class property
+ on a BeanDefinition instance, is normally
+ mandatory. (For exceptions, see and .) You use the
+ Class property in one of two ways:
+
+ To specify the class of the bean to be constructed in the
+ common case where the container itself directly creates the bean
+ by calling its constructor reflectively, somewhat equivalent to
+ Java code using the new' operator.
+
+
- a package-qualified class name: typically
- this is the actual implementation class of the bean being
- defined.
-
-
-
- bean behavioral configuration elements, which state how the
- bean should behave in the container (scope, lifecycle callbacks, and
- so forth).
-
-
-
- references to other beans which are needed for the bean to do
- its work; these references are also called
- collaborators or
- dependencies.
-
-
-
- other configuration settings to set in the newly created
- object. An example would be the number of connections to use in a
- bean that manages a connection pool, or the size limit of the
- pool.
+ In the less common case where the container invokes a
+ static, factory method on a
+ class to create the bean, to specify the actual class containing the
+ static factory method that is to be invoked to
+ create the object. The type of the object returned from the
+ invocation of the static factory method may be
+ the same class or another class entirely.
- The concepts listed above directly translate to a set of
- properties that each bean definition consists of. Some of these
- properties are listed below, along with a link to further documentation
- about each of them.
+
+ Instantiation using a constructor
-
- The bean definition
+ When you create a bean by the constructor approach, all normal
+ classes are usable by 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.
-
-
+ Additionally, the Spring IoC container can manage virtually
+ any class you want it to manage; it is not
+ limited to managing true JavaBeans. Most Spring users prefer actual
+ JavaBeans with just a default (no-argument) constructor and
+ appropriate setters and getters modeled after the properties in the
+ container. You can also have more exotic non-bean-style classes in
+ your container. If, for example, you need to use a legacy connection
+ pool that absolutely does not adhere to the JavaBean specification,
+ Spring can manage it as well.
-
+ With XML-based configuration metadata you can specify your bean
+ class as follows:
-
-
- Feature
-
- Explained in...
-
-
-
-
-
- class
-
-
-
-
-
-
- name
-
-
-
-
-
- scope
-
-
-
-
-
-
- constructor arguments
-
-
-
-
-
-
- properties
-
-
-
-
-
-
- autowiring mode
-
-
-
-
-
-
- dependency checking mode
-
-
-
-
-
-
- lazy-initialization mode
-
-
-
-
-
-
- initialization method
-
-
-
-
-
-
- destruction method
-
-
-
-
-
-
-
-
- Besides bean definitions which contain information on how to
- create a specific bean, certain
- BeanFactory implementations also permit
- the registration of existing objects that have been created outside the
- factory (by user code). The
- DefaultListableBeanFactory class supports this
- through the registerSingleton(..) method.
- (Typical applications solely work with beans defined through metadata
- bean definitions though.)
-
-
- Naming beans
-
-
- Bean naming conventions
-
- The convention (at least amongst the Spring development team)
- is to use the standard Java convention for instance field names when
- naming beans. That is, bean names start with a lowercase letter, and
- are camel-cased from then on. Examples of such names would be
- (without quotes) 'accountManager',
- 'accountService', 'userDao',
- 'loginController', and so forth.
-
- Adopting a consistent way of naming your beans will go a long
- way towards making your configuration easier to read and understand;
- adopting such naming standards is not hard to do, and if you are
- using Spring AOP it can pay off handsomely when it comes to applying
- advice to a set of beans related by name.
-
-
- 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 container 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.
-
- When using XML-based configuration metadata, you use the
- 'id' or 'name' attributes to
- specify the bean identifier(s). The 'id' attribute
- allows you to specify exactly one id, and as it is a real XML element
- ID attribute, the XML parser is able to do some extra validation when
- other elements reference the id; as such, it is the preferred way to
- specify a bean id. However, the XML specification does limit the
- characters which are legal in XML IDs. This is usually not a
- constraint, but if you have a need to use one of these special XML
- 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 (,), semicolon
- (;), or whitespace in the 'name'
- attribute.
-
- Please note that you are not required to supply a name for a
- bean. If no name is supplied explicitly, the container will generate a
- unique name for that bean. The motivations for not supplying a name
- for a bean will be discussed later (one use case is inner beans).
-
-
- Aliasing beans
-
- In a bean definition itself, you may supply more than one name
- for the bean, by using a combination of up to one name specified via
- the id attribute, and any number of other names
- via the name attribute. All these names can be
- considered equivalent aliases to the same bean, and are useful for
- some situations, such as allowing each component used in an
- application to refer to a common dependency using a bean name that
- is specific to that component itself.
-
- Having to specify all aliases when the bean is actually
- defined is not always adequate however. It is sometimes desirable to
- introduce an alias for a bean which is defined elsewhere. In
- XML-based configuration metadata this may be accomplished via the
- use of the <alias/> element.
-
- <alias name="fromName" alias="toName"/>
-
- In this case, a bean in the same container which is named
- 'fromName', may also after the use of this alias
- definition, be referred to as 'toName'.
-
- As a concrete example, consider the case where component A
- defines a DataSource bean called componentA-dataSource, in its XML
- fragment. Component B would however like to refer to the DataSource
- as componentB-dataSource in its XML fragment. And the main
- application, MyApp, defines its own XML fragment and assembles the
- final application context from all three fragments, and would like
- to refer to the DataSource as myApp-dataSource. This scenario can be
- easily handled by adding to the MyApp XML fragment the following
- standalone aliases:
-
- <alias name="componentA-dataSource" alias="componentB-dataSource"/>
-<alias name="componentA-dataSource" alias="myApp-dataSource" />
-
- Now each component and the main application can refer to the
- dataSource via a name that is unique and guaranteed not to clash
- with any other definition (effectively there is a namespace), yet
- they refer to the same bean.
-
-
-
-
- Instantiating beans
-
-
- Inner class names
-
- If for whatever reason you want to configure a bean definition
- for a static inner class, you have to use the
- binary name of the inner class.
-
- For example, if you have a class called
- Foo in the com.example
- package, and this Foo class has a
- static inner class called
- Bar, the value of the
- 'class' attribute on a bean definition would
- be...
-
- com.example.Foo$Bar
-
- Notice the use of the $ character in the
- name to separate the inner class name from the outer class
- name.
-
-
- A bean definition essentially is a recipe for creating one or
- more objects. The container looks at the recipe for a named bean when
- asked, and uses the configuration metadata encapsulated by that bean
- definition to create (or acquire) an actual object.
-
- If you are using XML-based configuration metadata, you can
- specify the type (or class) of object that is to be instantiated using
- the 'class' attribute of the
- <bean/> element. This
- 'class' attribute (which internally eventually
- boils down to being a Class property on a
- BeanDefinition instance) is normally
- mandatory (see and for the two exceptions) and
- is used for one of two purposes. The class property specifies the
- class of the bean to be constructed in the common case where the
- container itself directly creates the bean by calling its constructor
- reflectively (somewhat equivalent to Java code using the
- 'new' operator). In the less common case where
- the container invokes a static,
- factory method on a class to create the bean, the
- class property specifies the actual class containing the
- static factory method that is to be invoked to
- create the object (the type of the object returned from the invocation
- of the static factory method may be the same class
- or another class entirely, it doesn't matter).
-
-
- Instantiation using a constructor
-
- When creating a bean using the constructor approach, all
- normal classes are usable by 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.
-
- Additionally, the Spring IoC container 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 container, but it is also
- possible to have more exotic non-bean-style classes in your
- container. If, for example, you need to use a legacy connection pool
- that absolutely does not adhere to the JavaBean specification,
- Spring can manage it as well.
-
- When using XML-based configuration metadata you can specify
- your bean class like so:
-
- <bean id="exampleBean" class="examples.ExampleBean"/>
+ <bean id="exampleBean" class="examples.ExampleBean"/>
<bean name="anotherExample" class="examples.ExampleBeanTwo"/>
- The mechanism for supplying arguments to the constructor (if
- required), or setting properties of the object instance after it has
- been constructed, is
- described shortly.
-
+ The mechanism for supplying arguments to the constructor (if
+ required), or setting properties of the object instance after it has
+ been constructed, is described in Injecting
+ Dependencies.
+
-
- Instantiation using a static factory method
+
+ Instantiation using a static factory method
- 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.
+ When defining a bean that you create with a static factory
+ method, you use the class attribute to specify the
+ class containing the static factory method and an
+ attribute named factory-method to specify the name
+ of the factory method itself. You should be able to call this method
+ (with an optional list of arguments as described later) and return a
+ live object, which from that point on is treated as if it had been
+ created normally through a constructor. One use for such a bean
+ definition is to call static factories in legacy
+ code.
- The following example shows 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, the createInstance() method
- must be a static method.
+ The following example shows a bean definition that specifies
+ that the bean is to be created by calling a factory-method. The
+ definition does not specify the type (class) of the returned object,
+ only the class containing the factory method. In this example, the
+ createInstance() method must be a
+ static method.
- <bean id="exampleBean"
+ <bean id="exampleBean"
class="examples.ExampleBean2"
factory-method="createInstance"/>
- 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.
-
+ 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, is described in Dependencies and
+ configuration in detail.
+
-
- Instantiation using an instance factory method
+
+ Instantiation using an instance factory method
- In a fashion similar to instantiation via a static factory
- method, instantiation using an instance factory method is
- where a non-static method of an existing bean from the container is
- invoked to create a new bean. 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 parent/ancestor) container that contains
- the instance method that is to be invoked to create the object. The
- name of the factory method itself must be set using the
- 'factory-method' attribute.
+ Similar to instantiation through a static factory
+ method, instantiation with an instance factory method involves
+ the invocation of a non-static method of an existing bean from the
+ container to create a new bean. To use this mechanism, leave the
+ class attribute empty, and in the
+ factory-bean attribute, specify the name of a bean
+ in the current (or parent/ancestor) container that contains the
+ instance method that is to be invoked to create the object. Set the
+ name of the factory method itself with the
+ factory-method attribute.
- <!-- the factory bean, which contains a method called createInstance() -->
+ <!-- the factory bean, which contains a method called createInstance() -->
<bean id="serviceLocator" class="com.foo.DefaultServiceLocator">
<!-- inject any dependencies required by this locator bean -->
</bean>
@@ -789,26 +749,25 @@ List userList service.getUsernameList();
factory-bean="serviceLocator"
factory-method="createInstance"/>
- 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 DI.
+ 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
+ through dependency injection (DI).
-
- When the Spring documentation makes mention of a 'factory
- bean', this will be a reference to a bean that is configured in
- the Spring container that will create objects via an instance
- or static
- factory method. When the documentation mentions a
- FactoryBean (notice the
- capitalization) this is a reference to a Spring-specific
- FactoryBean .
-
-
+
+ In Spring documentation, factory bean
+ refers to a bean that is configured in the Spring container that
+ will create objects through an instance
+ or static
+ factory method. By contrast,
+ FactoryBean (notice the
+ capitalization) refers to a Spring-specific
+ FactoryBean .
+
@@ -816,51 +775,46 @@ List userList service.getUsernameList();
Dependencies
- Your typical enterprise application is not made up of a single
- object (or bean in the Spring parlance). Even the simplest of applications
- will no doubt have at least a handful of objects that work together to
- present what the end-user sees as a coherent application. This next
- section explains how you go from defining a number of bean definitions
- that stand-alone, each to themselves, to a fully realized application
- where objects work (or collaborate) together to achieve some goal (usually
- an application that does what the end-user wants).
+ A typical enterprise application does not consist of a single object
+ (or bean in the Spring parlance). Even the simplest application has a few
+ objects that work together to present what the end-user sees as a coherent
+ application. This next section explains how you go from defining a number
+ of bean definitions that stand alone to a fully realized application where
+ objects collaborate to achieve a goal.
- Injecting dependencies
+ Dependency injection and inversion of control
- The basic principle behind Dependency
- Injection (DI) is that objects define their dependencies
- (that is to say 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
+ Dependency injection (DI) is a process
+ whereby objects define their dependencies, that is, the other objects
+ they work with, only through constructor arguments, arguments to a
+ factory method, or properties that are set on the object instance after
+ it is constructed or returned from a factory method. The container then
+ injects those dependencies when it creates the
+ bean. This process is fundamentally the inverse, hence the name
Inversion of Control (IoC), of the bean itself
- being in control of instantiating or locating its dependencies on its
- own using direct construction of classes, or something like the
- Service Locator pattern.
+ controlling the instantiating or locating of its dependencies on its own
+ by using direct construction of classes, or the Service
+ Locator pattern.
- It becomes evident upon usage that code gets much cleaner when the
- DI principle is applied, and reaching a higher grade of decoupling is
- much easier when objects 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 concrete class they are). DI exists
- in two major variants, namely Constructor Injection and
- Setter Injection.
+ Code is cleaner with the DI principle and decoupling is more
+ effective when objects are provided with their dependencies. The object
+ does not look up its dependencies, and does not know the location or
+ class of the dependencies. DI exists in two major variants, Constructor-based dependency
+ injection and Setter-based
+ dependency injection.
- Constructor Injection
+ Constructor-based dependency injection
- Constructor-based DI is effected by
+ You accomplish constructor-based DI by
invoking a constructor with a number of arguments, each representing a
- dependency. 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. Find below an
- example of a class that could only be dependency injected using
+ dependency. Calling a static factory method with
+ specific arguments to construct the bean is nearly equivalent, and
+ this discussion treats arguments to a constructor and to a
+ static factory method similarly. The following
+ example shows a class that can only be dependency-injected by using
constructor injection. Notice that there is nothing
special about this class.
@@ -878,13 +832,13 @@ List userList service.getUsernameList();
}
- Constructor Argument Resolution
+ Constructor argument resolutionConstructor argument resolution matching occurs using the
- argument's type. If there is no potential for ambiguity in the
- constructor arguments of a bean definition, then the order in which
- the constructor arguments are defined in a bean definition is the
- order in which those arguments will be supplied to the appropriate
+ argument's type. If no potential ambiguity exists in the constructor
+ arguments of a bean definition, then the order in which the
+ constructor arguments are defined in a bean definition is the order
+ in which those arguments will be supplied to the appropriate
constructor when it is being instantiated. Consider the following
class:
@@ -897,12 +851,11 @@ public class Foo {
}
}
- There is no potential for ambiguity here (assuming of course
- that Bar and Baz
- classes are not related in an inheritance hierarchy). Thus the
- following configuration will work just fine, and you do not need to
- specify the constructor argument indexes and / or types
- explicitly.
+ No potential ambiguity exists, assuming that
+ Bar and Baz classes
+ are not related by inheritance. Thus the following configuration
+ works fine, and you do not need to specify the constructor argument
+ indexes and/or types explicitly.<beans>
<bean name="foo" class="x.y.Foo">
@@ -939,11 +892,11 @@ public class ExampleBean {
}
- Constructor Argument Type Matching
+ Constructor argument type matching
- The above scenario can use type
- matching with simple types by explicitly specifying the type of
- the constructor argument using the 'type'
+ In the preceding scenario, you can use
+ type matching with simple types by explicitly specifying the type
+ of the constructor argument using the 'type'
attribute. For example:<bean id="exampleBean" class="examples.ExampleBean">
@@ -953,10 +906,10 @@ public class ExampleBean {
- Constructor Argument Index
+ Constructor argument index
- Constructor arguments can have their index specified
- explicitly by use of the index attribute. For
+ You can specify explicitly the index of constructor
+ arguments by using the index attribute. For
example:<bean id="exampleBean" class="examples.ExampleBean">
@@ -964,26 +917,25 @@ public class ExampleBean {
<constructor-arg index="1" value="42"/>
</bean>
- 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.
+ In addition to resolving the ambiguity of multiple simple
+ values, specifying an index resolves ambiguity where a constructor
+ has two arguments of the same type. Note that the index
+ is 0 based.
- Setter Injection
+ Setter-based dependency injection
- Setter-based DI is realized by calling
+ You implement setter-based DI by calling
setter methods on your beans after invoking a no-argument constructor
or no-argument static factory method to instantiate
your bean.
- Find below an example of a class that can only be dependency
- injected using pure setter injection. Note that there is nothing
- special about this class... it is plain old
- Java.
+ The following example shows a class that can only be
+ dependency-injected using pure setter injection. This class is
+ conventional Java.public class SimpleMovieLister {
@@ -999,165 +951,151 @@ public class ExampleBean {
}
- Constructor- or Setter-based DI?
+ Constructor-based or setter-based DI?
- The Spring team generally advocates the usage of setter
- injection, since a large number of constructor arguments can get
- unwieldy, especially when some properties are optional. The presence
- of setter methods also makes objects of that class amenable to being
- re-configured (or re-injected) at some later time (for management
- via JMX MBeans is a particularly
- compelling use case).
+ The Spring team generally advocates setter injection, because
+ large numbers of constructor arguments can get unwieldy, especially
+ when properties are optional. Setter methods also make objects of
+ that class amenable to reconfiguration or re-injection later.
+ Management through JMX MBeans is a
+ compelling use case.
- Constructor-injection is favored by some purists though (and
- with good reason). Supplying all of an object's dependencies means
- that object is never returned to client (calling) code in a less
- than totally initialized state. The flip side is that the object
- becomes less amenable to re-configuration (or re-injection).
+ Some purists favor constructor-based injection. Supplying all
+ object dependencies means that the object is always returned to
+ client (calling) code in a totally initialized state. The
+ disadvantage is that the object becomes less amenable to
+ reconfiguration and re-injection.
- There is no hard and fast rule here. Use whatever type of DI
- makes the most sense for a particular class; sometimes, when dealing
- with third party classes to which you do not have the source, the
- choice will already have been made for you - a legacy class may not
- expose any setter methods, and so constructor injection will be the
- only type of DI available to you.
+ Use the DI that makes the most sense for a particular class.
+ Sometimes, when dealing with third-party classes to which you do not
+ have the source, the choice is made for you. A legacy class may not
+ expose any setter methods, and so constructor injection is the only
+ available DI.The ApplicationContext 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 PropertyEditor instances
- to know how to convert properties from one format to another. However,
- most users of Spring will not be dealing with these classes directly
- (that is programmatically), but rather with an XML definition file
- which will be converted internally into instances of these classes,
- and used to load an entire Spring IoC container instance.
+ constructor- and setter-based DI for the beans it manages. It also
+ supports setter-based DI after some dependencies are already injected
+ through the constructor approach. You configure the dependencies in
+ the form of a BeanDefinition, which you
+ use with PropertyEditor instances to
+ convert properties from one format to another. However, most Spring
+ users do not work with these classes directly (programmatically), but
+ rather with an XML definition file that is then converted internally
+ into instances of these classes, and used to load an entire Spring IoC
+ container instance.
- Bean dependency resolution generally happens as follows:
+ In general, you resolve bean dependency as follows:
- The ApplicationContext is
- created and initialized with a configuration which describes all
- the beans. (Many Spring users use a an
+ Create the ApplicationContext
+ and initialize it with a configuration that describes all the
+ beans. (Many Spring users prefer an
ApplicationContext implementation
- that supports XML format configuration files but Java code and
- annotation based configurations are also supported.)
+ that supports XML format configuration files, but Java code and
+ annotation-based configurations are also supported.)
- Each bean has dependencies expressed in the form of
+ For each bean, create dependencies 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,
+ static-factory method if you are using that instead of a normal
+ constructor. These dependencies are provided to the bean,
when the bean is actually created.
- Each property or constructor argument is either an actual
+ Make each property or constructor argument an actual
definition of the value to set, or a reference to another bean in
the container.
- 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.
+ Make sure that each property or constructor argument that is a
+ value can be converted from its specified format 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.
The Spring container validates the configuration of each bean as
- the container is created, including the validation that properties
- which are bean references are actually referring to valid beans.
- However, the bean properties themselves are not set until the bean
- is actually created. For those beans that are
- singleton-scoped and set to be pre-instantiated (such as singleton
- beans in an ApplicationContext),
- creation happens at the time that the container 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'
+ the container is created, including the validation of whether bean
+ reference properties refer to valid beans. However, the bean
+ properties themselves are not set until the bean is actually
+ created. Beans that are singleton-scoped and set to be
+ pre-instantiated (such as singleton beans in an
+ ApplicationContext) are created when
+ the container is created. Otherwise, the bean is created only when it
+ is requested. Creation of a bean potentially causes a hierarchy of
+ beans to be created, as the bean's dependencies and its dependencies'
dependencies (and so on) are created and assigned.Circular dependencies
- If you are using predominantly constructor injection it is
- possible to write and configure your classes and beans such that an
- unresolvable circular dependency scenario is created.
+ If you use predominantly constructor injection, it is possible
+ to create an unresolvable circular dependency scenario.
- Consider the scenario where you have class A, which requires
- an instance of class B to be provided via constructor injection, and
- class B, which requires an instance of class A to be provided via
- constructor injection. If you configure beans for classes A and B to
- be injected into each other, the Spring IoC container will detect
- this circular reference at runtime, and throw a
+ For example: Class A requires an instance of class B through
+ constructor injection, and class B equires an instance of class A
+ through constructor injection. If you configure beans for classes A
+ and B to be injected into each other, the Spring IoC container
+ detect st this circular reference at runtime, and throws a
BeanCurrentlyInCreationException.
- One possible solution to this issue is to edit the source code
- of some of your classes to be configured via setters instead of via
- constructors. Another solution is not to use constructor injection
- and stick to setter injection only. In other words, while it should
- generally be avoided in all but the rarest of circumstances, it is
- possible to configure circular dependencies with setter
- injection.
+ One possible solution is to edit the source code of some
+ classes to be configured by setters rather than constructors.
+ Alternatively, avoid constructor injection and use setter injection
+ only. In other words, although it is not recommended, you can
+ configure circular dependencies with setter injection.Unlike the typical case (with no circular
- dependencies), a circular dependency between bean A and bean B will
- force one of the beans to be injected into the other prior to being
+ dependencies), a circular dependency between bean A and bean B
+ forces one of the beans to be injected into the other prior to being
fully initialized itself (a classic chicken/egg scenario).
- You can generally trust Spring to do the right thing. It will
- detect misconfiguration issues, such as references to non-existent
- beans and circular dependencies, at container load-time. It will
- actually set properties and resolve dependencies as late as possible,
- which is when the bean is actually created. This means that a Spring
- container 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 implementations
- by default pre-instantiate 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
+ You can generally trust Spring to do the right thing. It detects
+ configuration problems, such as references to non-existent beans and
+ circular dependencies, at container load-time. Spring sets properties
+ and resolves dependencies as late as possible, when the bean is
+ actually created. A Spring container that loads correctly can generate
+ an exception when there is a problem creating a requested bean or one
+ of its dependencies. For example, the bean throws an exception as a
+ result of a missing or invalid property. This potentially delayed
+ visibility of some configuration issues is why
+ ApplicationContext implementations by
+ default pre-instantiate singleton beans. At the cost of some upfront
+ time and memory to create these beans before they are actually needed,
+ you discover 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-initialize (that is not be
- pre-instantiated).
+ later. You can still override this default behavior so that singleton
+ beans will lazy-initialize, rather than be pre-instantiated.
- If no circular dependencies are involved (see sidebar for a
- discussion of circular dependencies), when one or more collaborating
- beans are being injected into a dependent bean, each collaborating
- bean is totally configured prior to being passed
- (via one of the DI flavors) to the dependent bean. This means that if
- bean A has a dependency on bean B, the Spring IoC container will
- totally configure bean B prior to invoking the
- setter method on bean A; you can read 'totally
- configure' to mean that the bean will be instantiated (if
- not a pre-instantiated singleton), all of its dependencies will be
- set, and the relevant lifecycle methods (such as a configured init
- method or the If no circular dependencies exist, when one or more
+ collaborating beans are being injected into a dependent bean, each
+ collaborating bean is totally configured prior to
+ being injected into the dependent bean. This means that if bean A has
+ a dependency on bean B, the Spring IoC container completely configures
+ bean B prior to invoking the setter method on bean A. In other words,
+ the bean is instantiated (if not a pre-instantiated singleton), its
+ dependencies are set, and the relevant lifecycle methods (such as a
+ configured
+ init method or the IntializingBean
- callback method) will all be invoked.
+ callback method) are invoked.
- Some examples
+ Examples of Dependency Injection
- First, an example of using XML-based configuration metadata for
- setter-based DI. Find below a small part of a Spring XML configuration
- file specifying some bean definitions.
+ The following example uses XML-based configuration metadata for
+ setter-based DI. A small part of a Spring XML configuration file
+ specifies some bean definitions:<bean id="exampleBean" class="examples.ExampleBean">
@@ -1191,9 +1129,9 @@ public class ExampleBean {
}
}
- As you can see, setters have been declared to match against the
- properties specified in the XML file. Find below an example of using
- constructor-based DI.
+ In the preceding example, setters are declared to match against
+ the properties specified in the XML file. The following example uses
+ constructor-based DI:<bean id="exampleBean" class="examples.ExampleBean">
@@ -1225,11 +1163,11 @@ public class ExampleBean {
}
}
- 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.
+ The constructor arguments specified in the bean definition will
+ be used as arguments to the constructor of the
+ ExampleBean.
- Now consider a variant of this where instead of using a
+ Now consider a variant of this example, where instead of using a
constructor, Spring is told to call a static
factory method to return an instance of the object:
@@ -1262,17 +1200,17 @@ public class ExampleBean {
}
}
- 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.
- 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 would be used in an essentially identical fashion (aside from
- the use of the factory-bean attribute instead of
- the class attribute), so details will not be
- discussed here.
+ Arguments to the static factory method are
+ supplied via <constructor-arg/> elements,
+ exactly the same as if a constructor had actually been used. The type
+ of the class being returned by the factory method does not have to be
+ of the same type as the class that contains the
+ static factory method, although in this example it
+ is. An instance (non-static) factory method would be used in an
+ essentially identical fashion (aside from the use of the
+ factory-bean attribute instead of the
+ class attribute), so details will not be discussed
+ here.
@@ -1282,14 +1220,14 @@ public class ExampleBean {
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. Spring's
- XML-based configuration metadata supports a number of sub-element types
- within its <property/> and
- <constructor-arg/> elements for just this
+ XML-based configuration metadata supports sub-element types within its
+ <property/> and
+ <constructor-arg/> elements for this
purpose.
- Straight values (primitives, Strings,
- etc.)
+ Straight values (primitives, Strings, and so
+ on)The value attribute of the
<property/> element specifies a property or
@@ -1330,15 +1268,13 @@ public class ExampleBean {
- While the XML is in a more succinct form, there is still an
- issue with authoring any XML based bean definition which is how to
- ensure you do not make any typos for property names. Any typos will be
- discovered at runtime, not design time unless you are using an IDE
+ The preceding XML is more succinct; however, typos are
+ discovered at runtime rather than design time, unless you use an IDE
such as IntelliJ
IDEA or the SpringSource Tool
Suite (STS) that support automatic property completion when
- defining bean definitions. The use of such IDE assistance is highly
+ you create bean definitions. Such IDE assistance is highly
recommended.If you are reading this reference manual straight through from
@@ -1357,22 +1293,21 @@ public class ExampleBean {
</property>
</bean>
- Can you see what is happening? The Spring container is
- converting the text inside the <value/>
- element into a java.util.Properties instance
- using the JavaBeans PropertyEditor
- mechanism. This is a nice shortcut, and is one of a few places where
- the Spring team do favor the use of the nested
- <value/> element over the
- 'value' attribute style.
+ The Spring container converts the text inside the
+ <value/> element into a
+ java.util.Properties instance by using the
+ JavaBeans PropertyEditor mechanism.
+ This is a nice shortcut, and is one of a few places where the Spring
+ team do favor the use of the nested <value/>
+ element over the value attribute style.The idref elementThe idref element is simply an error-proof
way to pass the id of another bean in the
- container (to a <constructor-arg/> or
- <property/> element).
+ container to a <constructor-arg/> or
+ <property/> element.<bean id="theTargetBean" class="..."/>
@@ -1392,38 +1327,37 @@ public class ExampleBean {
<property name="targetName" value="theTargetBean" />
</bean>
- The main reason the first form is preferable to the second is
- that using the idref tag allows the container to
- validate at deployment time that the
- referenced, named bean actually exists. In the second variation, no
- validation is performed on the value that is passed to the
+ The first form is preferable to the second because using the
+ idref tag allows the container to validate
+ at deployment time that the referenced, named
+ bean actually exists. In the second variation, no validation is
+ performed on the value that is passed to the
'targetName' property of the
- 'client' bean. Any typo will only be discovered
- (with most likely fatal results) when the
- 'client' bean is actually instantiated. If the
- 'client' bean is a prototype bean, this typo (and
- the resulting exception) may only be discovered long after the
- container is actually deployed.
+ 'client' bean. Typos are only discovered (with
+ most likely fatal results) when the 'client' bean
+ is actually instantiated. If the 'client' bean is
+ a prototype bean, this
+ typo and the resulting exception may only be discovered long after
+ the container is deployed.
- Additionally, if the bean being referred to is in the same XML
- unit, and the bean name is the bean id, the
+ Additionally, if the referenced bean is in the same XML unit,
+ and the bean name is the bean id, the
'local' attribute may be used, which allows the
- XML parser itself to validate the bean id even earlier, at XML
- document parse time.
+ XML parser itself to validate the bean id earlier, at XML document
+ parse time.<property name="targetName">
<!-- a bean with an id of 'theTargetBean' must exist; otherwise an XML exception will be thrown -->
<idref local="theTargetBean"/>
</property>
- By way of an example, one common place (at least in pre-Spring
- 2.0 configuration) where the <idref/> element brings value is
- in the configuration of AOP
- interceptors in a ProxyFactoryBean
- bean definition. If you use <idref/> elements when specifying
- the interceptor names, there is no chance of inadvertently
- misspelling an interceptor id.
+ A common place (at least in pre-Spring 2.0 configuration)
+ where the <idref/> element brings value is in the
+ configuration of AOP interceptors
+ in a ProxyFactoryBean bean definition. If you
+ use <idref/> elements when specifying the interceptor names,
+ there is no chance of inadvertently misspelling an interceptor
+ id.
@@ -1432,26 +1366,24 @@ public class ExampleBean {
The ref element is the final element allowed
inside a <constructor-arg/> or
- <property/> definition element. It is used to
+ <property/> definition element. You use it to
set the value of the specified property to be a reference to another
- bean managed by the container (a collaborator). 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.
+ bean managed by the container (a collaborator). The referenced bean is
+ a dependency of the bean whose property will be set, and it is
+ initialized on demand as needed before the property is set. (if it is
+ a singleton bean, it may be initialized already by the container.) All
+ references are ultimately just a reference to another object, but you
+ can specify the id/name of the other object in three different ways,
+ which determines how scoping and validation is handled.
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
+ general form, and allows creation of a reference to any bean in the
same container (whether or not in the same XML file), or parent
container. 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.
+ the same as the 'id' attribute of the target bean,
+ or as one of the values in the 'name' attribute of
+ the target bean.
<ref bean="someBean"/>
@@ -1460,24 +1392,24 @@ public class ExampleBean {
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
+ issues 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 as early as possible) if the target bean is in the same
XML file.
<ref local="someBean"/>Specifying the target bean by using the
- 'parent' attribute allows a reference to be created
- to a bean which is in a parent container of the current container. 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 container to the
- current one. The main use of this bean reference variant is when you
- have a hierarchy of containers and you want to wrap an existing bean
- in a parent container with some sort of proxy which will have the same
- name as the parent bean.
+ 'parent' attribute creates a reference to a bean
+ that is in a parent container of the current container. 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 container to the current
+ one. You use this bean reference variant mainly when you have a
+ hierarchy of containers and you want to wrap an existing bean in a
+ parent container with some sort of proxy which will have the same name
+ as the parent bean.
<!-- in the parent context -->
<bean id="accountService" class="com.foo.SimpleAccountService">
@@ -1501,11 +1433,11 @@ public class ExampleBean {
A <bean/> element inside the
<property/> or
- <constructor-arg/> elements is used to define
- a so-called inner bean. An inner bean
- definition does not need to have any id or name defined, and it is
- best not to even specify any id or name value because the id or name
- value simply will be ignored by the container.
+ <constructor-arg/> elements defines a
+ so-called inner bean. An inner bean definition
+ does not need to have any id or name defined, and it is best not to
+ even specify any id or name value because the id or name value simply
+ will be ignored by the container.
<bean id="outer" class="...">
<!-- instead of using a reference to a target bean, simply define the target bean inline -->
@@ -1517,14 +1449,14 @@ public class ExampleBean {
</property>
</bean>
- Note that in the specific case of inner beans, the
+ In the specific case of inner beans, the
'scope' flag and any 'id' or
'name' attribute are effectively ignored. Inner
beans are always anonymous and they are
always scoped as prototypes. Please
- also note that it is not possible to inject inner
- beans into collaborating beans other than the enclosing bean.
+ linkend="beans-factory-scopes-prototype">prototypes. It is
+ not possible to inject inner beans into
+ collaborating beans other than into the enclosing bean.
@@ -1573,44 +1505,39 @@ public class ExampleBean {
</bean>
- The nested element style used this initial example tends to
- become quite verbose. Fortunately, there are attribute shortcuts for
- most elements, which you can read about in .
+ The nested element style shown in the preceding example
+ becomes verbose. Fortunately, attribute shortcuts exist for most
+ elements; see .
- Note that the value of a map key or value, or a set
- value, can also again be any of the following
- elements:
+ The value of a map key or value, or a set value, can
+ also again be any of the following elements:bean | ref | idref | list | set | map | props | value | nullCollection merging
- As of Spring 2.0, the container also supports the
- merging of collections. This allows an
- application developer to define a parent-style
+ As of Spring 2.0, the container supports the
+ merging of collections. An application
+ developer can define a parent-style
<list/>, <map/>,
<set/> or <props/>
element, and have child-style <list/>,
<map/>, <set/> or
<props/> elements inherit and override
- values from the parent collection; that is to say the child
- collection's values will be the result obtained from the merging of
- the elements of the parent and child collections, with the child's
- collection elements overriding values specified in the parent
- collection.
+ values from the parent collection. That is, the child collection's
+ values are the result of merging the elements of the parent and
+ child collections, with the child's collection elements overriding
+ values specified in the parent collection.
- Please note that this section on merging makes use
- of the parent-child bean mechanism. This concept has not yet been
- introduced, so readers unfamiliar with the concept of parent and
- child bean definitions may wish to read the This section on merging discusses the parent-child
+ bean mechanism. Readers unfamiliar with parent and child bean
+ definitions may wish to read the relevant section
before continuing.
- Find below an example of the collection merging
- feature:
+ The following example demonstrates collection merging:<beans>
<bean id="parent" abstract="true" class="example.ComplexObject">
@@ -1636,8 +1563,8 @@ public class ExampleBean {
on the <props/> element of the
adminEmails property of the
child bean definition. When the
- child bean is actually resolved and instantiated
- by the container, the resulting instance will have an
+ child bean is resolved and instantiated by the
+ container, the resulting instance has an
adminEmailsProperties
collection that contains the result of the merging of the child's
adminEmails collection with the parent's
@@ -1647,58 +1574,59 @@ public class ExampleBean {
sales=sales@example.com
support=support@example.co.uk
- Notice how the child Properties
- collection's value set will have inherited all the property elements
- from the parent <props/>. Notice also how
- the child's value for the support value overrides
- the value in the parent collection.
+ The child Properties collection's value
+ set inherits all property elements from the parent
+ <props/>, and the child's value for the
+ support value overrides the value in the parent
+ collection.This merging behavior applies similarly to the
<list/>, <map/>,
and <set/> collection types. In the
specific case of the <list/> element, the
semantics associated with the List collection
- type, that is the notion of an ordered collection
- of values, is maintained; the parent's values will precede all of
- the child list's values. In the case of the
+ type, that is, the notion of an ordered
+ collection of values, is maintained; the parent's values precede all
+ of the child list's values. In the case of the
Map,
Set, and
- Properties collection types, there is
- no notion of ordering and hence no ordering semantics are in effect
- for the collection types that underlie the associated
+ Properties collection types, no
+ ordering exists. Hence no ordering semantics are in effect for the
+ collection types that underlie the associated
Map,
- Set and
+ Set, and
Properties implementation types used
internally by the container.
+
- Finally, some minor notes about the merging support are in
- order; you cannot merge different collection types (e.g. a
+
+ Limitations of collection merging
+
+ You cannot merge different collection types (such as a
Map and a
List), and if you do attempt to do so
- an appropriate Exception will be thrown; and
- in case it is not immediately obvious, the
- 'merge' attribute must be specified on the lower
- level, inherited, child definition; specifying the
+ an appropriate Exception is thrown. The
+ 'merge' attribute must be specified on the lower,
+ inherited, child definition; specifying the
'merge' attribute on a parent collection
- definition is redundant and will not result in the desired merging;
- and (lastly), please note that this merging feature is only
- available in Spring 2.0 (and later versions).
+ definition is redundant and will not result in the desired merging.
+ The merging feature is available only in Spring 2.0 and
+ later.Strongly-typed collection (Java 5+ only)
- If you are using Java 5 or Java 6, you will be aware that it
- is possible to have strongly typed collections (using generic
- types). That is, it is possible to declare a
+ In Java 5 and later, you can use strongly typed collections
+ (using generic types). That is, it is possible to declare a
Collection type such that it can only
contain String elements (for example). If you
- are using Spring to dependency inject a strongly-typed
+ are using Spring to dependency-inject a strongly-typed
Collection into a bean, you can take
advantage of Spring's type-conversion support such that the elements
of your strongly-typed Collection
- instances will be converted to the appropriate type prior to being
- added to the Collection.
+ instances are converted to the appropriate type prior to being added
+ to the Collection.public class Foo {
@@ -1722,36 +1650,33 @@ support=support@example.co.uk
</beans>
When the 'accounts' property of the
- 'foo' bean is being prepared for injection, the
+ 'foo' bean is prepared for injection, the
generics information about the element type of the strongly-typed
- Map<String, Float> is actually
- available via reflection, and so Spring's type conversion
- infrastructure will actually recognize the various value elements as
- being of type Float and so the string values
- '9.99', '2.75', and '3.99'
- will be converted into an actual Float
- type.
+ Map<String, Float> is available by
+ reflection. Thus Spring's type conversion infrastructure recognizes
+ the various value elements as being of type
+ Float, and the string values '9.99',
+ '2.75', and '3.99' are converted into
+ an actual Float type.
- Nulls
+ Null and empty string values
- The <null/> element is used to handle
- null values. Spring treats empty arguments for
- properties and the like as empty Strings. The
- following XML-based configuration metadata snippet results in the
- email property being set to the empty String
- value ("")
+ Spring treats empty arguments for properties and the like as
+ empty Strings. The following XML-based
+ configuration metadata snippet sets the email property to the empty
+ String value ("")<bean class="ExampleBean">
<property name="email" value=""/>
</bean>
- This is equivalent to the following Java code:
- exampleBean.setEmail(""). The special
- <null> element may be used to indicate a
- null value. For example:
+ The preceding example is equivalent to the following Java code:
+ exampleBean.setEmail(""). The
+ <null/> element handles
+ null values. For example:<bean class="ExampleBean">
<property name="email"><null/></property>
@@ -1761,122 +1686,113 @@ support=support@example.co.uk
code: exampleBean.setEmail(null).
-
- Shortcuts and other convenience options for XML-based
- configuration metadata
+
+ XML shortcut with configuration metadata
- The configuration metadata shown so far is a tad verbose. That
- is why there are several options available for you to limit the amount
- of XML you have to write to configure your components. The first is a
- shortcut to define values and references to other beans as part of a
- <property/> definition. The second is
- slightly different format of specifying properties altogether.
+ Several options can limit the amount of XML you have to write to
+ configure your components. The first is a shortcut to define values
+ and references to other beans as part of a
+ <property/> definition. The
+ <property/>,
+ <constructor-arg/>, and
+ <entry/> elements all support a
+ 'value' attribute that you can use instead of
+ embedding a full <value/> element. Therefore,
+ the following:
-
- XML-based configuration metadata shortcuts
-
- The <property/>,
- <constructor-arg/>, and
- <entry/> elements all support a
- 'value' attribute which may be used instead of
- embedding a full <value/> element.
- Therefore, the following:
-
- <property name="myProperty">
+ <property name="myProperty">
<value>hello</value>
</property>
- <constructor-arg>
+ <constructor-arg>
<value>hello</value>
</constructor-arg>
- <entry key="myKey">
+ <entry key="myKey">
<value>hello</value>
</entry>
- are equivalent to:
+ are equivalent to:
- <property name="myProperty" value="hello"/>
+ <property name="myProperty" value="hello"/>
- <constructor-arg value="hello"/>
+ <constructor-arg value="hello"/>
- <entry key="myKey" value="hello"/>
+ <entry key="myKey" value="hello"/>
- The <property/> and
- <constructor-arg/> elements support a
- similar shortcut 'ref' attribute which may be
- used instead of a full nested <ref/>
- element. Therefore, the following:
+ The <property/> and
+ <constructor-arg/> elements support a similar
+ shortcut 'ref' attribute that you can use instead
+ of a full nested <ref/> element. Therefore,
+ the following:
- <property name="myProperty">
+ <property name="myProperty">
<ref bean="myBean">
</property>
- <constructor-arg>
+ <constructor-arg>
<ref bean="myBean">
</constructor-arg>
- ... are equivalent to:
+ ... are equivalent to:
- <property name="myProperty" ref="myBean"/>
+ <property name="myProperty" ref="myBean"/>
- <constructor-arg ref="myBean"/>
+ <constructor-arg ref="myBean"/>
- Note however that the shortcut form is equivalent to a
- <ref bean="xxx"> element; there is no
- shortcut for <ref local="xxx">. To enforce
- a strict local reference, you must use the long form.
+ However, the shortcut form is equivalent to a <ref
+ bean="xxx"> element; no shortcut exists for
+ <ref local="xxx">. To enforce a strict local
+ reference, you must use the long form.
- Finally, the entry element allows a shortcut form to specify
- the key and/or value of the map, in the form of the
- 'key' / 'key-ref' and
- 'value' / 'value-ref'
- attributes. Therefore, the following:
+ Finally, the entry element allows a shortcut form to specify the
+ key and/or value of the map, in the form of the
+ 'key' / 'key-ref' and
+ 'value' / 'value-ref'
+ attributes. Therefore, the following:
- <entry>
+ <entry>
<key>
<ref bean="myKeyBean" />
</key>
<ref bean="myValueBean" />
</entry>
- is equivalent to:
+ is equivalent to:
- <entry key-ref="myKeyBean" value-ref="myValueBean"/>
+ <entry key-ref="myKeyBean" value-ref="myValueBean"/>
- Again, the shortcut form is equivalent to a <ref
- bean="xxx"> element; there is no shortcut for
- <ref local="xxx">.
-
+ Again, the shortcut form is equivalent to a <ref
+ bean="xxx"> element; there is no shortcut for
+ <ref local="xxx">.
+
-
- The p-namespace and how to use it to configure
- properties
+
+ XML shortcut with the p-namespace
- The second option you have to limit the amount of XML you have
- to write to configure your components is to use the special
- "p-namespace". Spring 2.0 and later features support for extensible
- configuration formats using
- namespaces. Those namespaces are all based on an XML Schema
- definition. In fact, the beans configuration
- format that you've been reading about is defined in an XML Schema
- document.
+ You can also decrease the amount of required XML by using the
+ "p-namespace". Spring 2.0 and later features support for extensible
+ configuration formats using
+ namespaces. Those namespaces are all based on an XML Schema
+ definition. In fact, the beans configuration format
+ that you've been reading about is defined in an XML Schema
+ document.
- One special namespace is not defined in an XSD file, and only
- exists in the core of Spring itself. The so-called p-namespace
- doesn't need a schema definition and is an alternative way of
- configuring your properties differently than the way you have seen
- so far. Instead of using nested <property/>
- elements, using the p-namespace you can use attributes as part of
- the bean element that describe your property
- values. The values of the attributes will be taken as the values for
- your properties.
+ One special namespace is not defined in an XSD file, and only
+ exists in the core of Spring itself. The so-called p-namespace doesn't
+ need a schema definition and is an alternative way of configuring your
+ properties differently than the way you have seen so far. Instead of
+ using nested <property/> elements, using the
+ p-namespace you can use attributes as part of the
+ bean element that describe your property values.
+ The values of the attributes will be taken as the values for your
+ properties.
- The following two XML snippets boil down to the same thing in
- the end: the first is using the standard XML format whereas the
- second example is using the p-namespace.
+ The following two XML snippets boil down to the same thing in
+ the end: the first is using the standard XML format whereas the second
+ example is using the p-namespace.
- <beans xmlns="http://www.springframework.org/schema/beans"
+ <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
@@ -1890,17 +1806,16 @@ support=support@example.co.uk
p:email="foo@bar.com"/>
</beans>
- As you can see, we are including an attribute in the
- p-namespace called email in the bean definition - this is telling
- Spring that it should include a property declaration. As previously
- mentioned, the p-namespace doesn't have a schema definition, so the
- name of the attribute can be set to whatever name your property
- has.
+ As you can see, we are including an attribute in the p-namespace
+ called email in the bean definition - this is telling Spring that it
+ should include a property declaration. As previously mentioned, the
+ p-namespace doesn't have a schema definition, so the name of the
+ attribute can be set to whatever name your property has.
- This next example includes two more bean definitions that both
- have a reference to another bean:
+ This next example includes two more bean definitions that both
+ have a reference to another bean:
- <beans xmlns="http://www.springframework.org/schema/beans"
+ <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
@@ -1921,32 +1836,30 @@ support=support@example.co.uk
</bean>
</beans>
- As you can see, this example doesn't only include a property
- value using the p-namespace, but also uses a special format to
- declare property references. Whereas the first bean definition uses
- <property name="spouse" ref="jane"/> to
- create a reference from bean john to bean
- jane, the second bean definition uses
- p:spouse-ref="jane" as an attribute to do the
- exact same thing. In this case 'spouse' is the
- property name whereas the '-ref' part indicates
- that this is not a straight value but rather a reference to another
- bean.
+ As you can see, this example doesn't only include a property
+ value using the p-namespace, but also uses a special format to declare
+ property references. Whereas the first bean definition uses
+ <property name="spouse" ref="jane"/> to
+ create a reference from bean john to bean
+ jane, the second bean definition uses
+ p:spouse-ref="jane" as an attribute to do the exact
+ same thing. In this case 'spouse' is the property
+ name whereas the '-ref' part indicates that this is
+ not a straight value but rather a reference to another bean.
-
- Please note that the p-namespace is not quite as flexible as
- the standard XML format - for example particular, the 'special'
- format used to declare property references will clash with
- properties that end in 'Ref', whereas the
- standard XML format would have no problem there. We recommend that
- you choose carefully which approach you are going to use in your
- projects. You should also communicate this to your team members so
- you won't end up with XML documents using all three approaches at
- the same time. This will prevent people from not understanding the
- application because of different ways of configuring it, and will
- add to the overall consistency of your codebase.
-
-
+
+ Please note that the p-namespace is not quite as flexible as
+ the standard XML format - for example particular, the 'special'
+ format used to declare property references will clash with
+ properties that end in 'Ref', whereas the
+ standard XML format would have no problem there. We recommend that
+ you choose carefully which approach you are going to use in your
+ projects. You should also communicate this to your team members so
+ you won't end up with XML documents using all three approaches at
+ the same time. This will prevent people from not understanding the
+ application because of different ways of configuring it, and will
+ add to the overall consistency of your codebase.
+