From 35b2a7e6126304ed2734da8c75eb427f162f0914 Mon Sep 17 00:00:00 2001 From: Mark Pollack Date: Thu, 16 Jul 2009 06:41:52 +0000 Subject: [PATCH] Applied and reviewed Beverly's final edits up to section "beans-factory-scopes" --- spring-framework-reference/src/beans.xml | 1130 +++++++++++----------- 1 file changed, 545 insertions(+), 585 deletions(-) diff --git a/spring-framework-reference/src/beans.xml b/spring-framework-reference/src/beans.xml index 889fed31376..81b15d5d213 100644 --- a/spring-framework-reference/src/beans.xml +++ b/spring-framework-reference/src/beans.xml @@ -18,7 +18,7 @@ Spring Framework's IoC container. The BeanFactory interface provides an advanced configuration mechanism capable of managing - objects of any nature. ApplicationContext is a sub-interface of BeanFactory. It adds easier integration with Spring's AOP features; message resource handling @@ -33,9 +33,9 @@ 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 the - ApplicationContext refer to For + more information on using the BeanFactory instead + of the ApplicationContext, refer to . In Spring, the objects that form the backbone of your application @@ -49,7 +49,7 @@
- The Spring IoC container + Container overview The interface org.springframework.context.ApplicationContext @@ -61,9 +61,9 @@ express the objects that compose your application and the rich interdependencies between such objects. - Spring provides implementations of the - ApplicationContext interface for use in standalone - and web applications. In standalone applications it is common to create an + 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 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 you configure the use of the - WebApplicationContext using simple eight (or so) lines of boilerplate J2EE - web descriptor XML in the web.xml file (see web.xml file of the + application will typically suffice (see ). If you are using the SpringSource Tool Suite Eclipse-powered development environment or Spring configuration consists of at least one and typically more - than one bean definition that the container must manage. XML-based - configuration represents beans as <bean/> - elements inside a top-level <beans/> - element. + configuration metadata shows these beans 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 define service layer objects, data @@ -260,7 +259,7 @@ </beans> - In this example, the service layer consists of the class + In the preceding example, the service layer consists of the class PetStoreServiceImpl, and two data access objects of the type SqlMapAccountDao and SqlMapItemDao are based on the iBatis @@ -275,17 +274,17 @@
Composing XML-based configuration metadata - It can be useful to split up bean definitions into multiple XML + It can be useful to have bean definitions span 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. + logical layer or module in your architecture. - An alternate approach is to use one or more occurrences of the + 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). Let's look at a sample: + from another file or files. For example: <beans> @@ -298,32 +297,31 @@ </beans> - In this example, external bean definitions are being loaded from - three files, services.xml, + In the preceding example, external bean definitions are loaded + from three files, services.xml, messageSource.xml, and - themeSource.xml. All location paths are considered - relative to the definition file doing the importing, so - services.xml in this case must be in the same - directory or classpath location as the file doing the importing, while + themeSource.xml. All location paths are relative to + the definition file doing the importing, so + services.xml must be in the same directory or + classpath location as the file doing the importing, while messageSource.xml and themeSource.xml must be in a resources location below the location of the - importing file. As you can see, a leading slash is actually ignored, - but given that these are considered relative paths, it is probably - better form not to use the slash at all. The contents of the files - being imported, including the top level - <beans/> element, must be valid XML bean - definitions according to the Spring Schema or DTD. + importing file. As you can see, a leading slash is ignored, but given + that these paths are relative, it is better form not to use the slash + at all. The contents of the files being imported, including the top + level <beans/> element, must be valid XML + bean definitions according to the Spring Schema or DTD. 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 - selects the "nearest" classpath root and then looks into its parent - directory. Classpath configuration changes may lead to the choice of - a different, incorrect directory. + dependency on a file that is outside the current application. In + particular, this reference is 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. You can always use fully qualified resource locations instead of relative paths: for example, "file:C:/config/services.xml" or @@ -332,8 +330,8 @@ locations. It is generally preferable to keep an indirection for such absolute locations, for example, through property - placeholders, "${...}", that are resolved against JVM system - properties at runtime. + placeholders, "${...}", that are resolved against externally + defined properties at runtime.
@@ -360,10 +358,9 @@ PetStoreServiceImpl service = context.getBean("petStore", PetStoreServiceImpl.cl List userList service.getUsernameList(); - You use the method getBean to retrieve - instances of your beans. The - ApplicationContext interface has a few - other methods for retrieving beans, but ideally your application code + 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 @@ -373,10 +370,10 @@ List userList service.getUsernameList();
- The beans + Bean overview A Spring IoC container manages one or more - beans. These beans are created using the + beans. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions. @@ -410,8 +407,8 @@ List userList service.getUsernameList(); - The preceding concepts translate directly to a set of properties - that each bean definition consists of. The following table lists some of + This metadata translates to a set of properties that make up each + bean definition. The following table lists some of these properties, with links to documentation @@ -424,7 +421,7 @@ List userList service.getUsernameList(); - Feature + Property Explained in... @@ -505,8 +502,8 @@ List userList service.getUsernameList();
- Besides bean definitions that contain information on how to create a - specific bean, The ApplicationContext + 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 @@ -530,7 +527,7 @@ List userList service.getUsernameList(); 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 + In 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 @@ -548,8 +545,8 @@ List userList service.getUsernameList(); 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 in - the ApplicationContext, you must provide a name. Motivations for not + linkend="beans-servicelocation">Service Location style lookup, + you must provide a name. Motivations for not supplying a name are related to using inner beans and autowiring collaborators. @@ -592,8 +589,8 @@ List userList service.getUsernameList(); <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'. + 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 @@ -623,32 +620,32 @@ List userList service.getUsernameList(); 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 + (or class) of object that is to be instantiated in the class attribute of the <bean/> element. This class attribute, which internally is a Class property - on a BeanDefinition instance, is normally + on a BeanDefinition instance, is usually 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. + Typically, to specify the bean class to be constructed in + the 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, 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. + To specify the actual class containing the + static factory method that will be invoked to + create the object, in the less common case where the container + invokes a static, factory + method on a class to create the bean. The object type returned from + the invocation of the static factory method may + be the same class or another class entirely. @@ -674,20 +671,20 @@ List userList service.getUsernameList();
- Instantiation using a constructor + Instantiation with a constructor 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 + 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 are going to use for that specific bean, you may need a default (empty) constructor. - Additionally, the Spring IoC container can manage virtually + 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 + JavaBeans with only 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 @@ -701,31 +698,30 @@ List userList service.getUsernameList(); <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 in For details about the mechanism for supplying arguments to the + constructor (if required) and setting object instance properties after + the object is constructed, see Injecting Dependencies.
- Instantiation using a static factory method + Instantiation with a static factory method 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. + (with optional arguments as described later) and return a live object, + which subsequently is treated as if it had been created 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 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 + The following bean definition specifies that the bean will 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. @@ -733,9 +729,9 @@ List userList service.getUsernameList(); 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, is described in For details about the mechanism for supplying (optional) + arguments to the factory method and setting object instance properties + after the object is returned from the factory, see Dependencies and configuration in detail.
@@ -745,15 +741,14 @@ List userList service.getUsernameList(); Similar to instantiation through a static factory - method, instantiation with an instance factory method involves - the invocation on 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. + method, instantiation with an instance factory method invokes 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() --> <bean id="serviceLocator" class="com.foo.DefaultServiceLocator"> @@ -765,11 +760,11 @@ 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 - through dependency injection (DI). + This approach shows that the factory bean itself can be managed + and configured through dependency injection (DI). See Dependencies and + configuration in detail. In Spring documentation, factory bean @@ -799,17 +794,17 @@ List userList service.getUsernameList(); objects collaborate to achieve a goal.
- Dependency injection and inversion of control + 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 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 + 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 - controlling the instantiating or locating of its dependencies on its own + controlling the instantiating or location of its dependencies on its own by using direct construction of classes, or the Service Locator pattern. @@ -835,7 +830,7 @@ List userList service.getUsernameList(); 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 + example shows a class that can only be dependency-injected with constructor injection. Notice that there is nothing special about this class, it is a POJO that has no dependencies on container specific interfaces, base classes or @@ -861,8 +856,8 @@ List userList service.getUsernameList(); 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 + in which those arguments are supplied to the appropriate constructor + when the bean is being instantiated. Consider the following class: package x.y; @@ -921,7 +916,7 @@ public class ExampleBean { In the preceding scenario, the container can use type matching with simple types if you explicitly specify the type of the constructor argument using - the 'type' attribute. For example: + the type attribute. For example: <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg type="int" value="7500000"/> @@ -932,9 +927,8 @@ public class ExampleBean {
Constructor argument index - You can specify explicitly the index of constructor - arguments by using the index attribute. For - example: + Use the index attribute to specify + explicitly the index of constructor arguments. For example: <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg index="0" value="7500000"/> @@ -1068,7 +1062,7 @@ public class ExampleBean { to create an unresolvable circular dependency scenario. For example: Class A requires an instance of class B through - constructor injection, and class B equires an instance of class A + constructor injection, and class B requires 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 detects this circular reference at runtime, and throws a @@ -1119,7 +1113,7 @@ public class ExampleBean {
- Examples of Dependency Injection + Examples of dependency injection The following example uses XML-based configuration metadata for setter-based DI. A small part of a Spring XML configuration file @@ -1245,10 +1239,10 @@ public class ExampleBean {
Dependencies and configuration in detail - 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 sub-element types within its + As mentioned in the previous section, you can define bean + properties and constructor arguments as references to other managed + beans (collaborators), or as values defined inline. Spring's XML-based + configuration metadata supports sub-element types within its <property/> and <constructor-arg/> elements for this purpose. @@ -1275,7 +1269,7 @@ public class ExampleBean { <property name="password" value="masterkaoli"/> </bean> - You can also use the The following example uses the p-namespace for even more succinct XML configuration. @@ -1305,10 +1299,7 @@ public class ExampleBean { you create bean definitions. Such IDE assistance is highly recommended. - If you are reading this reference manual straight through from - top to bottom (wow!) then we are getting slightly ahead of ourselves - here, but you can also configure a - java.util.Properties instance like so: + You can also configure a java.util.Properties instance as: <bean id="mappings" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> @@ -1333,7 +1324,7 @@ public class ExampleBean { The <literal>idref</literal> element The idref element is simply an error-proof - way to pass the id ((string value - not a + way to pass the id (string value - not a reference)of another bean in the container to a <constructor-arg/> or <property/> element. @@ -1356,37 +1347,36 @@ public class ExampleBean { <property name="targetName" value="theTargetBean" /> </bean> - The first form is preferable to the second because using 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. 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 + targetName property of the + 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 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 earlier, at XML document - parse time. + and the bean name is the bean id, you can use + the local attribute, which allows the 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> - A common place (at least in pre-Spring 2.0 configuration) + A common place (at least in versions earlier than Spring 2.0) 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. + in a ProxyFactoryBean bean definition. Using + <idref/> elements when you specify the interceptor names + prevents you from misspelling an interceptor id.
@@ -1395,28 +1385,29 @@ public class ExampleBean { The ref element is the final element allowed inside a <constructor-arg/> or - <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). The referenced bean is + <property/> definition element. Here you + set the value of the specified property of a bean to 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 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 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. + 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. - Specifying the target bean by using the bean + Specifying the target bean through the bean attribute of the <ref/> tag is the most 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 the 'id' attribute of the target bean, - or as one of the values in the 'name' attribute of + same container or parent container, regardless of whether it is in the + same XML file. The value of the bean attribute may + be 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"/> - Specifying the target bean by using the local + Specifying the target bean through the local attribute leverages the ability of the XML parser to validate XML id references within the same file. The value of the local attribute must be the same as the @@ -1428,17 +1419,16 @@ public class ExampleBean { <ref local="someBean"/> - Specifying the target bean by using the - '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. + Specifying the target bean through the 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 of 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 a + proxy that will have the same name as the parent bean. <!-- in the parent context --> <bean id="accountService" class="com.foo.SimpleAccountService"> @@ -1447,7 +1437,7 @@ public class ExampleBean { <!-- in the child (descendant) context --> <bean id="accountService" <-- notice that the name of this bean is the same as the name of the 'parent' bean + role="bold">same as the name of the parent bean class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target"> <ref parent="accountService"/> <-- notice how we refer to the A <bean/> element inside the <property/> or <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. + so-called inner bean. <bean id="outer" class="..."> <!-- instead of using a reference to a target bean, simply define the target bean inline --> @@ -1478,10 +1465,10 @@ public class ExampleBean { </property> </bean> - 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 + An inner bean definition does not require a defined id or name; + the container ignores these values. It also ignores the + scope flag. Inner beans are + always anonymous and they are always scoped as prototypes. It is not possible to inject inner beans into @@ -1491,15 +1478,14 @@ public class ExampleBean {
Collections - The <list/>, + In the <list/>, <set/>, <map/>, and - <props/> elements allow properties and - arguments of the Java Collection type + <props/> elements, you set the properties and + arguments of the Java Collection types List, Set, Map, and - Properties, respectively, to be defined - and set. + Properties, respectively. <bean id="moreComplexObject" class="example.ComplexObject"> <!-- results in a setAdminEmails(java.util.Properties) call --> @@ -1618,8 +1604,8 @@ support=support@example.co.uk collection types that underlie the associated Map, Set, and - Properties implementation types used - internally by the container. + Properties implementation types that + the container uses internally.
@@ -1629,12 +1615,11 @@ support=support@example.co.uk Map and a List), and if you do attempt to do so 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. - The merging feature is available only in Spring 2.0 and - later. + 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. The merging feature is available + only in Spring 2.0 and later.
@@ -1672,24 +1657,25 @@ support=support@example.co.uk </bean> </beans> - When the 'accounts' property of the - 'foo' bean is prepared for injection, the - generics information about the element type of the strongly-typed + When the accounts property of the + foo bean is prepared for injection, the generics + information about the element type of the strongly-typed 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. + Float, and the string values 9.99, + 2.75, and 3.99 are converted into an + actual Float type.
Null and empty string values - 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 + 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"> @@ -1712,27 +1698,21 @@ support=support@example.co.uk
XML shortcut with the p-namespace - 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. + The p-namespace enables you to use the bean + element's attributes, instead of nested + <property/> elements, to describe your + property values and/or collaborating beans. - 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. + Spring 2.0 and later supports extensible configuration formats + with namespaces, which are based on + an XML Schema definition. The beans configuration + format discussed in this chapter is defined in an XML Schema document. + However, the p-namespace is not defined in an XSD file and exists only + in the core of Spring. - 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 example shows two XML snippets that resolve to the + same result: The first uses standard XML format and the second uses + the p-namespace. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" @@ -1748,11 +1728,11 @@ 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. + The example shows an attribute in the p-namespace called email + in the bean definition. This tells Spring to include a property + declaration. As previously mentioned, the p-namespace not have a + schema definition, so you can set the name of the attribute to the + property name. This next example includes two more bean definitions that both have a reference to another bean: @@ -1778,83 +1758,75 @@ 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 + As you can see, this example includes not only 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 + 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. + The p-namespace is not as flexible as the standard XML format. + For example, the format for declaring property references clashes + with properties that end in Ref, whereas the + standard XML format does not. We recommend that you choose your + approach carefully and communicate this to your team members, to + avoid producing XML documents that use all three approaches at the + same time.
Compound property names - Compound or nested property names are perfectly legal when - setting bean properties, as long as all components of the path except - the final property name are not null. Consider the - following bean definition... + You can use compound or nested property names when you set bean + properties, as long as all components of the path except the final + property name are not null. Consider the following + bean definition. <bean id="foo" class="foo.Bar"> <property name="fred.bob.sammy" value="123" /> </bean> The foo bean has a fred - property which has a bob property, which has a + property, which has a bob property, which has a sammy property, and that final sammy property is being set to the value 123. In order for this to work, the fred property of foo, and the bob property of fred must not be - null be non-null after the bean is constructed, or - a NullPointerException will be - thrown. + null after the bean is constructed, or a + NullPointerException is thrown.
Using <literal>depends-on</literal> - For most situations, the fact that a bean is a dependency of - another is expressed by the fact that one bean is set as a property of - another. This is typically accomplished with the <ref/> - element in XML-based configuration metadata. For the relatively - infrequent situations where dependencies between beans are less direct - (for example, when a static initializer in a class needs to be - triggered, such as database driver registration), the - 'depends-on' attribute may be used to explicitly + If a bean is a dependency of another that usually means that one + bean is set as a property of another. Typically you accomplish this with + the <ref/> + element in XML-based configuration metadata. However, sometimes + dependencies between beans are less direct; for example, a static + initializer in a class needs to be triggered, such as database driver + registration. The depends-on attribute can explicitly force one or more beans to be initialized before the bean using this - element is initialized. Find below an example of using the - 'depends-on' attribute to express a dependency on a - single bean. + element is initialized. The following example uses the + depends-on attribute to express a dependency on a + single bean: <bean id="beanOne" class="ExampleBean" depends-on="manager"/> <bean id="manager" class="ManagerBean" /> - If you need to express a dependency on multiple beans, you can - supply a list of bean names as the value of the - 'depends-on' attribute, with commas, whitespace and - semicolons all valid delimiters, like so: + To express a dependency on multiple beans, supply a list of bean + names as the value of the depends-on attribute, with + commas, whitespace and semicolons, used as valid delimiters: <bean id="beanOne" class="ExampleBean" depends-on="manager,accountDao"> <property name="manager" ref="manager" /> @@ -1864,45 +1836,34 @@ support=support@example.co.uk <bean id="accountDao" class="x.y.jdbc.JdbcAccountDao" /> - The 'depends-on' attribute at the bean - definition level is used not only to specify an initialization time - dependency, but also to specify the corresponding destroy time - dependency (in the case of singleton beans only). - Dependent beans that define a 'depends-on' - relationship with a given bean will be destroyed first - prior to the - given bean itself being destroyed. As a consequence, - 'depends-on' may be used to control shutdown order - too. + The 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 + destroyed first, prior to the given bean itself being destroyed. Thus + depends-on can also control shutdown order.
- Lazily-instantiated beans + Lazy-initialized beans<!--Changed to lazy-initialized from lazily instantiated because attribute is lazy-init, and there was a lot of inconsistency. --> - The default behavior for - ApplicationContext implementations is to - eagerly pre-instantiate all singleton beans at - startup. Pre-instantiation means that an - ApplicationContext will eagerly create - and configure all of its By default, ApplicationContext + implementations eagerly create and configure all singleton beans as part - of its initialization process. Generally this is a good - thing, because it means that any errors in the configuration - or in the surrounding environment will be discovered immediately (as - opposed to possibly hours or even days down the line). + of the initialization process. Generally, this pre-instantiation is + desirable, because errors in the configuration or surrounding + environment are discovered immediately, as opposed to hours or even days + later. When this behavior is not desirable, you can + prevent pre-instantiation of a singleton bean by marking the bean + definition as lazy-initialized. A lazy-initialized bean tells the IoC + container to create a bean instance when it is first requested, rather + than at startup. - However, there are times when this behavior is - not what is wanted. If you do not want a singleton - bean to be pre-instantiated when using an - ApplicationContext, you can selectively - control this by marking a bean definition as lazy-initialized. A - lazily-initialized bean indicates to the IoC container whether or not a - bean instance should be created at startup or when it is first - requested. - - When configuring beans via XML, this lazy loading is controlled by - the 'lazy-init' attribute on the + In XML, this behavior is controlled by the + lazy-init attribute on the <bean/> element; for example: <bean id="lazy" class="com.foo.ExpensiveToCreateBean" <bean name="not.lazy" class="com.foo.AnotherBean"/> - When the above configuration is consumed by an + When the preceding configuration is consumed by an ApplicationContext, the bean named - 'lazy' will not be eagerly - pre-instantiated when the + lazy is not eagerly pre-instantiated when the ApplicationContext is starting up, - whereas the 'not.lazy' bean will be eagerly + whereas the not.lazy bean is eagerly pre-instantiated. - One thing to understand about lazy-initialization is that even - though a bean definition may be marked up as being lazy-initialized, if - the lazy-initialized bean is the dependency of a singleton bean that is - not lazy-initialized, when the - ApplicationContext is eagerly - pre-instantiating the singleton, it will have to satisfy all of the - singletons dependencies, one of which will be the lazy-initialized bean! - So don't be confused if the IoC container creates one of the beans that - you have explicitly configured as lazy-initialized at startup; all that - means is that the lazy-initialized bean is being injected into a - non-lazy-initialized singleton bean elsewhere. + However, when a lazy-initialized bean is a dependency of a + singleton bean that is not lazy-initialized, the + ApplicationContext creates the + lazy-initialized bean at startup, because it must satisfy the + singleton's dependencies. The lazy-initialized bean is injected into a + singleton bean elsewhere that is not lazy-initialized. - It is also possible to control lazy-initialization at the - container level by using the 'default-lazy-init' - attribute on the <beans/> element; for - example: + You can also control lazy-initialization at the container level by + using the default-lazy-init attribute on the + <beans/> element; for example: <beans default-lazy-init="true"> <!-- no beans will be pre-instantiated... --> @@ -1943,24 +1897,40 @@ support=support@example.co.uk
Autowiring collaborators - The Spring container is able to autowire - relationships between collaborating beans. This means that it is - possible to automatically let Spring resolve collaborators (other beans) - for your bean by inspecting the contents of the - ApplicationContext. The autowiring - functionality has five modes. Autowiring is specified - per bean and can thus be enabled for some beans, - while other beans will not be autowired. Using autowiring, it is - possible to reduce or eliminate the need to specify properties or - constructor arguments, thus saving a significant amount of typing. - - See the section entitled - When using XML-based configuration metadata, the autowire - mode for a bean definition is specified by using the - autowire attribute of the - <bean/> element. The following values are - allowed: + + + The Spring container can autowire + relationships between collaborating beans. You can allow Spring to + resolve collaborators (other beans) automatically for your bean by + inspecting the contents of the + ApplicationContext. Autowiring has the + following advantages: + + + + Autowiring can significantly reduce the need to specify + properties or constructor arguments. (Other mechanisms such as a + bean template discussed elsewhere in this + chapter are also valuable in this regard.) + + + + Autowiring can update a configuration as your objects + evolve. For example, if you need to add a dependency to a class, + that dependency can be satisfied automatically your needing to + modify the configuration. Thus autowiring can be especially useful + during development, without negating the option of switching to + explicit wiring when the code base becomes more stable. + + + See + When using XML-based configuration metadata, you specify + autowire mode for a bean definition with the autowire + attribute of the <bean/> element. The + autowiring functionality has five modes. You specify autowiring + per bean and thus can choose which ones to + autowire. Autowiring modes @@ -1982,37 +1952,36 @@ support=support@example.co.uk no - No autowiring at all. Bean references must be - defined via a ref element. This is the - default, and changing this is discouraged for larger - deployments, since explicitly specifying collaborators gives - greater control and clarity. To some extent, it is a form of - documentation about the structure of a system. + (Default) No autowiring. Bean references must be + defined via a ref element. Changing the + default setting is not recommended for larger deployments, + because specifying collaborators explicitly gives greater + control and clarity. To some extent, it documents the structure + of a system. byName - Autowiring by property name. This option will - inspect the container and look for a bean named exactly the same - as the property which needs to be autowired. For example, if you - have a bean definition which is set to autowire by name, and it - contains a master property (that is, it has - a setMaster(..) method), Spring will look - for a bean definition named master, and use - it to set the property. + Autowiring by property name. Spring looks for a + bean with the same name as the property that needs to be + autowired. For example, if a bean definition is set to autowire + by name, and it contains a master property + (that is, it has a setMaster(..) method), + Spring looks for a bean definition named + master, and uses it to set the + property. byType - Allows a property to be autowired if there is - exactly one bean of the property type in the container. If there - is more than one, a fatal exception is thrown, and this - indicates that you may not use byType - autowiring for that bean. If there are no matching beans, - nothing happens; the property is not set. If this is not - desirable, setting the + Allows a property to be autowired if exactly one + bean of the property type exists in the container. If more than + one exists, a fatal exception is thrown, which indicates that + you may not use byType autowiring for that + bean. If there are no matching beans, nothing happens; the + property is not set. If this is not desirable, setting the dependency-check="objects" attribute value specifies that an error should be thrown in this case. @@ -2021,8 +1990,8 @@ support=support@example.co.uk constructor - This is analogous to byType, - but applies to constructor arguments. If there isn't exactly one + Analogous to byType, but + applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. @@ -2033,153 +2002,152 @@ support=support@example.co.uk Chooses constructor or byType through introspection of the bean class. If a default constructor is found, the - byType mode will be applied. + byType mode is applied.
- Note that explicit dependencies in property and - constructor-arg settings - always override autowiring. Please also - note that it is not currently possible to autowire so-called - simple properties such as primitives, - Strings, and Classes (and - arrays of such simple properties). (This is by-design and should be - considered a feature.) When using either the - byType or constructor - autowiring mode, it is possible to wire arrays and typed-collections. In - such cases all autowire candidates within the - container that match the expected type will be provided to satisfy the - dependency. Strongly-typed Maps can even be autowired if the expected - key type is String. An autowired Map's values - will consist of all bean instances that match the expected type, and the - Map's keys will contain the corresponding bean names. + With byType or + constructor autowiring mode, you can wire arrays + and typed-collections. In such cases all autowire + candidates within the container that match the expected type are + provided to satisfy the dependency. You can autowire strongly-typed Maps + if the expected key type is String. An autowired + Maps values will consist of all bean instances that match the expected + type, and the Maps keys will contain the corresponding bean + names. - Autowire behavior can be combined with dependency checking, which - will be performed after all autowiring has been completed. + You can combine autowire behavior with dependency checking, which + is performed after autowiring completes. - It is important to understand the various advantages and - disadvantages of autowiring. Some advantages of autowiring - include: +
+ Limitations and disadvantages of autowiring - - - Autowiring can significantly reduce the volume of - configuration required. However, mechanisms such as the use of a - bean template (discussed elsewhere in this - chapter) are also valuable in this regard. - + Autowiring works best when it is used consistently across a + project. If autowiring is not used in general, it might be confusing + to developers to use it to wire only one or two bean + definitions. - - Autowiring can cause configuration to keep itself up to date - as your objects evolve. For example, if you need to add an - additional dependency to a class, that dependency can be satisfied - automatically without the need to modify configuration. Thus there - may be a strong case for autowiring during development, without - ruling out the option of switching to explicit wiring when the code - base becomes more stable. - - + Consider the limitations and disadvantages of autowiring: - Some disadvantages of autowiring: + + + Explicit dependencies in property and + constructor-arg settings always override + autowiring. You cannot autowire so-called + simple properties such as primitives, + Strings, and Classes + (and arrays of such simple properties). This limitation is + by-design. + + - - - Autowiring is more magical than explicit wiring. Although, as - noted in the above table, Spring is careful to avoid guessing in - case of ambiguity which might have unexpected results, the - relationships between your Spring-managed objects are no longer - documented explicitly. - + + + Autowiring is less exact than explicit wiring. Although, as + noted in the above table, Spring is careful to avoid guessing in + case of ambiguity that might have unexpected results, the + relationships between your Spring-managed objects are no longer + documented explicitly. + - - Wiring information may not be available to tools that may - generate documentation from a Spring container. - - + + Wiring information may not be available to tools that may + generate documentation from a Spring container. + + - Another issue to consider when autowiring by type is that multiple - bean definitions within the container may match the type specified by - the setter method or constructor argument to be autowired. For arrays, - collections, or Maps, this is not necessarily a problem. However for - dependencies that expect a single value, this ambiguity will not be - arbitrarily resolved. Instead, if no unique bean definition is - available, an Exception will be thrown. You do have several options when - confronted with this scenario. First, you may abandon autowiring in - favor of explicit wiring. Second, you may designate that certain bean - definitions are never to be considered as candidates by setting their - 'autowire-candidate' attributes to - 'false' as described in the next section. Third, you - may designate a single bean definition as the - primary candidate by setting the - 'primary' attribute of its - <bean/> element to 'true'. - Finally, if you are using at least Java 5, you may be interested in - exploring the more fine-grained control available with annotation-based - configuration as described in the section entitled . + + + Multiple bean definitions within the container may match the + type specified by the setter method or constructor argument to be + autowired. For arrays, collections, or Maps, this is not + necessarily a problem. However for dependencies that expect a + single value, this ambiguity is not arbitrarily resolved. If no + unique bean definition is available, an exception is + thrown. + + - When deciding whether to use autowiring, there is no wrong or - right answer in all cases. A degree of consistency across a project is - best though; for example, if autowiring is not used in general, it might - be confusing to developers to use it just to wire one or two bean - definitions. + In the latter scenario, you have several options: + + + + Abandon autowiring in favor of explicit wiring. + + + + Avoid autowiring for a bean definition by setting its + autowire-candidate attributes to + false as described in the next section. + + + + Designate a single bean definition as the + primary candidate by setting the + primary attribute of its + <bean/> element to + true. + + + + If you are using Java 5 or later, implement the more + fine-grained control available with annotation-based + configuration, as described in . + + +
- Excluding a bean from being available for autowiring + Excluding a bean from autowiring - You can also (on a per-bean basis) totally exclude a bean from - being an autowire candidate. When configuring beans using Spring's XML - format, the 'autowire-candidate' attribute of the - <bean/> element can be set to - 'false'; this has the effect of making the - container totally exclude that specific bean definition from being - available to the autowiring infrastructure. + On a per-bean basis, you can exclude a bean from autowiring. In + Spring's XML format, set the autowire-candidate + attribute of the <bean/> element to + false; the container makes that specific bean + definition unavailable to the autowiring infrastructure. - Another option is to limit autowire candidates based on - pattern-matching against bean names. The top-level - <beans/> element accepts one or more patterns - within its 'default-autowire-candidates' attribute. - For example, to limit autowire candidate status to any bean whose name - ends with 'Repository', provide a value of - '*Repository'. To provide multiple patterns, define them in a - comma-separated list. Note that an explicit value of - 'true' or 'false' for a bean - definition's 'autowire-candidate' attribute always - takes precedence, and for such beans, the pattern matching rules will - not apply. + You can also limit autowire candidates based on pattern-matching + against bean names. The top-level <beans/> + element accepts one or more patterns within its + default-autowire-candidates attribute. For example, + to limit autowire candidate status to any bean whose name ends with + Repository, provide a value of *Repository. To + provide multiple patterns, define them in a comma-separated list. An + explicit value of true or false + for a bean definitions autowire-candidate attribute + always takes precedence, and for such beans, the pattern matching + rules do not apply. - These techniques can be useful when you have one or more beans - that you absolutely never ever want to have injected into other beans - via autowiring. It does not mean that an excluded bean cannot itself - be configured using autowiring... it can, it is rather that it itself - will not be considered as a candidate for autowiring other - beans. + These techniques are useful for beans that you never want to be + injected into other beans by autowiring. It does not mean that an + excluded bean cannot itself be configured using autowiring. Rather, + the bean itself is not a candidate for autowiring other beans. + +
Checking for dependencies - The Spring IoC container also has the ability to check for the - existence of unresolved dependencies of a bean deployed into the - container. These are JavaBeans properties of the bean, which do not have - actual values set for them in the bean definition, or alternately - provided automatically by the autowiring feature. + 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. - This feature is sometimes useful when you want to ensure that all - properties (or all properties of a certain type) are set on a bean. Of - course, in many cases a bean class will have default values for many - properties, or some properties do not apply to all usage scenarios, so - this feature is of limited use. Dependency checking can also be enabled - and disabled per bean, just as with the autowiring functionality. The - default is to not check dependencies. Dependency - checking can be handled in several different modes. When using XML-based - configuration metadata, this is specified via the - 'dependency-check' attribute in a bean definition, - which may have the following values. + 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 + often has default values for many properties, or some properties do not + apply to all usage scenarios, so this feature is of limited use. You can + 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 modes @@ -2201,66 +2169,65 @@ support=support@example.co.uk none - No dependency checking. Properties of the bean - which have no value specified for them are simply not + (Default) No dependency checking. Properties of the + bean that have no value specified for them are not set. simple - Dependency checking is performed for primitive - types and collections (everything except - collaborators). + Dependency checking for primitive types and + collections (everything except collaborators). object - Dependency checking is performed for collaborators + Dependency checking for collaborators only. all - Dependency checking is done for collaborators, - primitive types and collections. + Dependency checking for collaborators, primitive + types, and collections.
- If you are using Java 5 and thus have access to source-level - annotations, you may find the section entitled If you use Java 5 and thus have access to source-level + annotations, you may find to be of interest.
- Method Injection + Method injection - For most application scenarios, the majority of the beans in the - container will be singletons. When a + In most application scenarios, most beans in the container are + singletons. When a singleton bean needs to collaborate with another singleton bean, or a non-singleton bean needs to collaborate with another non-singleton bean, - the typical and common approach of handling this dependency by defining - one bean to be a property of the other is quite adequate. There is a - problem when the bean lifecycles are different. Consider a singleton - bean A which needs to use a non-singleton (prototype) bean B, perhaps on - each method invocation on A. The container will only create the - singleton bean A once, and thus only get the opportunity to set the - properties once. There is no opportunity for the container to provide - bean A with a new instance of bean B every time one is needed. + you typically handle the dependency by defining one bean as a property + of the other. A problem arises when the bean lifecycles are different. + Suppose singleton bean A needs to use non-singleton (prototype) bean B, + perhaps on each method invocation on A. The container only creates the + singleton bean A once, and thus only gets one opportunity to set the + properties. The container cannot provide bean A with a new instance of + bean B every time one is needed. - One solution to this issue is to forego some inversion of control. - Bean A can be made - aware of the container by implementing the + A solution is to forego some inversion of control. You can make bean A aware of the + container by implementing the ApplicationContextFactoryAware interface, - and use programmatic means - to ask the container via a getBean("B") call - for (a typically new) bean B instance every time it needs it. Find below - an admittedly somewhat contrived example of this approach: + 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 a contrived example of this + approach: + + // a class that uses a stateful Command-style class to perform some processing package fiona.apple; @@ -2292,42 +2259,49 @@ public class CommandManager implements ApplicationContextAware { } } - The above example is generally not a desirable solution since the - business code is then aware of and coupled to the Spring Framework. - Method Injection, a somewhat advanced feature of the Spring IoC - container, allows this use case to be handled in a clean fashion. + The preceding is not desirable, because the business code is aware + of and coupled to the Spring Framework. Method Injection, a somewhat + advanced feature of the Spring IoC container, allows this use case to be + handled in a clean fashion. + + + You can read more about the motivation for Method Injection in + this blog + entry. +
Lookup method injection - - Isn't this Method Injection... + - ... somewhat like Tapestry 4.0's pages, where folks wrote - abstract properties that Tapestry would override - at runtime with implementations that did stuff? It sure is (well, - somewhat). + Lookup method injection is the ability of the container to + override methods on container managed beans, to + return the lookup result for another named bean in the container. The + 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. + - You can read more about the motivation for Method Injection in - this blog - entry. - + + For this dynamic subclassing to work, you must have the CGLIB + jar(s) in your classpath. The class that the Spring container will + subclass cannot be final, and the method to be + overridden cannot be final either. Also, testing + a class that has an abstract method requires you + to subclass the class yourself and to supply a stub implementation + of the abstract method. Finally, objects that + have been the target of method injection cannot be + serialized. + - Lookup method injection refers to the ability of the container - to override methods on container managed beans, - to return the result of looking up another named bean in the - container. The lookup will typically be of a prototype bean as in the - scenario described above. The Spring Framework implements this method - injection by dynamically generating a subclass overriding the method, - using bytecode generation via the CGLIB library. - - So if you look at the code from previous code snippet (the - CommandManager class), the Spring container is - going to dynamically override the implementation of the + Looking at the CommandManager class in + the previous code snippet, you see that the Spring container will + dynamically override the implementation of the createCommand() method. Your - CommandManager class is not going to have any - Spring dependencies, as can be seen in this reworked example - below: + CommandManager class will not have any Spring + dependencies, as can be seen in the reworked example: package fiona.apple; @@ -2348,16 +2322,15 @@ public abstract class CommandManager { } In the client class containing the method to be injected (the - CommandManager in this case), the method that - is to be 'injected' must have a signature of the following - form: + CommandManager in this case), the method to be + injected requires a signature of the following form: <public|protected> [abstract] <return-type> theMethodName(no-arguments); If the method is abstract, the - dynamically-generated subclass will implement the method. Otherwise, - the dynamically-generated subclass will override the concrete method - defined in the original class. Let's look at an example: + dynamically-generated subclass implements the method. Otherwise, the + dynamically-generated subclass overrides the concrete method defined + in the original class. For example: <!-- a stateful bean deployed as a prototype (non-singleton) --> <bean id="command" class="fiona.apple.AsyncCommand" scope="prototype"> @@ -2369,26 +2342,14 @@ public abstract class CommandManager { <lookup-method name="createCommand" bean="command"/> </bean> - The bean identified as commandManager will - call its own method createCommand() whenever - it needs a new instance of the command bean. It - is important to note that the person deploying the beans must be - careful to deploy the command bean as a prototype - (if that is actually what is needed). If it is deployed as a singleton, the same - instance of the command bean will be returned each - time! - - Please be aware that in order for this dynamic subclassing to - work, you will need to have the CGLIB jar(s) on your classpath. - Additionally, the class that the Spring container is going to subclass - cannot be final, and the method that is being - overridden cannot be final either. Also, testing a - class that has an abstract method can be somewhat - odd in that you will have to subclass the class yourself and supply a - stub implementation of the abstract method. - Finally, objects that have been the target of method injection cannot - be serialized. + The bean identified as commandManager calls + its own method createCommand() whenever it + needs a new instance of the command bean. You + must be careful to deploy the command bean as a + prototype, if that is actually what is needed. If it is deployed as a + singleton, the + same instance of the command bean is returned each + time. The interested reader may also find the @@ -2397,11 +2358,11 @@ public abstract class CommandManager { to be of use. The approach used in ServiceLocatorFactoryBean is similar to that of another utility class, ObjectFactoryCreatingFactoryBean, but it - allows you to specify your own lookup interface as opposed to having - to use a Spring-specific lookup interface. Consult the JavaDocs for - these classes as well as this blog - entry for a additional information + entry for additional information ServiceLocatorFactoryBean.
@@ -2409,17 +2370,16 @@ public abstract class CommandManager {
Arbitrary method replacement - A less commonly useful form of method injection than Lookup - Method Injection is the ability to replace arbitrary methods in a - managed bean with another method implementation. Users may safely skip - the rest of this section (which describes this somewhat advanced - feature), until this functionality is actually needed. + A less useful form of method injection than lookup method + Injection is the ability to replace arbitrary methods in a managed + bean with another method implementation. Users may safely skip the + rest of this section until the functionality is actually needed. - When using XML-based configuration metadata, the - replaced-method element may be used to replace an - existing method implementation with another, for a deployed bean. - Consider the following class, with a method computeValue, which we - want to override: + With XML-based configuration metadata, you can use the + replaced-method element to replace an existing + method implementation with another, for a deployed bean. Consider the + following class, with a method computeValue, which we want to + override: public class MyValueCalculator { @@ -2461,23 +2421,23 @@ public class ReplacementComputeValue implements MethodReplacer { <bean id="replacementComputeValue" class="a.b.c.ReplacementComputeValue"/> - One or more contained <arg-type/> - elements within the <replaced-method/> - element may be used to indicate the method signature of the method - being overridden. Note that the signature for the arguments is - actually only needed in the case that the method is actually - overloaded and there are multiple variants within the class. For - convenience, the type string for an argument may be a substring of the - fully qualified type name. For example, all the following would match - java.lang.String. + You can use one or more contained + <arg-type/> elements within the + <replaced-method/> element to indicate the + method signature of the method being overridden. The signature for the + arguments is necessary only if the method is overloaded and multiple + variants exist within the class. For convenience, the type string for + an argument may be a substring of the fully qualified type name. For + example, the following all match + java.lang.String: java.lang.String String Str - Since the number of arguments is often enough to distinguish + Because the number of arguments is often enough to distinguish between each possible choice, this shortcut can save a lot of typing, - by allowing you to type just the shortest string that will match an + by allowing you to type only the shortest string that will match an argument type.