0% found this document useful (0 votes)
52 views

Core Technologies

Auto-detection is not implemented for remote interfaces. The main reason why auto-detection of implemented interfaces does not occur for remote interfaces is to avoid opening too many doors to remote callers. The target object might implement internal callback interfaces, such as InitializingBean or DisposableBean which one would not want to expose to callers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Core Technologies

Auto-detection is not implemented for remote interfaces. The main reason why auto-detection of implemented interfaces does not occur for remote interfaces is to avoid opening too many doors to remote callers. The target object might implement internal callback interfaces, such as InitializingBean or DisposableBean which one would not want to expose to callers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

7/31/22, 5:51 PM Core Technologies

Core Technologies

Version 5.3.22

Back to index

1. The IoC Container


1.1. Introduction to the Spring IoC Container and Beans
1.2. Container Overview
1.2.1. Configuration Metadata
1.2.2. Instantiating a Container
Composing XML-based Configuration Metadata
The Groovy Bean Definition DSL
1.2.3. Using the Container
1.3. Bean Overview
1.3.1. Naming Beans
Aliasing a Bean outside the Bean Definition
1.3.2. 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
1.4. Dependencies
1.4.1. Dependency Injection
Constructor-based Dependency Injection
Setter-based Dependency Injection
Dependency Resolution Process
Examples of Dependency Injection
1.4.2. Dependencies and Configuration in Detail
Straight Values (Primitives, Strings, and so on)
References to Other Beans (Collaborators)
Inner Beans
Collections
Null and Empty String Values

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 1/23
7/31/22, 5:51 PM Core Technologies

XML Shortcut with the p-namespace


XML Shortcut with the c-namespace
Compound Property Names
1.4.3. Using  depends-on
1.4.4. Lazy-initialized Beans
1.4.5. Autowiring Collaborators
Limitations and Disadvantages of Autowiring
Excluding a Bean from Autowiring
1.4.6. Method Injection
Lookup Method Injection
Arbitrary Method Replacement
1.5. Bean Scopes
1.5.1. The Singleton Scope
1.5.2. The Prototype Scope
1.5.3. Singleton Beans with Prototype-bean Dependencies
1.5.4. Request, Session, Application, and WebSocket Scopes
Initial Web Configuration
Request scope
Session Scope
Application Scope
WebSocket Scope
Scoped Beans as Dependencies
1.5.5. Custom Scopes
Creating a Custom Scope
Using a Custom Scope
1.6. Customizing the Nature of a Bean
1.6.1. Lifecycle Callbacks
Initialization Callbacks
Destruction Callbacks
Default Initialization and Destroy Methods
Combining Lifecycle Mechanisms
Startup and Shutdown Callbacks
Shutting Down the Spring IoC Container Gracefully in Non-Web Applications
1.6.2.  ApplicationContextAware  and  BeanNameAware
1.6.3. Other  Aware  Interfaces
1.7. Bean Definition Inheritance

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 2/23
7/31/22, 5:51 PM Core Technologies

1.8. Container Extension Points


1.8.1. Customizing Beans by Using a  BeanPostProcessor
Example: Hello World,  BeanPostProcessor -style
Example: The  AutowiredAnnotationBeanPostProcessor
1.8.2. Customizing Configuration Metadata with a  BeanFactoryPostProcessor
Example: The Class Name Substitution  PropertySourcesPlaceholderConfigurer
Example: The  PropertyOverrideConfigurer
1.8.3. Customizing Instantiation Logic with a  FactoryBean
1.9. Annotation-based Container Configuration
1.9.1. @Required
1.9.2. Using  @Autowired
1.9.3. Fine-tuning Annotation-based Autowiring with  @Primary
1.9.4. Fine-tuning Annotation-based Autowiring with Qualifiers
1.9.5. Using Generics as Autowiring Qualifiers
1.9.6. Using  CustomAutowireConfigurer
1.9.7. Injection with  @Resource
1.9.8. Using  @Value
1.9.9. Using  @PostConstruct  and  @PreDestroy
1.10. Classpath Scanning and Managed Components
1.10.1.  @Component  and Further Stereotype Annotations
1.10.2. Using Meta-annotations and Composed Annotations
1.10.3. Automatically Detecting Classes and Registering Bean Definitions
1.10.4. Using Filters to Customize Scanning
1.10.5. Defining Bean Metadata within Components
1.10.6. Naming Autodetected Components
1.10.7. Providing a Scope for Autodetected Components
1.10.8. Providing Qualifier Metadata with Annotations
1.10.9. Generating an Index of Candidate Components
1.11. Using JSR 330 Standard Annotations
1.11.1. Dependency Injection with  @Inject  and  @Named
1.11.2.  @Named  and  @ManagedBean : Standard Equivalents to the  @Component  Annotation
1.11.3. Limitations of JSR-330 Standard Annotations
1.12. Java-based Container Configuration
1.12.1. Basic Concepts:  @Bean  and  @Configuration
1.12.2. Instantiating the Spring Container by Using  AnnotationConfigApplicationContext
Simple Construction

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 3/23
7/31/22, 5:51 PM Core Technologies

