4
4
Bean Overview
Bean Overview
Overriding Beans
Naming Beans
Aliasing a Bean outside the Bean Definition
Instantiating Beans
Instantiation with a Constructor
Instantiation with a Static Factory Method
Instantiation by Using an Instance Factory Method
Determining a Bean’s Runtime Type
A 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).
Within the container itself, these bean definitions are represented as BeanDefinition objects, which contain (among other information) the following
metadata:
A package-qualified class name: typically, the actual implementation class of the bean being defined.
Bean behavioral configuration elements, which state how the bean should behave in the container (scope, lifecycle callbacks, and so forth).
References to other beans that are needed for the bean to do its work. These references are also called collaborators or dependencies.
Other configuration settings to set in the newly created object — for example, the size limit of the pool or the number of connections to use in a bean that
manages a connection pool.
This metadata translates to a set of properties that make up each bean definition. The following table describes these properties:
Table 1. The bean definition
Property Explained in…
Class Instantiating Beans
Name Naming Beans
Scope Bean Scopes
Constructor arguments Dependency Injection
Properties Dependency Injection
Autowiring mode Autowiring Collaborators
Lazy initialization mode Lazy-initialized Beans
Initialization method Initialization Callbacks
Destruction method Destruction Callbacks
In addition to bean definitions that contain information on how to create a specific bean, the ApplicationContext implementations also permit the registra‐
tion of existing objects that are created outside the container (by users). This is done by accessing the ApplicationContext’s BeanFactory through the
getAutowireCapableBeanFactory() method, which returns the DefaultListableBeanFactory implementation. DefaultListableBeanFactory sup‐
ports this registration through the registerSingleton(..) and registerBeanDefinition(..) methods. However, typical applications work solely with
beans defined through regular bean definition metadata.
Bean metadata and manually supplied singleton instances need to be registered as early as possible, in order for the container to properly reason about them during au‐
towiring and other introspection steps. While overriding existing metadata and existing singleton instances is supported to some degree, the registration of new beans at
runtime (concurrently with live access to the factory) is not officially supported and may lead to concurrent access exceptions, inconsistent state in the bean container, or
both.
Overriding Beans
Bean overriding occurs when a bean is registered using an identifier that is already allocated. While bean overriding is possible, it makes the configuration hard‐
er to read.
Bean overriding will be deprecated in a future release.
https://docs.spring.io/spring-framework/reference/core/beans/definition.html 1/5
4/22/25, 12:06 PM Bean Overview :: Spring Framework
To disable bean overriding altogether, you can set the allowBeanDefinitionOverriding flag to false on the ApplicationContext before it is refreshed.
In such a setup, an exception is thrown if bean overriding is used.
By default, the container logs every attempt to override a bean at INFO level so that you can adapt your configuration accordingly. While not recommended,
you can silence those logs by setting the allowBeanDefinitionOverriding flag to true .
Java Configuration
If you use Java Configuration, a corresponding @Bean method always silently overrides a scanned bean class with the same component name as long as
the return type of the @Bean method matches that bean class. This simply means that the container will call the @Bean factory method in favor of any
pre-declared constructor on the bean class.
We acknowledge that overriding beans in test scenarios is convenient, and there is explicit support for this as of Spring Framework 6.2. Please refer to this section for more
details.
Naming Beans
Every bean has one or more identifiers. These identifiers must be unique within the container that hosts the bean. A bean usually has only one identifier.
However, if it requires more than one, the extra ones can be considered aliases.
In XML-based configuration metadata, you use the id attribute, the name attribute, or both to specify bean identifiers. The id attribute lets you specify ex‐
actly one id . Conventionally, these names are alphanumeric ('myBean', 'someService', etc.), but they can contain special characters as well. If you want to in‐
troduce other aliases for the bean, you can also specify them in the name attribute, separated by a comma ( , ), semicolon ( ; ), or white space. Although the
id attribute is defined as an xsd:string type, bean id uniqueness is enforced by the container, though not by XML parsers.
You are not required to supply a name or an id for a bean. If you do not supply a name or id 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 a Service Locator style lookup, you must provide a name.
Motivations for not supplying a name are related to using inner beans and autowiring collaborators.
With component scanning in the classpath, Spring generates bean names for unnamed components, following the rules described earlier: essentially, taking the simple
class name and turning its initial character to lower-case. However, in the (unusual) special case when there is more than one character and both the first and second char‐
acters are upper case, the original casing gets preserved. These are the same rules as defined by java.beans.Introspector.decapitalize (which Spring uses here).
In this case, a bean (in the same container) 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 by the name of subsystemA-dataSource . The configuration metadata for
subsystem B may refer to a DataSource by the name of subsystemB-dataSource . When composing the main application that uses both these subsystems,
the main application refers to the DataSource by the name of myApp-dataSource . To have all three names refer to the same object, you can add the following
alias definitions to the configuration metadata:
XML
<alias name="myApp-dataSource" alias="subsystemA-dataSource"/>
<alias name="myApp-dataSource" alias="subsystemB-dataSource"/>
Now each component and the main application can refer to the dataSource through a name that is unique and guaranteed not to clash with any other definition
(effectively creating a namespace), yet they refer to the same bean.
https://docs.spring.io/spring-framework/reference/core/beans/definition.html 2/5
4/22/25, 12:06 PM Bean Overview :: Spring Framework
Java-configuration
If you use Java Configuration, the @Bean annotation can be used to provide aliases. See Using the @Bean Annotation for details.
Instantiating Beans
A bean definition is essentially a recipe for creating one or more objects. The container looks at the recipe for a named bean when asked and uses the configu‐
ration metadata encapsulated by that bean definition to create (or acquire) an actual object.
If you use XML-based configuration metadata, you specify the type (or class) of object that is to be instantiated in the class attribute of the <bean/> ele‐
ment. This class attribute (which, internally, is a Class property on a BeanDefinition instance) is usually mandatory. (For exceptions, see Instantiation by
Using an Instance Factory Method and Bean Definition Inheritance.) You can use the Class property in one of two ways:
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 with the new operator.
To specify the actual class containing the static factory method that is invoked to create the object, in the less common case where the container in‐
vokes 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.
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.
In the case of constructor arguments, the container can select a corresponding constructor among several overloaded constructors. That said, to avoid ambiguities, it is
recommended to keep your constructor signatures as straightforward as possible.
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, but rather the class containing the factory method. In this example, the createInstance() method must be a static method. The following example
shows how to specify a factory method:
XML
<bean id="clientService"
class="examples.ClientService"
factory-method="createInstance"/>
The following example shows a class that would work with the preceding bean definition:
https://docs.spring.io/spring-framework/reference/core/beans/definition.html 3/5
4/22/25, 12:06 PM Bean Overview :: Spring Framework
Java Kotlin
JAVA
public class ClientService {
private static ClientService clientService = new ClientService();
private ClientService() {}
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.
In the case of factory method arguments, the container can select a corresponding method among several overloaded methods of the same name. That said, to avoid ambi‐
guities, it is recommended to keep your factory method signatures as straightforward as possible.
A typical problematic case with factory method overloading is Mockito with its many overloads of the mock method. Choose the most specific variant of mock possible:
<bean id="clientService" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg type="java.lang.Class" value="examples.ClientService"/>
<constructor-arg type="java.lang.String" value="clientService"/>
</bean>
One factory class can also hold more than one factory method, as the following example shows:
XML
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
<!-- inject any dependencies required by this locator bean -->
</bean>
<bean id="clientService"
factory-bean="serviceLocator"
factory-method="createClientServiceInstance"/>
<bean id="accountService"
factory-bean="serviceLocator"
factory-method="createAccountServiceInstance"/>
https://docs.spring.io/spring-framework/reference/core/beans/definition.html 4/5
4/22/25, 12:06 PM Bean Overview :: Spring Framework
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" refers to a bean that is configured in the Spring container and that creates objects through an instance or static factory method. By
contrast, FactoryBean (notice the capitalization) refers to a Spring-specific FactoryBean implementation class.
Copyright © 2005 - 2025 Broadcom. All Rights Reserved. The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
Terms of Use • Privacy • Trademark Guidelines • Thank you • Your California Privacy Rights •
Apache®, Apache Tomcat®, Apache Kafka®, Apache Cassandra™, and Apache Geode™ are trademarks or registered trademarks of the Apache Software
Foundation in the United States and/or other countries. Java™, Java™ SE, Java™ EE, and OpenJDK™ are trademarks of Oracle and/or its affiliates. Kubernetes® is a
registered trademark of the Linux Foundation in the United States and other countries. Linux® is the registered trademark of Linus Torvalds in the United States
and other countries. Windows® and Microsoft® Azure are registered trademarks of Microsoft Corporation. “AWS” and “Amazon Web Services” are trademarks or
registered trademarks of Amazon.com Inc. or its affiliates. All other trademarks and copyrights are property of their respective owners and are only mentioned for
informative purposes. Other names may be trademarks of their respective owners.
https://docs.spring.io/spring-framework/reference/core/beans/definition.html 5/5