diff --git a/spring-framework-reference/src/beans.xml b/spring-framework-reference/src/beans.xml
index 692d36b8c0c..7fbb8e66056 100644
--- a/spring-framework-reference/src/beans.xml
+++ b/spring-framework-reference/src/beans.xml
@@ -76,23 +76,22 @@ The footnote should x-ref to first section in that chapter but I can't find the
Several 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.
-
- While XML has been the traditional format for defining configuration
- metadata you can instruct the container to use Java annotations or code as the
- metadata format by providng a small amount of XML configuration to
- declaratively enable support for these additional metadata
- formats.
+ While XML has been the traditional format
+ for defining configuration metadata you can instruct the container to use
+ Java annotations or code as the metadata format by providng a small amount
+ of XML configuration to declaratively enable support for these additional
+ metadata formats.
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 web.xml file of the
+ application will typically suffice (see ). If you are using the SpringSource Tool
Suite Eclipse-powered development environment or Resource
abstraction, as described in , which
provides a convenient mechanism for reading an InputSream from
- locations defined in a URI syntax. In particular,
- Resource paths are used to construct applications
- contexts as described in .
+ locations defined in a URI syntax. In particular,
+ Resource paths are used to construct
+ applications contexts as described in .
The following example shows the service layer objects
@@ -294,12 +294,11 @@ The footnote should x-ref to first section in that chapter but I can't find the
logical layer or module in your architecture.You can use the application context constructor to load bean
- definitions from all these XML fragments.
- This constructor takes multiple
- Resource locations, as was shown in the
- previous section. Alternatively, use one or more occurrences of the
- <import/> element to load bean definitions
- from another file or files. For example:
+ definitions from all these XML fragments. This constructor takes
+ multiple Resource locations, as was
+ shown in the previous section. Alternatively, use one or more
+ occurrences of the <import/> element to load
+ bean definitions from another file or files. For example:
<beans>
@@ -372,13 +371,14 @@ List userList service.getUsernameList();
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.
+ 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.
@@ -386,9 +386,9 @@ List userList service.getUsernameList();
Bean overviewA Spring IoC container manages one or more
- beans. These beans are created with the
- configuration metadata that you supply to the container, for example, in
- the form of XML <bean/> definitions.
+ beans. These beans are created with the configuration
+ metadata that you supply to the container, for example, in the form of XML
+ <bean/> definitions.
Within the container itself, these bean definitions are represented
as BeanDefinition objects, which contain
@@ -514,13 +514,14 @@ List userList service.getUsernameList();
- In addition to bean definitions that contain information on how to create a
- specific bean, the ApplicationContext
- implementations also permit the registration of existing objects that are
- created outside the container, by users. This is done by accessing the
- ApplicationContext's BeanFactory via the method
- getBeanFactory which returns the BeanFactory
- implementation DefaultListableBeanFactory.
+ In addition to bean definitions that contain information on how to
+ create a specific bean, the
+ ApplicationContext implementations also
+ permit the registration of existing objects that are created outside the
+ container, by users. This is done by accessing the ApplicationContext's
+ BeanFactory via the method getBeanFactory which
+ returns the BeanFactory implementation
+ DefaultListableBeanFactory.
DefaultListableBeanFactory supports this
registration through the methods
registerSingleton(..) and
@@ -550,15 +551,15 @@ List userList service.getUsernameList();
(,), semicolon (;), or white
space.
- You are not required to supply a name or id for a bean. If no
- name or id is supplied explicitly, the container generates a unique name
- for that bean. However, if you want to refer to that bean by name,
- through the use of the ref element or You are not required to supply a name or id for a bean. If no name
+ or id is supplied explicitly, the container generates a unique name for
+ that bean. However, if you want to refer to that bean by name, through
+ the use of the ref element or Service Location style lookup,
- you must provide a name. Motivations for not
- supplying a name are related to using inner beans and autowiring collaborators.
+ you must provide a name. Motivations for not supplying a name are
+ related to using inner beans
+ and autowiring
+ collaborators.Bean naming conventions
@@ -600,7 +601,9 @@ List userList service.getUsernameList();
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, the configuration metadata for subsystem A may
refer to a DataSource via the name 'subsystemA-dataSource. The
configuration metadata for subsystem B may refer to a DataSource via
@@ -684,10 +687,10 @@ List userList service.getUsernameList();
When you create a bean by the constructor approach, all normal
classes are usable by and compatible with Spring. That is, the class
- being developed does not need to implement any specific interfaces or to be
- coded in a specific fashion. Simply specifying the bean class should
- suffice. However, depending on what type of IoC you use for that
- specific bean, you may need a default (empty) constructor.
+ being developed does not need to implement any specific interfaces or
+ to be coded in a specific fashion. Simply specifying the bean class
+ should suffice. However, depending on what type of IoC you use for
+ that specific bean, you may need a default (empty) constructor.The Spring IoC container can manage virtually
any class you want it to manage; it is not
@@ -802,8 +805,10 @@ List userList service.getUsernameList();
objects collaborate to achieve a goal.
- Dependency injection
+ Dependency injection
+
+
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
@@ -957,7 +962,7 @@ public class ExampleBean {
Setter-based DI is accomplished by the
container calling setter methods on your beans after invoking a
no-argument constructor or no-argument static
- factory method to instantiate your bean.
+ factory method to instantiate your bean.The ApplicationContext supports
constructor- and setter-based DI for the beans it manages. It also
@@ -982,7 +987,6 @@ public class ExampleBean {
// business logic that actually 'uses' the injected MovieFinder is omitted...
}
-
The ApplicationContext supports
constructor- and setter-based DI for the beans it manages. It also
supports setter-based DI after some dependencies are already injected
@@ -1031,7 +1035,9 @@ public class ExampleBean {
The container performs bean dependency resolution as
follows:
+
+
The ApplicationContext is
@@ -1320,7 +1326,8 @@ public class ExampleBean {
you create bean definitions. Such IDE assistance is highly
recommended.
- You can also configure a java.util.Properties instance as:
+ You can also configure a
+ java.util.Properties instance as:<bean id="mappings" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
@@ -1404,16 +1411,17 @@ public class ExampleBean {
References to other beans (collaborators)
- The ref element is the final element
- inside a <constructor-arg/> or
- <property/> definition element. Here you
- set the value of the specified property of a bean to be a reference to another
- bean (a collaborator) managed by the container. 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 the collaborator is
- a singleton bean, it may be initialized already by the container.) All
- references are ultimately a reference to another object. Scoping and validation
- depend on whether you specify the id/name of the other object through the
+ The ref element is the final element inside a
+ <constructor-arg/> or
+ <property/> definition element. Here you set
+ the value of the specified property of a bean to be a reference to
+ another bean (a collaborator) managed by the container. 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 the
+ collaborator is a singleton bean, it may be initialized already by the
+ container.) All references are ultimately a reference to another
+ object. Scoping and validation depend on whether you specify the
+ id/name of the other object through the
bean,local, or
parent attributes.
@@ -1858,11 +1866,11 @@ support=support@example.co.ukThe depends-on attribute in the bean
- definition can specify both an initialization time dependency
- and, in the case of singleton beans only,
- a corresponding destroy time dependency. Dependent beans that define
- a depends-on relationship with a given bean are
+ a corresponding destroy time dependency. Dependent beans that define a
+ depends-on relationship with a given bean are
destroyed first, prior to the given bean itself being destroyed. Thus
depends-on can also control shutdown order.
@@ -2153,11 +2161,14 @@ support=support@example.co.uk
Checking for dependencies
+
+
The Spring IoC container can check for unresolved dependencies of
- a bean deployed into the container. When enabling checking for unresolved dependencies
- all JavaBean properties of the bean must have explicit values set for them in the bean
- definition or have their values set via autowiring.
+ a bean deployed into the container. When enabling checking for
+ unresolved dependencies all JavaBean properties of the bean must have
+ explicit values set for them in the bean definition or have their values
+ set via autowiring.This feature is useful when you want to ensure that all properties
(or all properties of a certain type) are set on a bean. A bean class
@@ -2166,9 +2177,9 @@ support=support@example.co.uk
enable dependency checking per bean, just as with the autowiring
functionality. The default is to not check
dependencies. In XML-based configuration metadata, you specify
- dependency checking via the
- dependency-check attribute in a bean definition,
- which can have the following values.
+ dependency checking via the dependency-check
+ attribute in a bean definition, which can have the following
+ values.
Dependency checking modes
@@ -2242,12 +2253,11 @@ support=support@example.co.uk
A solution is to forego some inversion of control. You can make bean A aware of the
container by implementing the
- ApplicationContextAware interface,
- and by making a getBean("B")
- call to the container ask for (a typically new) bean B instance every
- time bean A needs it. The following is an example of this
- approach:
-
+ ApplicationContextAware interface, and by
+ making a getBean("B") call to the
+ container ask for (a typically new) bean B instance every time
+ bean A needs it. The following is an example of this approach:
+
// a class that uses a stateful Command-style class to perform some processing
package fiona.apple;
@@ -2300,8 +2310,8 @@ public class CommandManager implements ApplicationContextAware {
lookup typically involves a prototype bean as in the scenario
described in the preceding section. The Spring Framework implements
this method injection by using bytecode generation from the CGLIB
- library to generate dynamically a subclass that overrides the method.
-
+ library to generate dynamically a subclass that overrides the
+ method.
For this dynamic subclassing to work, you must have the CGLIB
@@ -2643,25 +2653,25 @@ public class ReplacementComputeValue implements MethodReplacer {
<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="false"/>
- In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype
- bean: the container instantiates, configures, and otherwise assembles a
- prototype object, and hands it to the client, with no further record of
- that prototype instance. Thus, although
- initialization lifecycle callback methods are
- called on all objects regardless of scope, in the case of prototypes,
- configured destruction lifecycle callbacks are
- not called. The client code must clean up
- prototype-scoped objects and release expensive resources that the
- prototype bean(s) are holding. To get the Spring container to release
- resources held by prototype-scoped beans, try using a custom bean post-processor, which
- holds a reference to beans that need to be cleaned up.
+ In contrast to the other scopes, Spring does not manage the
+ complete lifecycle of a prototype bean: the container instantiates,
+ configures, and otherwise assembles a prototype object, and hands it to
+ the client, with no further record of that prototype instance. Thus,
+ although initialization lifecycle callback methods
+ are called on all objects regardless of scope, in the case of
+ prototypes, configured destruction lifecycle
+ callbacks are not called. The client code must
+ clean up prototype-scoped objects and release expensive resources that
+ the prototype bean(s) are holding. To get the Spring container to
+ release resources held by prototype-scoped beans, try using a custom
+ bean post-processor,
+ which holds a reference to beans that need to be cleaned up.In some respects, the Spring container's role in regard to a
prototype-scoped bean is a replacement for the Java
- new operator. All lifecycle management past that point
- must be handled by the client. (For details on the lifecycle of a bean
- in the Spring container, see new operator. All lifecycle management past that
+ point must be handled by the client. (For details on the lifecycle of a
+ bean in the Spring container, see .)
@@ -2673,8 +2683,8 @@ public class ReplacementComputeValue implements MethodReplacer {
instantiation time. Thus if you dependency-inject a
prototype-scoped bean into a singleton-scoped bean, a new prototype bean
is instantiated and then dependency-injected into the singleton bean.
- The prototype instance is the sole instance that is ever supplied
- to the singleton-scoped bean.
+ The prototype instance is the sole instance that is ever supplied to the
+ singleton-scoped bean.
However, suppose you want the singleton-scoped bean to acquire a
new instance of the prototype-scoped bean repeatedly at runtime. You
@@ -2947,19 +2957,20 @@ public class ReplacementComputeValue implements MethodReplacer {
userPreferences bean) are also injected only once.
This means that the userManager bean will only
operate on the exact same userPreferences object,
- that is, the one that it was originally injected with.
-
+ that is, the one that it was originally injected with.
+
-
- This is not the behavior you want when injecting
- a shorter-lived scoped bean into a longer-lived scoped bean, for
- example injecting an HTTP Session-scoped collaborating
- bean as a dependency into singleton bean. Rather, you need a single
+
+ This is not the behavior you want when
+ injecting a shorter-lived scoped bean into a longer-lived scoped bean,
+ for example injecting an HTTP
+ Session-scoped collaborating bean as a
+ dependency into singleton bean. Rather, you need a single
userManager object, and for the lifetime of an HTTP
Session, you need a
userPreferences object that is specific to said
- HTTP Session. Thus the container creates
- an object that exposes the exact same public interface as the
+ HTTP Session. Thus the container
+ creates an object that exposes the exact same public interface as the
UserPreferences class (ideally an object that
is aUserPreferences
instance) which can fetch the real
@@ -3054,7 +3065,8 @@ public class ReplacementComputeValue implements MethodReplacer {
Scope implementations that are supplied
with the Spring Framework itself and the Scope
- Javadoc, which explains the methods you need to implement in more detail.
+ Javadoc, which explains the methods you need to implement in
+ more detail.The Scope interface has four methods to get
objects from the scope, remove them from the scope, and allow them to
@@ -3085,7 +3097,8 @@ public class ReplacementComputeValue implements MethodReplacer {
The following method obtains the conversation identifier for the
underlying scope. This identifier is different for each scope. For a
- session scoped implementation, this identifier can be the session identifier.
+ session scoped implementation, this identifier can be the session
+ identifier.String getConversationId()
@@ -3100,9 +3113,13 @@ public class ReplacementComputeValue implements MethodReplacer {
container.
void registerScope(String scopeName, Scope scope);
- This method is declared on the ConfigurableBeanFactory interface,
- which is available on most of the concrete ApplicationContext implementations that ship
- with Spring via the BeanFactory property.
+
+ This method is declared on the
+ ConfigurableBeanFactory interface,
+ which is available on most of the concrete
+ ApplicationContext implementations that
+ ship with Spring via the BeanFactory property.
+
The first argument to the
registerScope(..) method is the unique name
associated with a scope; examples of such names in the Spring
@@ -3178,17 +3195,20 @@ beanFactory.registerScope("thread", customScope
Lifecycle callbacks
+
+
To interact with the container's management of the bean lifecycle,
- you can implement the Spring InitializingBean and
- DisposableBean interfaces. The
- container calls afterPropertiesSet() for the
- former and destroy() for the latter to allow the bean to
- perform certain actions upon initialization and destruction of your beans.
- You can also achieve the same integration with the container without coupling your
- classes to Spring interfaces though the use of init-method and destroy method object definition
- metadata.
+ you can implement the Spring
+ InitializingBean and
+ DisposableBean interfaces. The container
+ calls afterPropertiesSet() for the former and
+ destroy() for the latter to allow the bean to
+ perform certain actions upon initialization and destruction of your
+ beans. You can also achieve the same integration with the container
+ without coupling your classes to Spring interfaces though the use of
+ init-method and destroy method object definition metadata.Internally, the Spring Framework uses
BeanPostProcessor implementations to
@@ -3198,7 +3218,8 @@ beanFactory.registerScope("thread", customScope
BeanPostProcessor yourself. For more
information, see .
- The lifecycle callback interfaces are described in this section.
+ The lifecycle callback interfaces are described in this
+ section.Initialization callbacks
@@ -3207,17 +3228,18 @@ beanFactory.registerScope("thread", customScope
org.springframework.beans.factory.InitializingBean
interface allows a bean to perform initialization work after all
necessary properties on the bean have been set by the container. The
- InitializingBean interface specifies
- a single method:
+ InitializingBean interface specifies a
+ single method:
void afterPropertiesSet() throws Exception;It is recommended that you do not use the
InitializingBean interface because it
- unnecessarily couples the code to Spring. Alternatively, specify a POJO
- initialization method. In the case of XML-based configuration metadata, you use the
- init-method attribute to specify the name of the method that has a void no-argument signature.
- For example, the following definition:
+ unnecessarily couples the code to Spring. Alternatively, specify a
+ POJO initialization method. In the case of XML-based configuration
+ metadata, you use the init-method attribute to
+ specify the name of the method that has a void no-argument signature.
+ For example, the following definition:
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
@@ -3305,11 +3327,11 @@ beanFactory.registerScope("thread", customScope
as an application developer, can write your application classes and
use an initialization callback called init(),
without having to configure an init-method="init"
- attribute with each bean definition. The Spring IoC container calls that method
- when the bean is created (and in accordance with the standard
- lifecycle callback contract described previously). This feature also
- enforces a consistent naming convention for initialization and destroy
- method callbacks.
+ attribute with each bean definition. The Spring IoC container calls
+ that method when the bean is created (and in accordance with the
+ standard lifecycle callback contract described previously). This
+ feature also enforces a consistent naming convention for
+ initialization and destroy method callbacks.
Suppose that your initialization callback methods are named
init() and destroy callback methods are named
@@ -3354,8 +3376,8 @@ beanFactory.registerScope("thread", customScope
Where existing bean classes already have callback methods that
are named at variance with the convention, you can override the
default by specifying (in XML, that is) the method name using the
- init-method and destroy-method attributes on the <bean/> itself.
-
+ init-method and destroy-method attributes on the <bean/>
+ itself.The Spring container guarantees that a configured initialization
callback is called immediately after a bean is supplied with all
@@ -3373,7 +3395,7 @@ beanFactory.registerScope("thread", customScope
- Combining lifecycle mechanisms
+ Combining lifecycle mechanismsAs of Spring 2.5, you have three options for controlling bean
lifecycle behavior: the thread", customScope
once, as explained in the preceding section.
- Multiple lifestyle mechanisms configured for the same bean,
- with different initialization methods, are called as follows:
+ Multiple lifestyle mechanisms configured for the same bean, with
+ different initialization methods, are called as follows:
@@ -3510,9 +3532,9 @@ public final class Boot {
MessageSource. These additional features are described in
- As of Spring 2.5, autowiring is another alternative
- to obtain reference to the ApplicationContext.
- The "traditional" constructor and
+ As of Spring 2.5, autowiring is another alternative to obtain
+ reference to the ApplicationContext. The
+ "traditional" constructor and
byType autowiring modes (as described in ) can provide a dependency of type
ApplicationContext for a constructor
@@ -3529,15 +3551,16 @@ public final class Boot {
When an ApplicationContext creates a class that implements the
org.springframework.beans.factory.BeanNameAware
- interface, the class is provided with a reference to the name defined in
- its associated object definition.
+ interface, the class is provided with a reference to the name defined in
+ its associated object definition.
+
public interface BeanNameAware {
void setBeanName(string name) throws BeansException;
}
-
- The callback is invoked after population of normal bean properties but
- before an initialization callback such as
+
+ The callback is invoked after population of normal bean properties
+ but before an initialization callback such as
InitializingBeans
afterPropertiesSet or a custom init-method.
@@ -3615,13 +3638,13 @@ public final class Boot {
The parent bean cannot be instantiated on its own because it is
incomplete, and it is also explicitly marked as
- abstract. When
- a definition is abstract like this, it is usable only
- as a pure template bean definition that serves as a parent definition for
- child definitions. Trying to use such an abstract
- parent bean on its own, by referring to it as a ref property of another
- bean or doing an explicit getBean() call with the
- parent bean id, returns an error. Similarly, the container's internal
+ abstract. When a definition is
+ abstract like this, it is usable only as a pure
+ template bean definition that serves as a parent definition for child
+ definitions. Trying to use such an abstract parent bean
+ on its own, by referring to it as a ref property of another bean or doing
+ an explicit getBean() call with the parent bean
+ id, returns an error. Similarly, the container's internal
preInstantiateSingletons() method ignores bean
definitions that are defined as abstract.
@@ -3673,11 +3696,10 @@ public final class Boot {
Ordered interfaces.
- BeanPostProcessors operate on bean
- (or object) instances; that is to say, the Spring
- IoC container instantiates a bean instance and
- thenBeanPostProcessor
- interfaces do their work.
+ BeanPostProcessors operate on bean (or
+ object) instances; that is to say, the Spring IoC
+ container instantiates a bean instance and then
+ BeanPostProcessor interfaces do their work.BeanPostProcessor interfaces are scoped
per-container. This is only relevant if you are
@@ -3840,32 +3862,31 @@ org.springframework.scripting.groovy.GroovyMessenger@272961
Using callback interfaces or annotations in conjunction with a
custom BeanPostProcessor implementation
is a common means of extending the Spring IoC container. An example is
- shown in the section entitled which
- demonstrates the usage of a custom
- BeanPostProcessor implementation that
- ships with the Spring distribution which ensures that JavaBean
- properties on beans that are marked with an (arbitrary) annotation are
- actually (configured to be) dependency-injected with a value.
+ shown in the section entitled which demonstrates the
+ usage of a custom BeanPostProcessor
+ implementation that ships with the Spring distribution which ensures
+ that JavaBean properties on beans that are marked with an (arbitrary)
+ annotation are actually (configured to be) dependency-injected with a
+ value.Customizing configuration metadata with
- BeanFactoryPostProcessor interface
-
+ BeanFactoryPostProcessor
+ interface
The next extension point that we will look at is the
org.springframework.beans.factory.config.BeanFactoryPostProcessor.
The semantics of this interface are similar to the
BeanPostProcessor, with one major
- difference: BeanFactoryPostProcessors
- operate on the bean configuration metadata; that
- is, the Spring IoC container allows
- BeanFactoryPostProcessors to read the configuration
- metadata and potentially change it before the
- container instantiates any beans other than BeanFactoryPostProcessors.
-
-
+ difference: BeanFactoryPostProcessors operate on the
+ bean configuration metadata; that is, the Spring
+ IoC container allows BeanFactoryPostProcessors to
+ read the configuration metadata and potentially change it
+ before the container instantiates any beans other
+ than BeanFactoryPostProcessors.
You can configure multiple
BeanFactoryPostProcessors. You can control the order
@@ -3943,15 +3964,17 @@ org.springframework.scripting.groovy.GroovyMessenger@272961
customize environment-specific properties such as database URLs and
passwords, without the complexity or risk of modifying the main XML
definition file or files for the container.
-
+
+
+
Consider the following XML-based configuration metadata
fragment, where a DataSource with
placeholder values is defined. The example shows properties configured
from an external Properties file. At runtime, a
PropertyPlaceholderConfigurer is applied to the
- metadata that will replace some properties of the DataSource.
- The values to replace are specified as 'placeholders' of the form ${property-name}
- which follows the Ant / Log4J / JSP EL style.
+ metadata that will replace some properties of the DataSource. The
+ values to replace are specified as 'placeholders' of the form
+ ${property-name} which follows the Ant / Log4J / JSP EL style.
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:com/foo/jdbc.properties"/>
@@ -3973,11 +3996,13 @@ org.springframework.scripting.groovy.GroovyMessenger@272961
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
- Therefore, the string ${jdbc.username} is replaced at runtime with the
- value 'sa' and similarly for other placeholder values that match to keys in the
- property file. The PropertyPlaceholderConfigurer checks for placeholders in most
- locations of a bean definition and the placeholder prefix and suffix can be customized.
-
+
+ Therefore, the string ${jdbc.username} is replaced at runtime
+ with the value 'sa' and similarly for other placeholder values that
+ match to keys in the property file. The PropertyPlaceholderConfigurer
+ checks for placeholders in most locations of a bean definition and the
+ placeholder prefix and suffix can be customized.
+
With the context namespace introduced in
Spring 2.5, it is possible to configure property placeholders with a
dedicated configuration element. You can provide multiple locations as
@@ -3994,10 +4019,9 @@ jdbc.password=root
systemPropertiesMode property of the configurer. It
has three values that specify configurer behavior: always override,
never override, and override only if the property
- is not found in the properties file specified.
-
-
- Consult the Javadoc for the
+ is not found in the properties file specified.
+
+ Consult the Javadoc for the
PropertyPlaceholderConfigurer for more
information.
@@ -4040,13 +4064,12 @@ jdbc.password=root
Properties file does not have an entry for a
certain bean property, the default context definition is used.
- Note that the bean definition is
- not aware of being overridden, so it is not
- immediately obvious from the XML definition file that the
- override configurer is used. In case of multiple
- PropertyOverrideConfigurer instances that
- define different values for the same bean property, the last one wins,
- due to the overriding mechanism.
+ Note that the bean definition is not aware
+ of being overridden, so it is not immediately obvious from the XML
+ definition file that the override configurer is used. In case of
+ multiple PropertyOverrideConfigurer instances
+ that define different values for the same bean property, the last one
+ wins, due to the overriding mechanism.Properties file configuration lines take this format:
@@ -4095,7 +4118,7 @@ dataSource.url=jdbc:mysql:mydb
FactoryBean Interface
- You implement the
+ You implement the
org.springframework.beans.factory.FactoryBean
interface for objects that are themselves
factories.
@@ -4151,12 +4174,10 @@ dataSource.url=jdbc:mysql:mydb
on the container returns the product of the
FactoryBean, and invoking
getBean("&myBean") returns the
- FactoryBean instance itself.
-
+ FactoryBean instance itself.
-
Annotation-based container configuration
@@ -4370,8 +4391,8 @@ dataSource.url=jdbc:mysql:mydb
non-required constructors can be annotated. In that case, each is
considered among the candidates and Spring uses the
greediest constructor whose dependencies can be
- satisfied, that is the constructor that has the largest number of
- arguments.
+ satisfied, that is the constructor that has the largest number of
+ arguments.
@Autowired's
required attribute is recommended over the
@@ -4767,11 +4788,11 @@ public @interface MovieQualifier {
CustomAutowireConfigurer will also play a
role.
- Regardless of the Java version, when multiple beans qualify as
- autowire candidates, the determination of a "primary"
- candidate is the same: if exactly one bean definition among the
- candidates has a primary attribute set to true,
- it will be selected.
+ Regardless of the Java version, when multiple beans qualify as
+ autowire candidates, the determination of a "primary" candidate is the
+ same: if exactly one bean definition among the candidates has a
+ primary attribute set to true, it
+ will be selected.
@@ -4834,8 +4855,7 @@ public @interface MovieQualifier {
BeanFactory,
ApplicationContext, ResourceLoader,
ApplicationEventPublisher, and
- MessageSource interfaces.
-
+ MessageSource interfaces.
Thus in the following example, the
customerPreferenceDao field first looks for a bean
@@ -4905,6 +4925,7 @@ public @interface MovieQualifier {
Classpath scanning and managed components
+
Most examples in this chapter use XML to specify the configuration
metadata that produces each BeanDefinition
within the Spring container. The previous section (candidate components by scanning the classpath.
- Candidate components are classes that match against a filter criteria
- and have a corresponding bean definition registered with the container.
- This removes the need to use XML to perform bean registration, instead
- you can use annotations (for example @Component), AspectJ type expressions,
- or your own custom filter criteria to select which classes
- will have bean definitions registered with the container.
-
+ candidate components by scanning the classpath.
+ Candidate components are classes that match against a filter criteria and
+ have a corresponding bean definition registered with the container. This
+ removes the need to use XML to perform bean registration, instead you can
+ use annotations (for example @Component), AspectJ type expressions, or
+ your own custom filter criteria to select which classes will have bean
+ definitions registered with the container.Starting with Spring 3.0, many features provided by the
- Automatically detecting classes and registering bean definitions
-
+ Automatically detecting classes and registering bean
+ definitionsSpring can automatically detect stereotyped classes and register
corresponding BeanDefinitions with the
@@ -5001,11 +5021,10 @@ public class JpaMovieFinder implements MovieFinder {
}
To autodetect these classes and register the corresponding beans,
- you need to include the following element in XML, where the
- base-package element is
- a common parent package for the two classes. (Alternatively, you can
- specify a comma-separated list that includes the parent package of each
- class.)
+ you need to include the following element in XML, where the base-package
+ element is a common parent package for the two classes. (Alternatively,
+ you can specify a comma-separated list that includes the parent package
+ of each class.)<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
@@ -5211,12 +5230,12 @@ public class FactoryMethodComponent {
return tb;
}
- @Bean @Scope(StandardScopes.PROTOTYPE)
+ @Bean @Scope(BeanDefinition.SCOPE_SINGLETON)
private TestBean privateInstance() {
return new TestBean("privateInstance", i++);
}
- @Bean @Scope(value = StandardScopes.SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
+ @Bean @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public TestBean requestScopedInstance() {
return new TestBean("requestScopedInstance", 3);
}
@@ -5234,10 +5253,10 @@ public class FactoryMethodComponent {
The @Bean methods in a Spring component are
processed differently than their counterparts inside a Spring
- @Configuration class. The
- difference is that @Component classes are not
- enhanced with CGLIB to intercept the invocation of methods and fields.
- CGLIB proxying is the means by which invoking methods or fields within
+ @Configuration class. The difference is that
+ @Component classes are not enhanced with CGLIB to
+ intercept the invocation of methods and fields. CGLIB proxying is the
+ means by which invoking methods or fields within
@Configuration classes @Bean
methods create bean metadata references to collaborating objects.
Methods are not invoked with normal Java semantics.
@@ -5443,8 +5462,7 @@ public class AppConfig {
You can use the @Bean annotation in
a @Configuration-annotated or in a
- @Component-annotated class.
-
+ @Component-annotated class.Declaring a bean
@@ -5506,11 +5524,11 @@ public class AppConfig {
Receiving lifecycle callbacks
- Beans created in a @Configuration-annotated
- class supports the regular
- lifecycle callbacks. Any classes defined with the @Bean annotation can
- use the @PostConstruct and @PreDestroy annotations from JSR-250, see
- the section on Beans created in a
+ @Configuration-annotated class supports
+ the regular lifecycle callbacks. Any classes defined with the @Bean
+ annotation can use the @PostConstruct and @PreDestroy annotations from
+ JSR-250, see the section on JSR-250
annotations for further details.
@@ -5587,7 +5605,9 @@ public class AppConfig {
Using the @Scope
annotation
-
+
+
+
You can specify that your beans defined with the
@Bean annotation should have a
specific scope. You can use any of the standard scopes specified in
@@ -5706,7 +5726,6 @@ public class AppConfig {
-
Registering a LoadTimeWeaver
@@ -5736,26 +5755,28 @@ public class AppConfig {
Additional Capabilities of the
ApplicationContext
-
+
+
As was discussed in the chapter introduction, the
org.springframework.beans.factory package provides
basic functionality for managing and manipulating beans, including in a
programmatic way. The org.springframework.context
package adds the ApplicationContext
- interface, which implements the BeanFactory interface,
- in addition to extending other interfaces to provide additional functionality
- in a more application framework-oriented style.
- Many people use the ApplicationContext in a
- completely declarative fashion, not even creating it
- programmatically, but instead relying on support classes such as
- ContextLoader to automatically instantiate an
+ interface, which implements the BeanFactory
+ interface, in addition to extending other interfaces to provide additional
+ functionality in a more application framework-oriented
+ style. Many people use the
+ ApplicationContext in a completely
+ declarative fashion, not even creating it programmatically, but instead
+ relying on support classes such as ContextLoader to
+ automatically instantiate an
ApplicationContext as part of the normal
startup process of a J2EE web application.To enhance BeanFactory functionality
- in a more framework-oriented style the context package also provides the
- following functionality:
+ in a more framework-oriented style the context package also provides the
+ following functionality:
@@ -5765,35 +5786,42 @@ public class AppConfig {
Access to resources, such as URLs and
- files, through the ResourceLoader interface.
+ files, through the ResourceLoader
+ interface.
Event publication to beans implementing the
- ApplicationListener interface, through the use
- of the ApplicationEventPublisher interface.
+ ApplicationListener interface, through
+ the use of the
+ ApplicationEventPublisher
+ interface.
Loading of multiple (hierarchical)
contexts, allowing each to be focused on one particular
- layer, such as the web layer of an application, through the
- HierarchicalBeanFactory interface.
+ layer, such as the web layer of an application, through the
+ HierarchicalBeanFactory
+ interface.
Internationalization using
MessageSource
+
+
The ApplicationContext interface
extends an interface called
MessageSource, and therefore provides
- internationalization (i18n) functionality. Spring also provides
- the interface HierarchicalMessageSource, which
- can resolve messages hierarchically. Together these interfaces
- provide the foundation upon which Spring effects message resolution.
- The methods defined on these interfaces include:
+ internationalization (i18n) functionality. Spring also provides the
+ interface HierarchicalMessageSource, which can
+ resolve messages hierarchically. Together these interfaces provide the
+ foundation upon which Spring effects message resolution. The methods
+ defined on these interfaces include:
+
String getMessage(String code, Object[] args,
@@ -5861,12 +5889,11 @@ public class AppConfig {
In the example it is assumed you have three resource bundles
defined in your classpath called format,
- exceptions and windows. Any
- request to resolve a message will be handled in the
- JDK standard way of resolving messages through ResourceBundles.
- For the purposes of the
- example, assume the contents of two of the above resource bundle
- files are...
+ exceptions and windows. Any
+ request to resolve a message will be handled in the JDK standard way of
+ resolving messages through ResourceBundles. For the purposes of the
+ example, assume the contents of two of the above resource bundle files
+ are...# in format.properties
message=Alligators rock!
@@ -5874,12 +5901,11 @@ message=Alligators rock!
# in exceptions.properties
argument.required=The '{0}' argument is required.
- A program to execute the
- MessageSource functionality is shown in the next
- example. Remember that all ApplicationContext
- implementations are also MessageSource
- implementations and so can be cast to the
- MessageSource interface.
+ A program to execute the MessageSource
+ functionality is shown in the next example. Remember that all
+ ApplicationContext implementations are also
+ MessageSource implementations and so can be cast
+ to the MessageSource interface.public static void main(String[] args) {
MessageSource resources = new ClassPathXmlApplicationContext("beans.xml");
@@ -5904,7 +5930,7 @@ argument.required=The '{0}' argument is required.The next example shows arguments passed to the message lookup;
these arguments will be converted into Strings and inserted into
- placeholders in the lookup message.
+ placeholders in the lookup message.
<beans>
@@ -5977,8 +6003,7 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
implements the MessageSourceAware interface is
injected with the application context's
MessageSource when the bean is created and
- configured.
-
+ configured. As an alternative to
ResourceBundleMessageSource, Spring provides
a ReloadableResourceBundleMessageSource
@@ -5991,8 +6016,7 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
(while efficiently caching them in between). Check out the
ReloadableResourceBundleMessageSource javadoc
for details.
-
-
+
@@ -6113,8 +6137,7 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
an ApplicationEventMulticaster
implementation). Furthermore, when a listener receives an event, it
operates inside the transaction context of the publisher, if a
- transaction context is available.
-
+ transaction context is available.
This example shows the bean definitions used to configure an
ApplicationContext:
@@ -6133,7 +6156,8 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
<property name="notificationAddress" value="spam@list.org"/>
</bean>
- This example shows the implementation of the classes refered to in the previous bean definitions:
+ This example shows the implementation of the classes refered to in
+ the previous bean definitions:public class EmailBean implements ApplicationContextAware {
@@ -6172,15 +6196,16 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
}
}
}
+
- When the sendEmail method is called, if there are any emails that
- should be blacklisted, a custom event of the type BlackListEvent
- is published to the application context. The BlackListNotifier class
- which implements the interface ApplicationListener is registered as a
- subscriber to the application context and will receive the BlackListEvent.
- In order to access properties specific to BlackListEvent, the listener must
- perform a downcast.
-
+
+ When the sendEmail method is called, if there are any emails that
+ should be blacklisted, a custom event of the type BlackListEvent is
+ published to the application context. The BlackListNotifier class which
+ implements the interface ApplicationListener is registered as a
+ subscriber to the application context and will receive the
+ BlackListEvent. In order to access properties specific to
+ BlackListEvent, the listener must perform a downcast.
@@ -6194,11 +6219,11 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
An application context is a
ResourceLoader, which can be used to load
Resources. A
- Resource is essentially a
- more feature rich version of the JDK class java.net.URL,
- in fact, the implementations of the Resource
- wrap an instance of java.net.URL where appropriate.
- A Resource can obtain low-level resources
+ Resource is essentially a more feature
+ rich version of the JDK class java.net.URL, in fact,
+ the implementations of the Resource wrap
+ an instance of java.net.URL where appropriate. A
+ Resource can obtain low-level resources
from almost any location in a transparent fashion, including from the
classpath, a filesystem location, anywhere describable with a standard
URL, and some other variations. If the resource location string is a
@@ -6241,8 +6266,8 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
ContextLoader. Of course you can also create
ApplicationContext instances
programmatically by using one of the
- ApplicationContext implementations.
-
+ ApplicationContext
+ implementations.
The ContextLoader mechanism comes in two
flavors: the ContextLoaderListener and the
@@ -6377,7 +6402,7 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
ApplicationContext?
Use an ApplicationContext unless
- you have a good reason for not doing so.
+ you have a good reason for not doing so.Because the ApplicationContext
includes all functionality of the
@@ -6529,11 +6554,11 @@ cfg.postProcessBeanFactory(factory);
is accessed, and remains decoupled from other code, with all ensuing
benefits. EJBs may also use this stub/proxy approach to delegate to a
plain Java implementation object, retrieved from a Spring IoC container.
- While the Spring IoC container itself ideally does not have to be a singleton,
- it may be unrealistic in terms of memory usage or initialization times
- (when using beans in the Spring IoC container such as a Hibernate
- SessionFactory) for each bean to use its
- own, non-singleton Spring IoC container.
+ While the Spring IoC container itself ideally does not have to be a
+ singleton, it may be unrealistic in terms of memory usage or
+ initialization times (when using beans in the Spring IoC container such
+ as a Hibernate SessionFactory) for each
+ bean to use its own, non-singleton Spring IoC container.
Looking up the application context in a service locator style is
sometimes the only option for accessing shared Spring-managed
@@ -6547,6 +6572,4 @@ cfg.postProcessBeanFactory(factory);
team blog entry.
-
-
diff --git a/spring-framework-reference/src/new-in-3.xml b/spring-framework-reference/src/new-in-3.xml
index e21716a5cbb..4399a5320af 100644
--- a/spring-framework-reference/src/new-in-3.xml
+++ b/spring-framework-reference/src/new-in-3.xml
@@ -25,10 +25,10 @@
The entire framework code has been revised to take advantage of Java
5 features like generics, varargs and other language improvements. We have
done our best to still keep the code backwards compatible. We now have
- consistent use of generic Collections and Maps, consistent use of
- generified FactoryBeans, and also consistent resolution of bridge methods
- in the Spring AOP API. Generified ApplicationListeners automatically
- receive specific event types only. All callback interfaces such as
+ consistent use of generic Collections and Maps, consistent use of generic
+ FactoryBeans, and also consistent resolution of bridge methods in the
+ Spring AOP API. Generic ApplicationListeners automatically receive
+ specific event types only. All callback interfaces such as
TransactionCallback and HibernateCallback declare a generic result value
now. Overall, the Spring core codebase is now freshly revised and
optimized for Java 5.