Building the Container Programmatically by Using  register(Class<?>…​)


Enabling Component Scanning with  scan(String…​)
Support for Web Applications with  AnnotationConfigWebApplicationContext
1.12.3. Using the  @Bean  Annotation
Declaring a Bean
Bean Dependencies
Receiving Lifecycle Callbacks
Specifying Bean Scope
Customizing Bean Naming
Bean Aliasing
Bean Description
1.12.4. Using the  @Configuration  annotation
Injecting Inter-bean Dependencies
Lookup Method Injection
Further Information About How Java-based Configuration Works Internally
1.12.5. Composing Java-based Configurations
Using the  @Import  Annotation
Conditionally Include  @Configuration  Classes or  @Bean  Methods
Combining Java and XML Configuration
1.13. Environment Abstraction
1.13.1. Bean Definition Profiles
Using  @Profile
XML Bean Definition Profiles
Activating a Profile
Default Profile
1.13.2.  PropertySource  Abstraction
1.13.3. Using  @PropertySource
1.13.4. Placeholder Resolution in Statements
1.14. Registering a  LoadTimeWeaver
1.15. Additional Capabilities of the  ApplicationContext
1.15.1. Internationalization using  MessageSource
1.15.2. Standard and Custom Events
Annotation-based Event Listeners
Asynchronous Listeners
Ordering Listeners
Generic Events

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 4/23
7/31/22, 5:51 PM Core Technologies

1.15.3. Convenient Access to Low-level Resources


1.15.4. Application Startup Tracking
1.15.5. Convenient ApplicationContext Instantiation for Web Applications
1.15.6. Deploying a Spring  ApplicationContext  as a Java EE RAR File
1.16. The  BeanFactory  API
1.16.1.  BeanFactory  or  ApplicationContext ?
2. Resources
2.1. Introduction
2.2. The  Resource  Interface
2.3. Built-in  Resource  Implementations
2.3.1.  UrlResource
2.3.2.  ClassPathResource
2.3.3.  FileSystemResource
2.3.4.  PathResource
2.3.5.  ServletContextResource
2.3.6.  InputStreamResource
2.3.7.  ByteArrayResource
2.4. The  ResourceLoader  Interface
2.5. The  ResourcePatternResolver  Interface
2.6. The  ResourceLoaderAware  Interface
2.7. Resources as Dependencies
2.8. Application Contexts and Resource Paths
2.8.1. Constructing Application Contexts
Constructing  ClassPathXmlApplicationContext  Instances — Shortcuts
2.8.2. Wildcards in Application Context Constructor Resource Paths
Ant-style Patterns
The  classpath*:  Prefix
Other Notes Relating to Wildcards
2.8.3.  FileSystemResource  Caveats
3. Validation, Data Binding, and Type Conversion
3.1. Validation by Using Spring’s Validator Interface
3.2. Resolving Codes to Error Messages
3.3. Bean Manipulation and the  BeanWrapper
3.3.1. Setting and Getting Basic and Nested Properties
3.3.2. Built-in  PropertyEditor  Implementations
Registering Additional Custom  PropertyEditor  Implementations

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 5/23
7/31/22, 5:51 PM Core Technologies

3.4. Spring Type Conversion


3.4.1. Converter SPI
3.4.2. Using  ConverterFactory
3.4.3. Using  GenericConverter
Using  ConditionalGenericConverter
3.4.4. The  ConversionService  API
3.4.5. Configuring a  ConversionService
3.4.6. Using a  ConversionService  Programmatically
3.5. Spring Field Formatting
3.5.1. The  Formatter  SPI
3.5.2. Annotation-driven Formatting
Format Annotation API
3.5.3. The  FormatterRegistry  SPI
3.5.4. The  FormatterRegistrar  SPI
3.5.5. Configuring Formatting in Spring MVC
3.6. Configuring a Global Date and Time Format
3.7. Java Bean Validation
3.7.1. Overview of Bean Validation
3.7.2. Configuring a Bean Validation Provider
Injecting a Validator
Configuring Custom Constraints
Spring-driven Method Validation
Additional Configuration Options
3.7.3. Configuring a  DataBinder
3.7.4. Spring MVC 3 Validation
4. Spring Expression Language (SpEL)
4.1. Evaluation
4.1.1. Understanding  EvaluationContext
Type Conversion
4.1.2. Parser Configuration
4.1.3. SpEL Compilation
Compiler Configuration
Compiler Limitations
4.2. Expressions in Bean Definitions
4.2.1. XML Configuration
4.2.2. Annotation Configuration

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 6/23
7/31/22, 5:51 PM Core Technologies

4.3. Language Reference


4.3.1. Literal Expressions
4.3.2. Properties, Arrays, Lists, Maps, and Indexers
4.3.3. Inline Lists
4.3.4. Inline Maps
4.3.5. Array Construction
4.3.6. Methods
4.3.7. Operators
Relational Operators
Logical Operators
Mathematical Operators
The Assignment Operator
4.3.8. Types
4.3.9. Constructors
4.3.10. Variables
The  #this  and  #root  Variables
4.3.11. Functions
4.3.12. Bean References
4.3.13. Ternary Operator (If-Then-Else)
4.3.14. The Elvis Operator
4.3.15. Safe Navigation Operator
4.3.16. Collection Selection
4.3.17. Collection Projection
4.3.18. Expression templating
4.4. Classes Used in the Examples
5. Aspect Oriented Programming with Spring
5.1. AOP Concepts
5.2. Spring AOP Capabilities and Goals
5.3. AOP Proxies
5.4. @AspectJ support
5.4.1. Enabling @AspectJ Support
Enabling @AspectJ Support with Java Configuration
Enabling @AspectJ Support with XML Configuration
5.4.2. Declaring an Aspect
5.4.3. Declaring a Pointcut
Supported Pointcut Designators

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 7/23
7/31/22, 5:51 PM Core Technologies

Combining Pointcut Expressions


Sharing Common Pointcut Definitions
Examples
Writing Good Pointcuts
5.4.4. Declaring Advice
Before Advice
After Returning Advice
After Throwing Advice
After (Finally) Advice
Around Advice
Advice Parameters
Advice Ordering
5.4.5. Introductions
5.4.6. Aspect Instantiation Models
5.4.7. An AOP Example
5.5. Schema-based AOP Support
5.5.1. Declaring an Aspect
5.5.2. Declaring a Pointcut
5.5.3. Declaring Advice
Before Advice
After Returning Advice
After Throwing Advice
After (Finally) Advice
Around Advice
Advice Parameters
Advice Ordering
5.5.4. Introductions
5.5.5. Aspect Instantiation Models
5.5.6. Advisors
5.5.7. An AOP Schema Example
5.6. Choosing which AOP Declaration Style to Use
5.6.1. Spring AOP or Full AspectJ?
5.6.2. @AspectJ or XML for Spring AOP?
5.7. Mixing Aspect Types
5.8. Proxying Mechanisms
5.8.1. Understanding AOP Proxies

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 8/23
7/31/22, 5:51 PM Core Technologies

5.9. Programmatic Creation of @AspectJ Proxies


5.10. Using AspectJ with Spring Applications
5.10.1. Using AspectJ to Dependency Inject Domain Objects with Spring
Unit Testing  @Configurable  Objects
Working with Multiple Application Contexts
5.10.2. Other Spring aspects for AspectJ
5.10.3. Configuring AspectJ Aspects by Using Spring IoC
5.10.4. Load-time Weaving with AspectJ in the Spring Framework
A First Example
Aspects
'META-INF/aop.xml'
Required libraries (JARS)
Spring Configuration
Environment-specific Configuration
5.11. Further Resources
6. Spring AOP APIs
6.1. Pointcut API in Spring
6.1.1. Concepts
6.1.2. Operations on Pointcuts
6.1.3. AspectJ Expression Pointcuts
6.1.4. Convenience Pointcut Implementations
Static Pointcuts
Dynamic pointcuts
6.1.5. Pointcut Superclasses
6.1.6. Custom Pointcuts
6.2. Advice API in Spring
6.2.1. Advice Lifecycles
6.2.2. Advice Types in Spring
Interception Around Advice
Before Advice
Throws Advice
After Returning Advice
Introduction Advice
6.3. The Advisor API in Spring
6.4. Using the  ProxyFactoryBean  to Create AOP Proxies
6.4.1. Basics

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 9/23
7/31/22, 5:51 PM Core Technologies

6.4.2. JavaBean Properties


6.4.3. JDK- and CGLIB-based proxies
6.4.4. Proxying Interfaces
6.4.5. Proxying Classes
6.4.6. Using “Global” Advisors
6.5. Concise Proxy Definitions
6.6. Creating AOP Proxies Programmatically with the  ProxyFactory
6.7. Manipulating Advised Objects
6.8. Using the "auto-proxy" facility
6.8.1. Auto-proxy Bean Definitions
BeanNameAutoProxyCreator

DefaultAdvisorAutoProxyCreator

6.9. Using  TargetSource  Implementations


6.9.1. Hot-swappable Target Sources
6.9.2. Pooling Target Sources
6.9.3. Prototype Target Sources
6.9.4.  ThreadLocal  Target Sources
6.10. Defining New Advice Types
7. Null-safety
7.1. Use cases
7.2. JSR-305 meta-annotations
8. Data Buffers and Codecs
8.1.  DataBufferFactory
8.2.  DataBuffer
8.3.  PooledDataBuffer
8.4.  DataBufferUtils
8.5. Codecs
8.6. Using  DataBuffer
9. Logging
10. Appendix
10.1. XML Schemas
10.1.1. The  util  Schema
Using  <util:constant/>
Using  <util:property-path/>
Using  <util:properties/>
Using  <util:list/>

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 10/23
7/31/22, 5:51 PM Core Technologies

Using  <util:map/>
Using  <util:set/>
10.1.2. The  aop  Schema
10.1.3. The  context  Schema
Using  <property-placeholder/>
Using  <annotation-config/>
Using  <component-scan/>
Using  <load-time-weaver/>
Using  <spring-configured/>
Using  <mbean-export/>
10.1.4. The Beans Schema
10.2. XML Schema Authoring
10.2.1. Authoring the Schema
10.2.2. Coding a  NamespaceHandler
10.2.3. Using  BeanDefinitionParser
10.2.4. Registering the Handler and the Schema
Writing  META-INF/spring.handlers
Writing 'META-INF/spring.schemas'
10.2.5. Using a Custom Extension in Your Spring XML Configuration
10.2.6. More Detailed Examples
Nesting Custom Elements within Custom Elements
Custom Attributes on “Normal” Elements
10.3. Application Startup Steps

This part of the reference documentation covers all the technologies that are absolutely integral to the
Spring Framework.

Foremost amongst these is the Spring Framework’s Inversion of Control (IoC) container. A thorough
treatment of the Spring Framework’s IoC container is closely followed by comprehensive coverage of
Spring’s Aspect-Oriented Programming (AOP) technologies. The Spring Framework has its own AOP
framework, which is conceptually easy to understand and which successfully addresses the 80% sweet
spot of AOP requirements in Java enterprise programming.

Coverage of Spring’s integration with AspectJ (currently the richest — in terms of features — and
certainly most mature AOP implementation in the Java enterprise space) is also provided.

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 11/23
7/31/22, 5:51 PM Core Technologies

1. The IoC Container


This chapter covers Spring’s Inversion of Control (IoC) container.

1.1. Introduction to the Spring IoC Container and Beans


This chapter covers the Spring Framework implementation of the Inversion of Control (IoC) principle.
IoC is also known as dependency injection (DI). It is a process whereby objects define their
dependencies (that is, the other objects they work with) only through constructor arguments, arguments
to a factory method, or properties that are set on the object instance after it is constructed or returned
from a factory method. The container then injects those dependencies when it creates the bean. This
process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself
controlling the instantiation or location of its dependencies by using direct construction of classes or a
mechanism such as the Service Locator pattern.

The  org.springframework.beans  and  org.springframework.context  packages are the basis for Spring
Framework’s IoC container. The  BeanFactory  interface provides an advanced configuration mechanism
capable of managing any type of object.  ApplicationContext  is a sub-interface of  BeanFactory . It
adds:

Easier integration with Spring’s AOP features

Message resource handling (for use in internationalization)

Event publication

Application-layer specific contexts such as the  WebApplicationContext  for use in web applications.

In short, the  BeanFactory  provides the configuration framework and basic functionality, and
the  ApplicationContext  adds more enterprise-specific functionality. The  ApplicationContext  is a
complete superset of the  BeanFactory  and is used exclusively in this chapter in descriptions of Spring’s
IoC container. For more information on using the  BeanFactory  instead of the  ApplicationContext,  see
the section covering the  BeanFactory  API.

In Spring, the objects that form the backbone of your application and that are managed by the Spring
IoC container are called beans. A bean is an object that is instantiated, assembled, and managed by a
Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and
the dependencies among them, are reflected in the configuration metadata used by a container.

1.2. Container Overview


The  org.springframework.context.ApplicationContext  interface represents the Spring IoC container
and is responsible for instantiating, configuring, and assembling the beans. The container gets its
instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 12/23
7/31/22, 5:51 PM Core Technologies

The configuration metadata is represented in XML, Java annotations, or Java code. It lets you express
the objects that compose your application and the rich interdependencies between those objects.

Several implementations of the  ApplicationContext  interface are supplied with Spring. In stand-alone
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 providing 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 web descriptor XML in the  web.xml  file of the application typically suffices (see Convenient
ApplicationContext Instantiation for Web Applications). If you use the Spring Tools for Eclipse (an
Eclipse-powered development environment), you can easily create this boilerplate configuration with a
few mouse clicks or keystrokes.

The following diagram shows a high-level view of how Spring works. Your application classes are
combined with configuration metadata so that, after the  ApplicationContext  is created and initialized,
you have a fully configured and executable system or application.

Figure 1. The Spring IoC container

1.2.1. Configuration Metadata


As the preceding diagram shows, the Spring IoC container consumes a form of configuration metadata.
This configuration metadata represents how you, as an application developer, tell the Spring container
to instantiate, configure, and assemble the objects in your application.

Configuration metadata is traditionally supplied in a simple and intuitive XML format, which is what most
of this chapter uses to convey key concepts and features of the Spring IoC container.

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 13/23
7/31/22, 5:51 PM Core Technologies

XML-based metadata is not the only allowed form of configuration metadata. The Spring IoC
container itself is totally decoupled from the format in which this configuration metadata is actually
written. These days, many developers choose Java-based configuration for their Spring
applications.

For information about using other forms of metadata with the Spring container, see:

Annotation-based configuration: Spring 2.5 introduced support for annotation-based configuration


metadata.

Java-based configuration: Starting with Spring 3.0, many features provided by the Spring
JavaConfig project became part of the core Spring Framework. Thus, you can define beans external
to your application classes by using Java rather than XML files. To use these new features, see
the  @Configuration ,  @Bean ,  @Import , and  @DependsOn  annotations.

Spring configuration consists of at least one and typically more than one bean definition that the
container must manage. XML-based configuration metadata configures these beans
as  <bean/>  elements inside a top-level  <beans/>  element. Java configuration typically uses  @Bean -
annotated methods within a  @Configuration  class.

These bean definitions correspond to the actual objects that make up your application. Typically, you
define service layer objects, data access objects (DAOs), presentation objects such as
Struts  Action  instances, infrastructure objects such as Hibernate  SessionFactories , JMS  Queues ,
and so forth. Typically, one does not configure fine-grained domain objects in the container, because it
is usually the responsibility of DAOs and business logic to create and load domain objects. However,
you can use Spring’s integration with AspectJ to configure objects that have been created outside the
control of an IoC container. See Using AspectJ to dependency-inject domain objects with Spring.

The following example shows the basic structure of XML-based configuration metadata:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="..." class="...">

<!-- collaborators and configuration for this bean go here -->

</bean>

<bean id="..." class="...">

<!-- collaborators and configuration for this bean go here -->

</bean>

<!-- more bean definitions go here -->

</beans>

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 14/23
7/31/22, 5:51 PM Core Technologies

The id attribute is a string that identifies the individual bean definition.

The class attribute defines the type of the bean and uses the fully qualified

classname.

The value of the  id  attribute refers to collaborating objects. The XML for referring to collaborating
objects is not shown in this example. See Dependencies for more information.

1.2.2. Instantiating a Container


The location path or paths supplied to an  ApplicationContext  constructor are resource strings that let
the container load configuration metadata from a variety of external resources, such as the local file
system, the Java  CLASSPATH , and so on.

Java Kotlin

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

After you learn about Spring’s IoC container, you may want to know more about
Spring’s  Resource  abstraction (as described in Resources), which provides a convenient
mechanism for reading an InputStream from locations defined in a URI syntax. In
particular,  Resource  paths are used to construct applications contexts, as described
in Application Contexts and Resource Paths.

The following example shows the service layer objects  (services.xml)  configuration file:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

https://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- services -->

<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">


<property name="accountDao" ref="accountDao"/>

<property name="itemDao" ref="itemDao"/>

<!-- additional collaborators and configuration for this bean go here -->

</bean>

<!-- more bean definitions for services go here -->

</beans>

The following example shows the data access objects  daos.xml  file:

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 15/23
7/31/22, 5:51 PM Core Technologies

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="accountDao"

class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">

<!-- additional collaborators and configuration for this bean go here -->

</bean>

<bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">

<!-- additional collaborators and configuration for this bean go here -->

</bean>

<!-- more bean definitions for data access objects go here -->

</beans>

In the preceding example, the service layer consists of the  PetStoreServiceImpl  class and two data
access objects of the types  JpaAccountDao  and  JpaItemDao  (based on the JPA Object-Relational
Mapping standard). The  property name  element refers to the name of the JavaBean property, and
the  ref  element refers to the name of another bean definition. This linkage
between  id  and  ref  elements expresses the dependency between collaborating objects. For details
of configuring an object’s dependencies, see Dependencies.

Composing XML-based Configuration Metadata


It can 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.

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. The following example shows how to do so:

<beans>

<import resource="services.xml"/>

<import resource="resources/messageSource.xml"/>

<import resource="/resources/themeSource.xml"/>

<bean id="bean1" class="..."/>

<bean id="bean2" class="..."/>

</beans>

In the preceding example, external bean definitions are loaded from three
files:  services.xml ,  messageSource.xml , and  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
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 16/23
7/31/22, 5:51 PM Core Technologies

ignored. However, 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.

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. 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  classpath:/config/services.xml . However, be aware
that you are coupling your application’s configuration to specific absolute locations. It is generally
preferable to keep an indirection for such absolute locations — for example, through "${…​}"
placeholders that are resolved against JVM system properties at runtime.

The namespace itself provides the import directive feature. Further configuration features beyond plain
bean definitions are available in a selection of XML namespaces provided by Spring — for example,
the  context  and  util  namespaces.

The Groovy Bean Definition DSL


As a further example for externalized configuration metadata, bean definitions can also be expressed in
Spring’s Groovy Bean Definition DSL, as known from the Grails framework. Typically, such
configuration live in a ".groovy" file with the structure shown in the following example:

beans {

dataSource(BasicDataSource) {

driverClassName = "org.hsqldb.jdbcDriver"

url = "jdbc:hsqldb:mem:grailsDB"

username = "sa"

password = ""

settings = [mynew:"setting"]

sessionFactory(SessionFactory) {

dataSource = dataSource

myService(MyService) {

nestedBean = { AnotherBean bean ->

dataSource = dataSource

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 17/23
7/31/22, 5:51 PM Core Technologies

This configuration style is largely equivalent to XML bean definitions and even supports Spring’s XML
configuration namespaces. It also allows for importing XML bean definition files through
an  importBeans  directive.

1.2.3. Using the Container


The  ApplicationContext  is the interface for an advanced factory capable of maintaining a registry of
different beans and their dependencies. By using the method  T getBean(String name, Class<T>
requiredType) , you can retrieve instances of your beans.

The  ApplicationContext  lets you read bean definitions and access them, as the following example
shows:

Java Kotlin

// create and configure beans

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

// retrieve configured instance

PetStoreService service = context.getBean("petStore", PetStoreService.class);

// use configured instance

List<String> userList = service.getUsernameList();

With Groovy configuration, bootstrapping looks very similar. It has a different context implementation
class which is Groovy-aware (but also understands XML bean definitions). The following example
shows Groovy configuration:

Java Kotlin

ApplicationContext context = new GenericGroovyApplicationContext("services.groovy", "daos.groovy");

The most flexible variant is  GenericApplicationContext  in combination with reader delegates — for
example, with  XmlBeanDefinitionReader  for XML files, as the following example shows:

Java Kotlin

GenericApplicationContext context = new GenericApplicationContext();


new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");

context.refresh();

You can also use the  GroovyBeanDefinitionReader  for Groovy files, as the following example shows:

Java Kotlin

GenericApplicationContext context = new GenericApplicationContext();


new GroovyBeanDefinitionReader(context).loadBeanDefinitions("services.groovy", "daos.groovy");

context.refresh();

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 18/23
7/31/22, 5:51 PM Core Technologies

You can mix and match such reader delegates on the same  ApplicationContext , reading bean
definitions from diverse configuration sources.

You can then 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 have no
dependency on Spring APIs at all. For example, Spring’s integration with web frameworks provides
dependency injection for various web framework components such as controllers and JSF-managed
beans, letting you declare a dependency on a specific bean through metadata (such as an autowiring
annotation).

1.3. Bean Overview


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

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 19/23
7/31/22, 5:51 PM Core Technologies

Property Explained in…​

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 registration of existing objects that are
created outside the container (by users). This is done by accessing the
ApplicationContext’s  BeanFactory  through the  getBeanFactory()  method, which returns
the  DefaultListableBeanFactory  implementation.  DefaultListableBeanFactory  supports 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 autowiring 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.

1.3.1. 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
the bean identifiers. The  id  attribute lets you specify exactly one id. Conventionally, these names are
alphanumeric ('myBean', 'someService', etc.), but they can contain special characters as well. If you
want to introduce other aliases for the bean, you can also specify them in the  name  attribute, separated
by a comma ( , ), semicolon ( ; ), or white space. As a historical note, in versions prior to Spring 3.1,
the  id  attribute was defined as an  xsd:ID  type, which constrained possible characters. As of 3.1, it is
defined as an  xsd:string  type. Note that bean  id  uniqueness is still enforced by the container,
though no longer by XML parsers.

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 20/23
7/31/22, 5:51 PM Core Technologies

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.

Bean Naming Conventions


The convention is to use the standard Java convention for instance field names when naming
beans. That is, bean names start with a lowercase letter and are camel-cased from there.
Examples of such names include  accountManager ,  accountService ,  userDao ,  loginController ,
and so forth.

Naming beans consistently makes your configuration easier to read and understand. Also, if you
use Spring AOP, it helps a lot when applying advice to a set of beans related by name.

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 characters are upper case, the original
casing gets preserved. These are the same rules as defined
by  java.beans.Introspector.decapitalize  (which Spring uses here).

Aliasing a Bean outside the Bean Definition


In a bean definition itself, you can supply more than one name for the bean, by using a combination of
up to one name specified by the  id  attribute and any number of other names in the  name  attribute.
These names can be equivalent aliases to the same bean and are useful for some situations, such as
letting each component in an application refer to a common dependency by using a bean name that is
specific to that component itself.

Specifying all aliases where the bean is actually defined is not always adequate, however. It is
sometimes desirable to introduce an alias for a bean that is defined elsewhere. This is commonly the
case in large systems where configuration is split amongst each subsystem, with each subsystem
having its own set of object definitions. In XML-based configuration metadata, you can use
the  <alias/>  element to accomplish this. The following example shows how to do so:

<alias name="fromName" alias="toName"/>

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 21/23
7/31/22, 5:51 PM Core Technologies

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:

<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.

Java-configuration
If you use Javaconfiguration, the  @Bean  annotation can be used to provide aliases. See Using
the  @Bean  Annotation for details.

1.3.2. 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 configuration metadata encapsulated by that bean
definition to create (or acquire) an actual object.

If you use XML-based configuration metadata, you specify the type (or class) of object that is to be
instantiated in the  class  attribute of the  <bean/>  element. 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 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.

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 22/23
7/31/22, 5:51 PM Core Technologies

Nested class names


If you want to configure a bean definition for a nested class, you may use either the binary name
or the source name of the nested class.

For example, if you have a class called  SomeThing  in the  com.example  package, and
this  SomeThing  class has a  static  nested class called  OtherThing , they can be separated by a
dollar sign ( $ ) or a dot ( . ). So the value of the  class  attribute in a bean definition would
be  com.example.SomeThing$OtherThing  or  com.example.SomeThing.OtherThing .

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 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 limited to
managing true JavaBeans. Most Spring users prefer actual 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 pool that absolutely does not adhere to the JavaBean specification, Spring can
manage it as well.

With XML-based configuration metadata you can specify your bean class as follows:

<bean id="exampleBean" class="example

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 23/23

You might also like