Spring Core Technologies
Spring Core Technologies
Core Technologies
Version 5.3.20
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)
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 1/373
6/10/22, 3:58 PM Core Technologies
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 3/373
6/10/22, 3:58 PM Core Technologies
Simple Construction
Building the Container Programmatically by Using register(Class<?>…
)
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 4/373
6/10/22, 3:58 PM Core Technologies
2.3.2. ClassPathResource
2.3.3. FileSystemResource
2.3.4. PathResource
2.3.5. ServletContextResource
2.3.6. InputStreamResource
2.3.7. ByteArrayResource
Using ConditionalGenericConverter
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
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
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 7/373
6/10/22, 3:58 PM Core Technologies
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
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
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 9/373
6/10/22, 3:58 PM Core Technologies
DefaultAdvisorAutoProxyCreator
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 10/373
6/10/22, 3:58 PM Core Technologies
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/>
Using <util:map/>
Using <util:set/>
Using <annotation-config/>
Using <component-scan/>
Using <load-time-weaver/>
Using <spring-configured/>
Using <mbean-export/>
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
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 11/373
6/10/22, 3:58 PM Core Technologies
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.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 12/373
6/10/22, 3:58 PM Core Technologies
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.
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.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 13/373
6/10/22, 3:58 PM Core Technologies
For information about using other forms of metadata with the Spring container, see:
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.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 14/373
6/10/22, 3:58 PM Core Technologies
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
<?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>
</bean>
</beans>
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.
Java Kotlin
JAVA
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 15/373
6/10/22, 3:58 PM Core Technologies
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
<?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">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
</beans>
The following example shows the data access objects daos.xml file:
XML
<?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>
<!-- 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
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 16/373
6/10/22, 3:58 PM Core Technologies
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:
XML
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
</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 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.
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.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 17/373
6/10/22, 3:58 PM Core Technologies
GROOVY
beans {
dataSource(BasicDataSource) {
driverClassName = "org.hsqldb.jdbcDriver"
url = "jdbc:hsqldb:mem:grailsDB"
username = "sa"
password = ""
settings = [mynew:"setting"]
}
sessionFactory(SessionFactory) {
dataSource = dataSource
}
myService(MyService) {
dataSource = dataSource
}
}
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.
The ApplicationContext lets you read bean definitions and access them, as the following
example shows:
Java Kotlin
JAVA
// create and configure beans
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 18/373
6/10/22, 3:58 PM Core Technologies
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
JAVA
ApplicationContext context = new GenericGroovyApplicationContext("services.groovy", "daos.groovy")
Java Kotlin
JAVA
GenericApplicationContext context = new GenericApplicationContext();
context.refresh();
You can also use the GroovyBeanDefinitionReader for Groovy files, as the following
example shows:
Java Kotlin
JAVA
GenericApplicationContext context = new GenericApplicationContext();
context.refresh();
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).
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 19/373
6/10/22, 3:58 PM Core Technologies
Within the container itself, these bean definitions are represented as BeanDefinition
objects, which
contain (among other information) the following metadata:
This metadata translates to a set of properties that make up each bean definition.
The following table
describes these properties:
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.
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.
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.
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
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 21/373
6/10/22, 3:58 PM Core Technologies
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:
XML
<alias name="fromName" alias="toName"/>
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"/>
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.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 22/373
6/10/22, 3:58 PM Core Technologies
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.
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 .
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
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 23/373
6/10/22, 3:58 PM Core Technologies
With XML-based configuration metadata you can specify your bean class as follows:
XML
<bean id="exampleBean" class="examples.ExampleBean"/>
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.
The following bean definition specifies that the bean 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. 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:
Java Kotlin
JAVA
public class 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
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 24/373
6/10/22, 3:58 PM Core Technologies
Configuration in Detail.
XML
<!-- the factory bean, which contains a method called createInstance() -->
</bean>
<bean id="clientService"
factory-bean="serviceLocator"
factory-method="createClientServiceInstance"/>
Java Kotlin
JAVA
public class DefaultServiceLocator {
return clientService;
}
}
One factory class can also hold more than one factory method, as the following example shows:
XML
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
</bean>
<bean id="clientService"
factory-bean="serviceLocator"
factory-method="createClientServiceInstance"/>
<bean id="accountService"
factory-bean="serviceLocator"
factory-method="createAccountServiceInstance"/>
Java Kotlin
JAVA
public class DefaultServiceLocator {
return clientService;
return accountService;
}
}
This approach shows that the factory bean itself can be managed and configured through
dependency
injection (DI). See Dependencies and
Configuration in Detail.
The recommended way to find out about the actual runtime type of a particular bean is
a
BeanFactory.getType call for the specified bean name. This takes all of the above
cases into account and
returns the type of object that a BeanFactory.getBean call is
going to return for the same bean name.
1.4. Dependencies
A typical enterprise application does not consist of a single object (or bean in the
Spring parlance). Even
the simplest application has a few objects that work together to
present what the end-user sees as a
coherent application. This next section explains how
you go from defining a number of bean definitions
that stand alone to a fully realized
application where objects collaborate to achieve a goal.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 26/373
6/10/22, 3:58 PM Core Technologies
Code is cleaner with the DI principle, and decoupling is more effective when objects are
provided with
their dependencies. The object does not look up its dependencies and does
not know the location or class
of the dependencies. As a result, your classes become easier
to test, particularly when the dependencies
are on interfaces or abstract base classes,
which allow for stub or mock implementations to be used in
unit tests.
Java Kotlin
JAVA
public class SimpleMovieLister {
this.movieFinder = movieFinder;
Notice that there is nothing special about this class. It is a POJO that
has no dependencies on container
specific interfaces, base classes, or annotations.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 27/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
package x.y;
// ...
}
}
Assuming that the ThingTwo and ThingThree classes are not related by inheritance, no
potential
ambiguity exists. Thus, the following configuration works fine, and you do not
need to specify the
constructor argument indexes or types explicitly in the
<constructor-arg/> element.
XML
<beans>
<constructor-arg ref="beanTwo"/>
<constructor-arg ref="beanThree"/>
</bean>
</beans>
When another bean is referenced, the type is known, and matching can occur (as was the
case with the
preceding example). When a simple type is used, such as
<value>true</value> , Spring cannot determine
the type of the value, and so cannot match
by type without help. Consider the following class:
Java Kotlin
JAVA
package examples;
this.years = years;
this.ultimateAnswer = ultimateAnswer;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 28/373
6/10/22, 3:58 PM Core Technologies
}
}
XML
<bean id="exampleBean" class="examples.ExampleBean">
</bean>
XML
<bean id="exampleBean" class="examples.ExampleBean">
</bean>
XML
<bean id="exampleBean" class="examples.ExampleBean">
</bean>
Keep in mind that, to make this work out of the box, your code must be compiled with the
debug flag
enabled so that Spring can look up the parameter name from the constructor.
If you cannot or do not
want to compile your code with the debug flag, you can use the
@ConstructorProperties
JDK annotation to
explicitly name your constructor arguments. The sample class would
then have to look as follows:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 29/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
package examples;
// Fields omitted
@ConstructorProperties({"years", "ultimateAnswer"})
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
The following example shows a class that can only be dependency-injected by using pure
setter injection.
This class is conventional Java. It is a POJO that has no dependencies
on container specific interfaces, base
classes, or annotations.
Java Kotlin
JAVA
public class SimpleMovieLister {
this.movieFinder = movieFinder;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 30/373
6/10/22, 3:58 PM Core Technologies
The Spring team generally advocates constructor injection, as it lets you implement
application
components as immutable objects and ensures that required dependencies
are not null .
Furthermore, constructor-injected components are always returned to the client
(calling) code in a
fully initialized state. As a side note, a large number of constructor
arguments is a bad code smell,
implying that the class likely has too many
responsibilities and should be refactored to better
address proper separation of concerns.
Setter injection should primarily only be used for optional dependencies that can be
assigned
reasonable default values within the class. Otherwise, not-null checks must be
performed
everywhere the code uses the dependency. One benefit of setter injection is that
setter methods
make objects of that class amenable to reconfiguration or re-injection
later. Management through
JMX MBeans is therefore a compelling
use case for setter injection.
Use the DI style that makes the most sense for a particular class. Sometimes, when dealing
with
third-party classes for which you do not have the source, the choice is made for you.
For example, if
a third-party class does not expose any setter methods, then constructor
injection may be the only
available form of DI.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 31/373
6/10/22, 3:58 PM Core Technologies
The Spring container validates the configuration of each bean as the container is created.
However, the
bean properties themselves are not set until the bean is actually created.
Beans that are singleton-scoped
and set to be pre-instantiated (the default) are created
when the container is created. Scopes are defined
in Bean Scopes. Otherwise,
the bean is created only when it is requested. Creation of a bean potentially
causes a
graph of beans to be created, as the bean’s dependencies and its dependencies'
dependencies
(and so on) are created and assigned. Note that resolution mismatches among
those dependencies may
show up late — that is, on first creation of the affected bean.
Circular dependencies
If you use predominantly constructor injection, it is possible to create an unresolvable
circular
dependency scenario.
For example: Class A requires an instance of class B through 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
BeanCurrentlyInCreationException .
One possible solution is to edit the source code of some classes to be configured by
setters rather
than constructors. Alternatively, avoid constructor injection and use
setter injection only. In other
words, although it is not recommended, you can configure
circular dependencies with setter
injection.
You can generally trust Spring to do the right thing. It detects configuration problems,
such as references
to non-existent beans and circular dependencies, at container
load-time. Spring sets properties and
resolves dependencies as late as possible, when
the bean is actually created. This means that a Spring
container that has loaded
correctly can later generate an exception when you request an object if there is
a
problem creating that object or one of its dependencies — for example, the bean throws an
exception as
a result of a missing or invalid property. This potentially delayed
visibility of some configuration issues is
why ApplicationContext implementations by
default pre-instantiate singleton beans. At the cost of some
upfront time and memory to
create these beans before they are actually needed, you discover
configuration issues
when the ApplicationContext is created, not later. You can still override this default
behavior so that singleton beans initialize lazily, rather than being eagerly
pre-instantiated.
If no circular dependencies exist, when one or more collaborating beans are being
injected into a
dependent bean, each collaborating bean is totally configured prior
to being injected into the dependent
bean. This means that, if bean A has a dependency on
bean B, the Spring IoC container completely
configures bean B prior to invoking the
setter method on bean A. In other words, the bean is instantiated
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 32/373
6/10/22, 3:58 PM Core Technologies
(if it is not a
pre-instantiated singleton), its dependencies are set, and the relevant lifecycle
methods (such
as a configured init method
or the InitializingBean callback method)
are invoked.
XML
<bean id="exampleBean" class="examples.ExampleBean">
<property name="beanOne">
<ref bean="anotherExampleBean"/>
</property>
</bean>
Java Kotlin
JAVA
public class ExampleBean {
private int i;
this.beanOne = beanOne;
this.beanTwo = beanTwo;
this.i = i;
}
}
In the preceding example, setters are declared to match against the properties specified
in the XML file.
The following example uses constructor-based DI:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 33/373
6/10/22, 3:58 PM Core Technologies
XML
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg>
<ref bean="anotherExampleBean"/>
</constructor-arg>
<constructor-arg ref="yetAnotherBean"/>
</bean>
Java Kotlin
JAVA
public class ExampleBean {
private int i;
public ExampleBean(
this.beanOne = anotherBean;
this.beanTwo = yetAnotherBean;
this.i = i;
}
}
The constructor arguments specified in the bean definition are used as arguments to
the constructor of
the ExampleBean .
Now consider a variant of this example, where, instead of using a constructor, Spring is
told to call a
static factory method to return an instance of the object:
XML
<bean id="exampleBean" class="examples.ExampleBean" factory-method="createInstance">
<constructor-arg ref="anotherExampleBean"/>
<constructor-arg ref="yetAnotherBean"/>
<constructor-arg value="1"/>
</bean>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 34/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
public class ExampleBean {
// a private constructor
private ExampleBean(...) {
...
return eb;
}
}
XML
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
</bean>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 35/373
6/10/22, 3:58 PM Core Technologies
The following example uses the p-namespace for even more succinct
XML configuration:
XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/mydb"
p:username="root"
p:password="misterkaoli"/>
</beans>
The preceding XML is more succinct. However, typos are discovered at runtime rather than
design time,
unless you use an IDE (such as IntelliJ
IDEA or the Spring Tools for Eclipse)
that supports automatic
property completion when you create bean definitions. Such IDE
assistance is highly recommended.
XML
<bean id="mappings"
class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="properties">
<value>
jdbc.driver.className=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb
</value>
</property>
</bean>
The Spring container converts the text inside the <value/> element into a
java.util.Properties
instance by using the JavaBeans PropertyEditor mechanism. This
is a nice shortcut, and is one of a few
places where the Spring team do favor the use of
the nested <value/> element over the value attribute
style.
The idref element is simply an error-proof way to pass the id (a string value - not
a reference) of
another bean in the container to a <constructor-arg/> or <property/>
element. The following example
shows how to use it:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 36/373
6/10/22, 3:58 PM Core Technologies
XML
<bean id="theTargetBean" class="..."/>
<property name="targetName">
<idref bean="theTargetBean"/>
</property>
</bean>
The preceding bean definition snippet is exactly equivalent (at runtime) to the
following snippet:
XML
<bean id="theTargetBean" class="..." />
</bean>
The first form is preferable to the second, because using the idref tag lets the
container 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 typo and the resulting exception
may only be discovered long after the
container is deployed.
The local attribute on the idref element is no longer supported in the 4.0 beans
XSD, since it
does not provide value over a regular bean reference any more. Change
your existing idref local
references to idref bean when upgrading to the 4.0 schema.
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. Using <idref/>
elements when you specify the
interceptor names prevents you from misspelling an interceptor ID.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 37/373
6/10/22, 3:58 PM Core Technologies
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 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 be the same
as one of the values in the name attribute of the target bean. The
following example
shows how to use a ref element:
XML
<ref bean="someBean"/>
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. The target bean
must be in a
parent container of the current one. You should 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 has the same name as the parent bean. The following pair of
listings shows how to use the
parent attribute:
XML
<!-- in the parent context -->
</bean>
XML
<!-- in the child (descendant) context -->
<bean id="accountService" <!-- bean name is the same as the parent bean -->
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref parent="accountService"/> <!-- notice how we refer to the parent bean -->
</property>
<!-- insert other configuration and dependencies as required here -->
</bean>
The local attribute on the ref element is no longer supported in the 4.0 beans
XSD, since it does
not provide value over a regular bean reference any more. Change
your existing ref local
references to ref bean when upgrading to the 4.0 schema.
Inner Beans
A <bean/> element inside the <property/> or <constructor-arg/> elements defines an
inner bean, as
the following example shows:
XML
<bean id="outer" class="...">
<!-- instead of using a reference to a target bean, simply define the target bean inline -->
<property name="target">
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 38/373
6/10/22, 3:58 PM Core Technologies
<bean class="com.example.Person"> <!-- this is the inner bean -->
An inner bean definition does not require a defined ID or name. If specified, the container
does not use
such a value as an identifier. The container also ignores the scope flag on
creation, because inner beans
are always anonymous and are always created with the outer
bean. It is not possible to access inner beans
independently or to inject them into
collaborating beans other than into the enclosing bean.
As a corner case, it is possible to receive destruction callbacks from a custom scope — for example, for a
request-scoped inner bean contained within a singleton bean. The creation
of the inner bean instance is
tied to its containing bean, but destruction callbacks let it
participate in the request scope’s lifecycle. This is
not a common scenario. Inner beans
typically simply share their containing bean’s scope.
Collections
The <list/> , <set/> , <map/> , and <props/> elements set the properties
and arguments of the Java
Collection types List , Set , Map , and Properties ,
respectively. The following example shows how to
use them:
XML
<bean id="moreComplexObject" class="example.ComplexObject">
<property name="adminEmails">
<props>
<prop key="administrator">administrator@example.org</prop>
<prop key="support">support@example.org</prop>
<prop key="development">development@example.org</prop>
</props>
</property>
<!-- results in a setSomeList(java.util.List) call -->
<property name="someList">
<list>
</list>
</property>
<!-- results in a setSomeMap(java.util.Map) call -->
<property name="someMap">
<map>
</map>
</property>
<!-- results in a setSomeSet(java.util.Set) call -->
<property name="someSet">
<set>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 39/373
6/10/22, 3:58 PM Core Technologies
<ref bean="myDataSource" />
</set>
</property>
</bean>
The value of a map key or value, or a set value, can also be any of the
following elements:
XML
bean | ref | idref | list | set | map | props | value | null
Collection Merging
This section on merging discusses the parent-child bean mechanism. Readers unfamiliar
with parent and
child bean definitions may wish to read the
relevant section before continuing.
XML
<beans>
<property name="adminEmails">
<props>
<prop key="administrator">administrator@example.com</prop>
<prop key="support">support@example.com</prop>
</props>
</property>
</bean>
<property name="adminEmails">
<props merge="true">
<prop key="sales">sales@example.com</prop>
<prop key="support">support@example.co.uk</prop>
</props>
</property>
</bean>
<beans>
Notice the use of the merge=true attribute on the <props/> element of the
adminEmails property of the
child bean definition. When the child bean is resolved
and instantiated by the container, the resulting
instance has an adminEmails Properties collection that contains the result of merging the child’s
adminEmails collection with the parent’s adminEmails collection. The following listing
shows the result:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 40/373
6/10/22, 3:58 PM Core Technologies
administrator=administrator@example.com
sales=sales@example.com
support=support@example.co.uk
The child Properties collection’s value set inherits all property elements from the
parent <props/> , and
the child’s value for the support value overrides the value in
the parent collection.
This merging behavior applies similarly to the <list/> , <map/> , and <set/>
collection types. In the
specific case of the <list/> element, the semantics
associated with the List collection type (that is, the
notion of an ordered
collection of values) is maintained. The parent’s values precede all of the child list’s
values. In the case of the Map , Set , and Properties collection types, no ordering
exists. Hence, no
ordering semantics are in effect for the collection types that underlie
the associated Map , Set , and
Properties implementation types that the container
uses internally.
You cannot merge different collection types (such as a Map and a List ). 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 does not
result in the desired merging.
Strongly-typed collection
Thanks to Java’s support for generic types, you can use strongly typed collections.
That is, it is possible to
declare a Collection type such that it can only contain
(for example) String elements. If you use Spring
to dependency-inject a
strongly-typed Collection into a bean, you can take advantage of Spring’s
type-
conversion support such that the elements of your strongly-typed Collection
instances are converted to
the appropriate type prior to being added to the Collection .
The following Java class and bean definition
show how to do so:
Java Kotlin
JAVA
public class SomeClass {
this.accounts = accounts;
}
}
XML
<beans>
<property name="accounts">
<map>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 41/373
6/10/22, 3:58 PM Core Technologies
<entry key="two" value="2.75"/>
</map>
</property>
</bean>
</beans>
When the accounts property of the something 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.
XML
<bean class="ExampleBean">
</bean>
Java Kotlin
JAVA
exampleBean.setEmail("");
The <null/> element handles null values. The following listing shows an example:
XML
<bean class="ExampleBean">
<property name="email">
<null/>
</property>
</bean>
Java Kotlin
JAVA
exampleBean.setEmail(null);
The following example shows two XML snippets (the first uses
standard XML format and the second uses
the p-namespace) that resolve to the same result:
XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
</bean>
p:email="someone@somewhere.com"/>
</beans>
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 does 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:
XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
</bean>
<bean name="john-modern"
class="com.example.Person"
p:name="John Doe"
p:spouse-ref="jane"/>
</bean>
</beans>
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
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 43/373
6/10/22, 3:58 PM Core Technologies
p:spouse-ref="jane"as an
attribute to do the exact same thing. In this case, spouse is the property
name,
whereas the -ref part indicates that this is not a straight value but rather a
reference to another
bean.
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.
The following example uses the c: namespace to do the same thing as the from
Constructor-based
Dependency Injection:
XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
</bean>
c:thingThree-ref="beanThree" c:email="something@somewhere.com"/>
</beans>
The c: namespace uses the same conventions as the p: one (a trailing -ref for
bean references) for
setting the constructor arguments by their names. Similarly,
it needs to be declared in the XML file even
though it is not defined in an XSD schema
(it exists inside the Spring core).
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 44/373
6/10/22, 3:58 PM Core Technologies
For the rare cases where the constructor argument names are not available (usually if
the bytecode was
compiled without debugging information), you can use fallback to the
argument indexes, as follows:
XML
<!-- c-namespace index declaration -->
c:_2="something@somewhere.com"/>
Due to the XML grammar, the index notation requires the presence of the leading _ ,
as XML
attribute names cannot start with a number (even though some IDEs allow it).
A corresponding index
notation is also available for <constructor-arg> elements but
not commonly used since the plain
order of declaration is usually sufficient there.
XML
<bean id="something" class="things.ThingOne">
<property name="fred.bob.sammy" value="123" />
</bean>
The something bean has a fred property, which has a bob property, which has a sammy
property, and
that final sammy property is being set to a value of 123 . In order for
this to work, the fred property of
something and the bob property of fred must not
be null after the bean is constructed. Otherwise, a
NullPointerException is thrown.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 45/373
6/10/22, 3:58 PM Core Technologies
XML
<bean id="beanOne" class="ExampleBean" depends-on="manager"/>
To express a dependency on multiple beans, supply a list of bean names as the value of
the depends-on
attribute (commas, whitespace, and semicolons are valid
delimiters):
XML
<bean id="beanOne" class="ExampleBean" depends-on="manager,accountDao">
</bean>
XML
<bean id="lazy" class="com.something.ExpensiveToCreateBean" lazy-init="true"/>
You can also control lazy-initialization at the container level by using the
default-lazy-init attribute on
the <beans/> element, as the following example shows:
XML
<beans default-lazy-init="true">
</beans>
Mode Explanation
byName 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.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 47/373
6/10/22, 3:58 PM Core Technologies
Mode Explanation
byType Lets a property 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).
constructor 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.
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 Map instances if the expected key type is String . An
autowired Map
instance’s values consist of all bean instances that match the expected type, and the
Map
instance’s keys contain the corresponding bean names.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 48/373
6/10/22, 3:58 PM Core Technologies
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 definition’s autowire-candidate attribute always takes
precedence.
For such beans, the pattern matching rules do not apply.
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 by
using autowiring. Rather, the bean
itself is not a candidate for autowiring other beans.
Java Kotlin
JAVA
// a class that uses a stateful Command-style class to perform some processing
package fiona.apple;
// Spring-API imports
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
command.setState(commandState);
return command.execute();
this.applicationContext = applicationContext;
}
}
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, lets you handle
this use case cleanly.
You can read more about the motivation for Method Injection in
this blog entry.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 50/373
6/10/22, 3:58 PM Core Technologies
For this dynamic subclassing to work, the class that the Spring bean container
subclasses cannot
be final , and the method to be overridden cannot be final , either.
Unit-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.
Concrete methods are also necessary for component scanning, which requires concrete
classes to
pick up.
A further key limitation is that lookup methods do not work with factory methods and
in
particular not with @Bean methods in configuration classes, since, in that case,
the container is
not in charge of creating the instance and therefore cannot create
a runtime-generated subclass
on the fly.
In the case of the CommandManager class in the previous code snippet, the
Spring container dynamically
overrides the implementation of the createCommand()
method. The CommandManager class does not have
any Spring dependencies, as
the reworked example shows:
Java Kotlin
JAVA
package fiona.apple;
command.setState(commandState);
return command.execute();
In the client class that contains the method to be injected (the CommandManager in this
case), the method
to be injected requires a signature of the following form:
XML
<public|protected> [abstract] <return-type> theMethodName(no-arguments);
XML
<!-- a stateful bean deployed as a prototype (non-singleton) -->
</bean>
</bean>
Alternatively, within the annotation-based component model, you can declare a lookup
method through
the @Lookup annotation, as the following example shows:
Java Kotlin
JAVA
public abstract class CommandManager {
command.setState(commandState);
return command.execute();
@Lookup("myCommand")
Or, more idiomatically, you can rely on the target bean getting resolved against the
declared return type of
the lookup method:
Java Kotlin
JAVA
public abstract class CommandManager {
command.setState(commandState);
return command.execute();
@Lookup
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 52/373
6/10/22, 3:58 PM Core Technologies
Note that you should typically declare such annotated lookup methods with a concrete
stub
implementation, in order for them to be compatible with Spring’s component
scanning rules where
abstract classes get ignored by default. This limitation does not
apply to explicitly registered or explicitly
imported bean classes.
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, which has a
method called computeValue that we want to override:
Java Kotlin
JAVA
public class MyValueCalculator {
Java Kotlin
JAVA
/**
* implementation in MyValueCalculator
*/
// get the input value, work with it, and return a computed result
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 53/373
6/10/22, 3:58 PM Core Technologies
String input = (String) args[0];
...
return ...;
}
}
The bean definition to deploy the original class and specify the method override would
resemble the
following example:
XML
<bean id="myValueCalculator" class="x.y.z.MyValueCalculator">
<arg-type>String</arg-type>
</replaced-method>
</bean>
You can use one or more <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
java.lang.String
String
Str
Because the number of arguments is often enough to distinguish between each possible
choice, this
shortcut can save a lot of typing, by letting you type only the
shortest string that matches an argument
type.
You can control not only the various dependencies and configuration values that are to
be plugged into an
object that is created from a particular bean definition but also control
the scope of the objects created
from a particular bean definition. This approach is
powerful and flexible, because you can choose the
scope of the objects you create
through configuration instead of having to bake in the scope of an object
at the Java
class level. Beans can be defined to be deployed in one of a number of scopes.
The Spring
Framework supports six scopes, four of which are available only if
you use a web-aware
ApplicationContext . You can also create
a custom scope.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 54/373
6/10/22, 3:58 PM Core Technologies
Scope Description
singleton (Default) Scopes a single bean definition to a single object instance for each Spring
IoC
container.
request Scopes a single bean definition to the lifecycle of a single HTTP request. That is,
each HTTP request has its own instance of a bean created off the back of a single
bean
definition. Only valid in the context of a web-aware Spring
ApplicationContext .
session Scopes a single bean definition to the lifecycle of an HTTP Session . Only valid in
the context of a web-aware Spring ApplicationContext .
application Scopes a single bean definition to the lifecycle of a ServletContext . Only valid in
the context of a web-aware Spring ApplicationContext .
websocket Scopes a single bean definition to the lifecycle of a WebSocket . Only valid in
the
context of a web-aware Spring ApplicationContext .
As of Spring 3.0, a thread scope is available but is not registered by default. For
more information,
see the documentation for
SimpleThreadScope .
For instructions on how to register this or any other
custom scope, see
Using a Custom Scope.
To put it another way, when you define a bean definition and it is scoped as a
singleton, the Spring IoC
container creates exactly one instance of the object
defined by that bean definition. This single instance is
stored in a cache of such
singleton beans, and all subsequent requests and references for that named
bean
return the cached object. The following image shows how the singleton scope works:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 55/373
6/10/22, 3:58 PM Core Technologies
Spring’s concept of a singleton bean differs from the singleton pattern as defined in
the Gang of Four (GoF)
patterns book. The GoF singleton hard-codes the scope of an
object such that one and only one instance
of a particular class is created per
ClassLoader. The scope of the Spring singleton is best described as
being per-container
and per-bean. This means that, if you define one bean for a particular class in a
single
Spring container, the Spring container creates one and only one instance
of the class defined by that bean
definition. The singleton scope is the default scope
in Spring. To define a bean as a singleton in XML, you
can define a bean as shown in the
following example:
XML
<bean id="accountService" class="com.something.DefaultAccountService"/>
<!-- the following is equivalent, though redundant (singleton scope is the default) -->
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 56/373
6/10/22, 3:58 PM Core Technologies
XML
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
In contrast to the other scopes, Spring does not manage the complete lifecycle of a
prototype bean. The
container instantiates, configures, and otherwise assembles a
prototype object and hands it to the client,
with no further record of that prototype
instance. Thus, although initialization lifecycle callback methods
are called on all
objects regardless of scope, in the case of prototypes, configured destruction
lifecycle
callbacks are not called. The client code must clean up prototype-scoped
objects and release expensive
resources that the prototype beans hold. To get
the Spring container to release resources held by
prototype-scoped beans, try using a
custom bean post-processor, which holds a reference to
beans that
need to be cleaned up.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 57/373
6/10/22, 3:58 PM Core Technologies
However, suppose you want the singleton-scoped bean to acquire a new instance of the
prototype-scoped
bean repeatedly at runtime. You cannot dependency-inject a
prototype-scoped bean into your singleton
bean, because that injection occurs only
once, when the Spring container instantiates the singleton bean
and resolves
and injects its dependencies. If you need a new instance of a prototype bean at
runtime
more than once, see Method Injection.
How you accomplish this initial setup depends on your particular Servlet environment.
If you access scoped beans within Spring Web MVC, in effect, within a request that is
processed by the
Spring DispatcherServlet , no special setup is necessary.
DispatcherServlet already exposes all
relevant state.
If you use a Servlet 2.5 web container, with requests processed outside of Spring’s
DispatcherServlet (for
example, when using JSF or Struts), you need to register the
org.springframework.web.context.request.RequestContextListener ServletRequestListener .
For
Servlet 3.0+, this can be done programmatically by using the WebApplicationInitializer
interface.
Alternatively, or for older containers, add the following declaration to
your web application’s web.xml file:
XML
<web-app>
...
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
...
</web-app>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 58/373
6/10/22, 3:58 PM Core Technologies
Alternatively, if there are issues with your listener setup, consider using Spring’s
RequestContextFilter .
The filter mapping depends on the surrounding web
application configuration, so you have to change it as
appropriate. The following listing
shows the filter part of a web application:
XML
<web-app>
...
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
Request scope
Consider the following XML configuration for a bean definition:
XML
<bean id="loginAction" class="com.something.LoginAction" scope="request"/>
The Spring container creates a new instance of the LoginAction bean by using the
loginAction bean
definition for each and every HTTP request. That is, the
loginAction bean is scoped at the HTTP request
level. You can change the internal
state of the instance that is created as much as you want, because other
instances
created from the same loginAction bean definition do not see these changes in state.
They are
particular to an individual request. When the request completes processing, the
bean that is scoped to the
request is discarded.
Java Kotlin
JAVA
@RequestScope
@Component
public class LoginAction {
// ...
}
Session Scope
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 59/373
6/10/22, 3:58 PM Core Technologies
XML
<bean id="userPreferences" class="com.something.UserPreferences" scope="session"/>
The Spring container creates a new instance of the UserPreferences bean by using the
userPreferences
bean definition for the lifetime of a single HTTP Session . In other
words, the userPreferences bean is
effectively scoped at the HTTP Session level. As
with request-scoped beans, you can change the internal
state of the instance that is
created as much as you want, knowing that other HTTP Session instances
that are also
using instances created from the same userPreferences bean definition do not see these
changes in state, because they are particular to an individual HTTP Session . When the
HTTP Session is
eventually discarded, the bean that is scoped to that particular HTTP
Session is also discarded.
When using annotation-driven components or Java configuration, you can use the
@SessionScope
annotation to assign a component to the session scope.
Java Kotlin
JAVA
@SessionScope
@Component
public class UserPreferences {
// ...
}
Application Scope
Consider the following XML configuration for a bean definition:
XML
<bean id="appPreferences" class="com.something.AppPreferences" scope="application"/>
The Spring container creates a new instance of the AppPreferences bean by using the
appPreferences
bean definition once for the entire web application. That is, the
appPreferences bean is scoped at the
ServletContext level and stored as a regular
ServletContext attribute. This is somewhat similar to a
Spring singleton bean but
differs in two important ways: It is a singleton per ServletContext , not per
Spring
ApplicationContext (for which there may be several in any given web application),
and it is
actually exposed and therefore visible as a ServletContext attribute.
When using annotation-driven components or Java configuration, you can use the
@ApplicationScope
annotation to assign a component to the application scope. The
following example shows how to do so:
Java Kotlin
JAVA
@ApplicationScope
@Component
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 60/373
6/10/22, 3:58 PM Core Technologies
public class AppPreferences {
// ...
}
WebSocket Scope
WebSocket scope is associated with the lifecycle of a WebSocket session and applies to
STOMP over
WebSocket applications, see
WebSocket scope for more details.
You may also use <aop:scoped-proxy/> between beans that are scoped as singleton ,
with the
reference then going through an intermediate proxy that is serializable
and therefore able to re-
obtain the target singleton bean on deserialization.
Also, scoped proxies are not the only way to access beans from shorter scopes in a
lifecycle-safe
fashion. You may also declare your injection point (that is, the
constructor or setter argument or
autowired field) as ObjectFactory<MyTargetBean> ,
allowing for a getObject() call to retrieve the
current instance on demand every
time it is needed — without holding on to the instance or storing it
separately.
The JSR-330 variant of this is called Provider and is used with a Provider<MyTargetBean>
declaration and a corresponding get() call for every retrieval attempt.
See here for more details on
JSR-330 overall.
The configuration in the following example is only one line, but it is important to
understand the “why” as
well as the “how” behind it:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 61/373
6/10/22, 3:58 PM Core Technologies
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:scoped-proxy/> 1
</bean>
<!-- a singleton-scoped bean injected with a proxy to the above bean -->
</bean>
</beans>
To create such a proxy, you insert a child <aop:scoped-proxy/> element into a scoped
bean definition
(see Choosing the Type of Proxy to Create and
XML Schema-based configuration).
Why do definitions of
beans scoped at the request , session and custom-scope
levels require the <aop:scoped-proxy/>
element?
Consider the following singleton bean definition and contrast it with
what you need to define for
the aforementioned scopes (note that the following
userPreferences bean definition as it stands is
incomplete):
XML
<bean id="userPreferences" class="com.something.UserPreferences" scope="session"/>
In the preceding example, the singleton bean ( userManager ) is injected with a reference
to the HTTP
Session -scoped bean ( userPreferences ). The salient point here is that the
userManager bean is a
singleton: it is instantiated exactly once per
container, and its dependencies (in this case only one, the
userPreferences bean) are
also injected only once. This means that the userManager bean operates only
on the
exact same userPreferences object (that is, the one with which it was originally injected).
This is not the behavior you want when injecting a shorter-lived scoped bean into a
longer-lived scoped
bean (for example, injecting an HTTP Session -scoped collaborating
bean as a dependency into singleton
bean). Rather, you need a single userManager
object, and, for the lifetime of an HTTP Session , you need
a userPreferences object
that is specific to the HTTP Session . Thus, the container creates an object that
exposes the exact same public interface as the UserPreferences class (ideally an
object that is a
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 62/373
6/10/22, 3:58 PM Core Technologies
Thus, you need the following (correct and complete) configuration when injecting
request- and session-
scoped beans into collaborating objects, as the following example
shows:
XML
<bean id="userPreferences" class="com.something.UserPreferences" scope="session">
<aop:scoped-proxy/>
</bean>
By default, when the Spring container creates a proxy for a bean that is marked up with
the <aop:scoped-
proxy/> element, a CGLIB-based class proxy is created.
CGLIB proxies intercept only public method calls! Do not call non-public methods
on such a proxy.
They are not delegated to the actual scoped target object.
Alternatively, you can configure the Spring container to create standard JDK
interface-based proxies for
such scoped beans, by specifying false for the value of
the proxy-target-class attribute of the
<aop:scoped-proxy/> element. Using JDK
interface-based proxies means that you do not need additional
libraries in your
application classpath to affect such proxying. However, it also means that the class of
the
scoped bean must implement at least one interface and that all collaborators
into which the scoped bean
is injected must reference the bean through one of its
interfaces. The following example shows a proxy
based on an interface:
XML
<!-- DefaultUserPreferences implements the UserPreferences interface -->
<aop:scoped-proxy proxy-target-class="false"/>
</bean>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 63/373
6/10/22, 3:58 PM Core Technologies
The Scope interface has four methods to get objects from the scope, remove them from
the scope, and
let them be destroyed.
The session scope implementation, for example, returns the session-scoped bean (if it
does not exist, the
method returns a new instance of the bean, after having bound it to
the session for future reference). The
following method returns the object from the
underlying scope:
Java Kotlin
JAVA
Object get(String name, ObjectFactory<?> objectFactory)
The session scope implementation, for example, removes the session-scoped bean from the
underlying
session. The object should be returned, but you can return null if the
object with the specified name is
not found. The following method removes the object from
the underlying scope:
Java Kotlin
JAVA
Object remove(String name)
The following method registers a callback that the scope should invoke when it is
destroyed or when the
specified object in the scope is destroyed:
Java Kotlin
JAVA
void registerDestructionCallback(String name, Runnable destructionCallback)
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 64/373
6/10/22, 3:58 PM Core Technologies
The following method obtains the conversation identifier for the underlying scope:
Java Kotlin
JAVA
String getConversationId()
This identifier is different for each scope. For a session scoped implementation, this
identifier can be the
session identifier.
Java Kotlin
JAVA
void registerScope(String scopeName, Scope scope);
The first argument to the registerScope(..) method is the unique name associated with
a scope.
Examples of such names in the Spring container itself are singleton and
prototype . The second
argument to the registerScope(..) method is an actual instance
of the custom Scope implementation
that you wish to register and use.
Suppose that you write your custom Scope implementation, and then register it as shown
in the next
example.
The next example uses SimpleThreadScope , which is included with Spring but is not
registered by
default. The instructions would be the same for your own custom Scope
implementations.
Java Kotlin
JAVA
Scope threadScope = new SimpleThreadScope();
beanFactory.registerScope("thread", threadScope);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 65/373
6/10/22, 3:58 PM Core Technologies
You can then create bean definitions that adhere to the scoping rules of your custom
Scope , as follows:
XML
<bean id="..." class="..." scope="thread">
With a custom Scope implementation, you are not limited to programmatic registration
of the scope. You
can also do the Scope registration declaratively, by using the
CustomScopeConfigurer class, as the
following example shows:
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="thread">
<bean class="org.springframework.context.support.SimpleThreadScope"/>
</entry>
</map>
</property>
</bean>
<aop:scoped-proxy/>
</bean>
</bean>
</beans>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 66/373
6/10/22, 3:58 PM Core Technologies
Lifecycle Callbacks
ApplicationContextAware and BeanNameAware
The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best
practice
for receiving lifecycle callbacks in a modern Spring application. Using these
annotations means that
your beans are not coupled to Spring-specific interfaces.
For details, see Using @PostConstruct and
@PreDestroy .
If you do not want to use the JSR-250 annotations but you still want to remove
coupling, consider
init-method and destroy-method bean definition metadata.
Initialization Callbacks
The org.springframework.beans.factory.InitializingBean interface lets a bean
perform initialization
work after the container has set all necessary properties on the
bean. The InitializingBean interface
specifies a single method:
JAVA
void afterPropertiesSet() throws Exception;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 67/373
6/10/22, 3:58 PM Core Technologies
XML
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
Java Kotlin
JAVA
public class ExampleBean {
}
}
The preceding example has almost exactly the same effect as the following example
(which consists of two
listings):
XML
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
Java Kotlin
JAVA
public class AnotherExampleBean implements InitializingBean {
@Override
}
}
However, the first of the two preceding examples does not couple the code to Spring.
Destruction Callbacks
Implementing the org.springframework.beans.factory.DisposableBean interface lets a
bean get a
callback when the container that contains it is destroyed. The
DisposableBean interface specifies a single
method:
JAVA
void destroy() throws Exception;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 68/373
6/10/22, 3:58 PM Core Technologies
We recommend that you do not use the DisposableBean callback interface, because it
unnecessarily
couples the code to Spring. Alternatively, we suggest using
the @PreDestroy annotation or
specifying a
generic method that is supported by bean definitions. With XML-based
configuration metadata, you can
use the destroy-method attribute on the <bean/> .
With Java configuration, you can use the
destroyMethod attribute of @Bean . See
Receiving Lifecycle Callbacks. Consider the following definition:
XML
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
Java Kotlin
JAVA
public class ExampleBean {
}
}
The preceding definition has almost exactly the same effect as the following definition:
XML
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
Java Kotlin
JAVA
public class AnotherExampleBean implements DisposableBean {
@Override
}
}
However, the first of the two preceding definitions does not couple the code to Spring.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 69/373
6/10/22, 3:58 PM Core Technologies
When you write initialization and destroy method callbacks that do not use the
Spring-specific
InitializingBean and DisposableBean callback interfaces, you
typically write methods with names such
as init() , initialize() , dispose() , and so
on. Ideally, the names of such lifecycle callback methods
are standardized across a
project so that all developers use the same method names and ensure
consistency.
You can configure the Spring container to “look” for named initialization and destroy
callback method
names on every bean. This means that you, as an application
developer, can write your application classes
and use an initialization callback called
init() , without having to configure an init-method="init"
attribute with each bean
definition. The Spring IoC container calls that method when the bean is created
(and in
accordance with the standard lifecycle callback contract described previously). This feature also
enforces a consistent naming convention for
initialization and destroy method callbacks.
Suppose that your initialization callback methods are named init() and your destroy
callback methods
are named destroy() . Your class then resembles the class in the
following example:
Java Kotlin
JAVA
public class DefaultBlogService implements BlogService {
if (this.blogDao == null) {
throw new IllegalStateException("The [blogDao] property must be set.");
}
}
You could then use that class in a bean resembling the following:
XML
<beans default-init-method="init">
</bean>
</beans>
You can configure destroy method callbacks similarly (in XML, that is) by using the
default-destroy-
method attribute on the top-level <beans/> element.
Where existing bean classes already have callback methods that are named at variance
with the
convention, you can override the default by specifying (in XML, that is) the
method name by using the
init-method and destroy-method attributes of the <bean/>
itself.
If multiple lifecycle mechanisms are configured for a bean and each mechanism is
configured with a
different method name, then each configured method is run in the
order listed after this note.
However, if the same method name is configured — for example,
init() for an initialization
method — for more than one of these lifecycle mechanisms,
that method is run once, as explained in
the
preceding section.
Multiple lifecycle mechanisms configured for the same bean, with different
initialization methods, are
called as follows:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 71/373
6/10/22, 3:58 PM Core Technologies
JAVA
public interface Lifecycle {
void start();
void stop();
boolean isRunning();
Any Spring-managed object may implement the Lifecycle interface. Then, when the
ApplicationContext itself receives start and stop signals (for example, for a stop/restart
scenario at
runtime), it cascades those calls to all Lifecycle implementations
defined within that context. It does this
by delegating to a LifecycleProcessor , shown
in the following listing:
JAVA
public interface LifecycleProcessor extends Lifecycle {
void onRefresh();
void onClose();
Also, please note that stop notifications are not guaranteed to come before destruction.
On regular
shutdown, all Lifecycle beans first receive a stop notification before
the general destruction
callbacks are being propagated. However, on hot refresh during a
context’s lifetime or on stopped
refresh attempts, only destroy methods are called.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 72/373
6/10/22, 3:58 PM Core Technologies
JAVA
public interface Phased {
int getPhase();
JAVA
public interface SmartLifecycle extends Lifecycle, Phased {
boolean isAutoStartup();
When starting, the objects with the lowest phase start first. When stopping, the
reverse order is followed.
Therefore, an object that implements SmartLifecycle and
whose getPhase() method returns
Integer.MIN_VALUE would be among the first to start
and the last to stop. At the other end of the
spectrum, a phase value of
Integer.MAX_VALUE would indicate that the object should be started last and
stopped
first (likely because it depends on other processes to be running). When considering the
phase
value, it is also important to know that the default phase for any “normal”
Lifecycle object that does not
implement SmartLifecycle is 0 . Therefore, any
negative phase value indicates that an object should
start before those standard
components (and stop after them). The reverse is true for any positive phase
value.
XML
<bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor"
<!-- timeout value in milliseconds -->
</bean>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 73/373
6/10/22, 3:58 PM Core Technologies
As mentioned earlier, the LifecycleProcessor interface defines callback methods for the
refreshing and
closing of the context as well. The latter drives the shutdown
process as if stop() had been called
explicitly, but it happens when the context is
closing. The 'refresh' callback, on the other hand, enables
another feature of
SmartLifecycle beans. When the context is refreshed (after all objects have been
instantiated and initialized), that callback is invoked. At that point, the
default lifecycle processor checks
the boolean value returned by each
SmartLifecycle object’s isAutoStartup() method. If true , that
object is
started at that point rather than waiting for an explicit invocation of the context’s or
its own
start() method (unlike the context refresh, the context start does not happen
automatically for a
standard context implementation). The phase value and any
“depends-on” relationships determine the
startup order as described earlier.
Java Kotlin
JAVA
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
ctx.registerShutdownHook();
// main method exits, hook is called prior to the app shutting down...
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 74/373
6/10/22, 3:58 PM Core Technologies
JAVA
public interface ApplicationContextAware {
Thus, beans can programmatically manipulate the ApplicationContext that created them,
through the
ApplicationContext interface or by casting the reference to a known
subclass of this interface (such as
ConfigurableApplicationContext , which exposes
additional functionality). One use would be the
programmatic retrieval of other beans.
Sometimes this capability is useful. However, in general, you
should avoid it, because
it couples the code to Spring and does not follow the Inversion of Control style,
where collaborators are provided to beans as properties. Other methods of the
ApplicationContext
provide access to file resources, publishing application events,
and accessing a MessageSource . These
additional features are described in
Additional Capabilities of the ApplicationContext .
JAVA
public interface BeanNameAware {
The callback is invoked after population of normal bean properties but before an
initialization callback
such as InitializingBean.afterPropertiesSet() or a custom
init-method.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 75/373
6/10/22, 3:58 PM Core Technologies
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 76/373
6/10/22, 3:58 PM Core Technologies
Note again that using these interfaces ties your code to the Spring API and does not
follow the Inversion of
Control style. As a result, we recommend them for infrastructure
beans that require programmatic access
to the container.
XML
<bean id="inheritedTestBean" abstract="true"
class="org.springframework.beans.TestBean">
</bean>
<bean id="inheritsWithDifferentClass"
class="org.springframework.beans.DerivedTestBean"
parent="inheritedTestBean" init-method="initialize"> 1
<!-- the age property value of 1 will be inherited from parent -->
</bean>
A child bean definition uses the bean class from the parent definition if none is
specified but can also
override it. In the latter case, the child bean class must be
compatible with the parent (that is, it must
accept the parent’s property values).
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 77/373
6/10/22, 3:58 PM Core Technologies
A child bean definition inherits scope, constructor argument values, property values, and
method
overrides from the parent, with the option to add new values. Any scope, initialization
method, destroy
method, or static factory method settings that you specify
override the corresponding parent settings.
The remaining settings are always taken from the child definition: depends on,
autowire mode,
dependency check, singleton, and lazy init.
The preceding example explicitly marks the parent bean definition as abstract by using
the abstract
attribute. If the parent definition does not specify a class, explicitly
marking the parent bean definition as
abstract is required, as the following example
shows:
XML
<bean id="inheritedTestBeanWithoutClass" abstract="true">
</bean>
parent="inheritedTestBeanWithoutClass" init-method="initialize">
<!-- age will inherit the value of 1 from the parent bean definition-->
</bean>
The parent bean cannot be instantiated on its own because it is incomplete, and it is
also explicitly marked
as abstract . When a definition is abstract , it is
usable only as a pure template bean definition that
serves as a parent definition for
child definitions. Trying to use such an abstract parent bean on its own,
by referring
to it as a ref property of another bean or doing an explicit getBean() call with the
parent
bean ID returns an error. Similarly, the container’s internal
preInstantiateSingletons() method ignores
bean definitions that are defined as
abstract.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 78/373
6/10/22, 3:58 PM Core Technologies
The BeanPostProcessor interface defines callback methods that you can implement to
provide your own
(or override the container’s default) instantiation logic, dependency
resolution logic, and so forth. If you
want to implement some custom logic after the
Spring container finishes instantiating, configuring, and
initializing a bean, you can
plug in one or more custom BeanPostProcessor implementations.
You can configure multiple BeanPostProcessor instances, and you can control the order
in which these
BeanPostProcessor instances run by setting the order property.
You can set this property only if the
BeanPostProcessor implements the Ordered
interface. If you write your own BeanPostProcessor , you
should consider implementing
the Ordered interface, too. For further details, see the javadoc of the
BeanPostProcessor
and Ordered interfaces. See also the note
on programmatic
registration of
BeanPostProcessor instances.
To change the actual bean definition (that is, the blueprint that defines the bean),
you instead need
to use a BeanFactoryPostProcessor , as described in
Customizing Configuration Metadata with a
BeanFactoryPostProcessor .
org.springframework.beans.factory.config.BeanPostProcessor
interface, clearly indicating the post-
processor nature of that bean. Otherwise, the
ApplicationContext cannot autodetect it by type before
fully creating it.
Since a BeanPostProcessor needs to be instantiated early in order to apply to the
initialization of other beans in the context, this early type detection is critical.
For any such bean, you should see an informational log message: Bean someBean is not
eligible
for getting processed by all BeanPostProcessor interfaces (for example: not
eligible for
auto-proxying) .
The following examples show how to write, register, and use BeanPostProcessor instances
in an
ApplicationContext .
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 80/373
6/10/22, 3:58 PM Core Technologies
The following listing shows the custom BeanPostProcessor implementation class definition:
Java Kotlin
JAVA
package scripting;
import org.springframework.beans.factory.config.BeanPostProcessor;
return bean;
}
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang
https://www.springframework.org/schema/lang/spring-lang.xsd">
<lang:groovy id="messenger"
script-source="classpath:org/springframework/scripting/groovy/Messenger.groovy">
</lang:groovy>
<!--
-->
<bean class="scripting.InstantiationTracingBeanPostProcessor"/>
</beans>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 81/373
6/10/22, 3:58 PM Core Technologies
The following Java application runs the preceding code and configuration:
Java Kotlin
JAVA
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scripting.Messenger;
System.out.println(messenger);
org.springframework.scripting.groovy.GroovyMessenger@272961
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 82/373
6/10/22, 3:58 PM Core Technologies
You can configure multiple BeanFactoryPostProcessor instances, and you can control the order in
which
these BeanFactoryPostProcessor instances run by setting the order property.
However, you can only set
this property if the BeanFactoryPostProcessor implements the
Ordered interface. If you write your own
BeanFactoryPostProcessor , you should
consider implementing the Ordered interface, too. See the
javadoc of the
BeanFactoryPostProcessor
and Ordered interfaces for more details.
If you want to change the actual bean instances (that is, the objects that are created
from the
configuration metadata), then you instead need to use a BeanPostProcessor
(described earlier in
Customizing Beans by Using a BeanPostProcessor ). While it is technically possible
to work with bean
instances within a BeanFactoryPostProcessor (for example, by using
BeanFactory.getBean() ),
doing so causes premature bean instantiation, violating the
standard container lifecycle. This may
cause negative side effects, such as bypassing
bean post processing.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 83/373
6/10/22, 3:58 PM Core Technologies
XML
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
</bean>
class="org.apache.commons.dbcp.BasicDataSource">
</bean>
The example shows properties configured from an external Properties file. At runtime,
a
PropertySourcesPlaceholderConfigurer is applied to the metadata that replaces some
properties of the
DataSource. The values to replace are specified as placeholders of the
form ${property-name} , which
follows the Ant and log4j and JSP EL style.
The actual values come from another file in the standard Java Properties format:
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
Therefore, the ${jdbc.username} string is replaced at runtime with the value, 'sa', and
the same applies
for other placeholder values that match keys in the properties file.
The
PropertySourcesPlaceholderConfigurer checks for placeholders in most properties and
attributes of a
bean definition. Furthermore, you can customize the placeholder prefix and suffix.
With the context namespace introduced in Spring 2.5, you can configure property placeholders
with a
dedicated configuration element. You can provide one or more locations as a
comma-separated list in the
location attribute, as the following example shows:
XML
<context:property-placeholder location="classpath:com/something/jdbc.properties"/>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 84/373
6/10/22, 3:58 PM Core Technologies
XML
<bean class="org.springframework.beans.factory.config.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<value>classpath:com/something/strategy.properties</value>
</property>
<property name="properties">
<value>custom.strategy.class=com.something.DefaultStrategy</value>
</property>
</bean>
If the class cannot be resolved at runtime to a valid class, resolution of the bean
fails when it is about
to be created, which is during the preInstantiateSingletons()
phase of an ApplicationContext for a
non-lazy-init bean.
Note that the bean definition is not aware of being overridden, so it is not
immediately obvious from the
XML definition file that the override configurer is being
used. In case of multiple
PropertyOverrideConfigurer instances that define different
values for the same bean property, the last
one wins, due to the overriding mechanism.
beanName.property=value
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 85/373
6/10/22, 3:58 PM Core Technologies
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql:mydb
This example file can be used with a container definition that contains a bean called
dataSource that has
driver and url properties.
Compound property names are also supported, as long as every component of the path
except the final
property being overridden is already non-null (presumably initialized
by the constructors). In the following
example, the sammy property of the bob property of the fred property of the tom bean
is set to the
scalar value 123 :
tom.fred.bob.sammy=123
Specified override values are always literal values. They are not translated into
bean references. This
convention also applies when the original value in the XML bean
definition specifies a bean
reference.
XML
<context:property-override location="classpath:override.properties"/>
The FactoryBean interface is a point of pluggability into the Spring IoC container’s
instantiation logic. If
you have complex initialization code that is better expressed in
Java as opposed to a (potentially) verbose
amount of XML, you can create your own
FactoryBean , write the complex initialization inside that class,
and then plug your
custom FactoryBean into the container.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 86/373
6/10/22, 3:58 PM Core Technologies
Class<?> getObjectType() : Returns the object type returned by the getObject() method
or null if
the type is not known in advance.
The FactoryBean concept and interface are used in a number of places within the Spring
Framework.
More than 50 implementations of the FactoryBean interface ship with Spring
itself.
When you need to ask a container for an actual FactoryBean instance itself instead of
the bean it
produces, prefix the bean’s id with the ampersand symbol ( & ) when
calling the getBean() method of
the ApplicationContext . So, for a given FactoryBean
with an id of myBean , invoking
getBean("myBean") on the container returns the
product of the FactoryBean , whereas invoking
getBean("&myBean") returns the
FactoryBean instance itself.
No matter the choice, Spring can accommodate both styles and even mix them together.
It is worth
pointing out that through its JavaConfig option, Spring lets
annotations be used in a non-invasive
way, without touching the target components
source code and that, in terms of tooling, all
configuration styles are supported by the
Spring Tools for Eclipse.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 87/373
6/10/22, 3:58 PM Core Technologies
Annotation injection is performed before XML injection. Thus, the XML configuration
overrides the
annotations for properties wired through both approaches.
As always, you can register the post-processors as individual bean definitions, but they
can also be
implicitly registered by including the following tag in an XML-based Spring
configuration (notice the
inclusion of the context namespace):
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
ConfigurationClassPostProcessor
AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
PersistenceAnnotationBeanPostProcessor
EventListenerMethodProcessor
1.9.1. @Required
The @Required annotation applies to bean property setter methods, as in the following
example:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 88/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
public class SimpleMovieLister {
@Required
this.movieFinder = movieFinder;
// ...
}
This annotation indicates that the affected bean property must be populated at
configuration time,
through an explicit property value in a bean definition or through
autowiring. The container throws an
exception if the affected bean property has not been
populated. This allows for eager and explicit failure,
avoiding NullPointerException
instances or the like later on. We still recommend that you put assertions
into the
bean class itself (for example, into an init method). Doing so enforces those required
references
and values even when you use the class outside of a container.
The RequiredAnnotationBeanPostProcessor
must be registered as a bean to enable support for the
@Required annotation.
JSR 330’s @Inject annotation can be used in place of Spring’s @Autowired annotation in the
examples included in this section. See here for more details.
You can apply the @Autowired annotation to constructors, as the following example shows:
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 89/373
6/10/22, 3:58 PM Core Technologies
JAVA
public class MovieRecommender {
@Autowired
this.customerPreferenceDao = customerPreferenceDao;
// ...
}
You can also apply the @Autowired annotation to traditional setter methods,
as the following example
shows:
Java Kotlin
JAVA
public class SimpleMovieLister {
@Autowired
this.movieFinder = movieFinder;
// ...
}
You can also apply the annotation to methods with arbitrary names and multiple
arguments, as the
following example shows:
Java Kotlin
JAVA
public class MovieRecommender {
@Autowired
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 90/373
6/10/22, 3:58 PM Core Technologies
CustomerPreferenceDao customerPreferenceDao) {
this.movieCatalog = movieCatalog;
this.customerPreferenceDao = customerPreferenceDao;
// ...
}
You can apply @Autowired to fields as well and even mix it with constructors, as the
following example
shows:
Java Kotlin
JAVA
public class MovieRecommender {
@Autowired
@Autowired
this.customerPreferenceDao = customerPreferenceDao;
// ...
}
Make sure that your target components (for example, MovieCatalog or CustomerPreferenceDao )
are
consistently declared by the type that you use for your @Autowired -annotated
injection points.
Otherwise, injection may fail due to a "no type match found" error at runtime.
For XML-defined beans or component classes found via classpath scanning, the container
usually
knows the concrete type up front. However, for @Bean factory methods, you need
to make sure that
the declared return type is sufficiently expressive. For components
that implement several interfaces
or for components potentially referred to by their
implementation type, consider declaring the most
specific return type on your factory
method (at least as specific as required by the injection points
referring to your bean).
You can also instruct Spring to provide all beans of a particular type from the
ApplicationContext by
adding the @Autowired annotation to a field or method that
expects an array of that type, as the following
example shows:
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 91/373
6/10/22, 3:58 PM Core Technologies
JAVA
public class MovieRecommender {
@Autowired
// ...
}
The same applies for typed collections, as the following example shows:
Java Kotlin
JAVA
public class MovieRecommender {
@Autowired
this.movieCatalogs = movieCatalogs;
// ...
}
You can declare the @Order annotation at the target class level and on @Bean methods,
potentially
for individual bean definitions (in case of multiple definitions that
use the same bean class). @Order
values may influence priorities at injection points,
but be aware that they do not influence singleton
startup order, which is an
orthogonal concern determined by dependency relationships and
@DependsOn declarations.
Even typed Map instances can be autowired as long as the expected key type is String .
The map values
contain all beans of the expected type, and the keys contain the
corresponding bean names, as the
following example shows:
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 92/373
6/10/22, 3:58 PM Core Technologies
JAVA
public class MovieRecommender {
@Autowired
this.movieCatalogs = movieCatalogs;
// ...
}
By default, autowiring fails when no matching candidate beans are available for a given
injection point. In
the case of a declared array, collection, or map, at least one
matching element is expected.
The default behavior is to treat annotated methods and fields as indicating required
dependencies. You
can change this behavior as demonstrated in the following example,
enabling the framework to skip a
non-satisfiable injection point through marking it as
non-required (i.e., by setting the required attribute
in @Autowired to false ):
Java Kotlin
JAVA
public class SimpleMovieLister {
@Autowired(required = false)
this.movieFinder = movieFinder;
// ...
}
A non-required method will not be called at all if its dependency (or one of its
dependencies, in case of
multiple arguments) is not available. A non-required field will
not get populated at all in such cases, leaving
its default value in place.
Injected constructor and factory method arguments are a special case since the required
attribute in
@Autowired has a somewhat different meaning due to Spring’s constructor
resolution algorithm that may
potentially deal with multiple constructors. Constructor
and factory method arguments are effectively
required by default but with a few special
rules in a single-constructor scenario, such as multi-element
injection points (arrays,
collections, maps) resolving to empty instances if no matching beans are available.
This
allows for a common implementation pattern where all dependencies can be declared in a
unique
multi-argument constructor — for example, declared as a single public constructor
without an
@Autowired annotation.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 93/373
6/10/22, 3:58 PM Core Technologies
Only one constructor of any given bean class may declare @Autowired with the required
attribute
set to true , indicating the constructor to autowire when used as a Spring
bean. As a consequence, if
the required attribute is left at its default value true ,
only a single constructor may be annotated
with @Autowired . If multiple constructors
declare the annotation, they will all have to declare
required=false in order to be
considered as candidates for autowiring (analogous to
autowire=constructor in XML).
The constructor with the greatest number of dependencies that can
be satisfied by matching
beans in the Spring container will be chosen. If none of the candidates can
be satisfied,
then a primary/default constructor (if present) will be used. Similarly, if a class
declares
multiple constructors but none of them is annotated with @Autowired , then a
primary/default
constructor (if present) will be used. If a class only declares a single
constructor to begin with, it will
always be used, even if not annotated. Note that an
annotated constructor does not have to be
public.
JAVA
public class SimpleMovieLister {
@Autowired
...
}
}
As of Spring Framework 5.0, you can also use a @Nullable annotation (of any kind
in any package — for
example, javax.annotation.Nullable from JSR-305) or just leverage
Kotlin builtin null-safety support:
Java Kotlin
JAVA
public class SimpleMovieLister {
@Autowired
...
}
}
You can also use for interfaces that are well-known resolvable
dependencies: BeanFactory ,
@Autowired
ApplicationContext , Environment , ResourceLoader ,
ApplicationEventPublisher , and MessageSource .
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 94/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
public class MovieRecommender {
@Autowired
public MovieRecommender() {
// ...
}
Java Kotlin
JAVA
@Configuration
@Bean
@Primary
@Bean
// ...
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 95/373
6/10/22, 3:58 PM Core Technologies
With the preceding configuration, the following MovieRecommender is autowired with the
firstMovieCatalog :
Java Kotlin
JAVA
public class MovieRecommender {
@Autowired
// ...
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</bean>
<bean class="example.SimpleMovieCatalog">
</bean>
</beans>
Java Kotlin
JAVA
public class MovieRecommender {
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 96/373
6/10/22, 3:58 PM Core Technologies
@Autowired
@Qualifier("main")
// ...
}
You can also specify the @Qualifier annotation on individual constructor arguments or
method
parameters, as shown in the following example:
Java Kotlin
JAVA
public class MovieRecommender {
@Autowired
CustomerPreferenceDao customerPreferenceDao) {
this.movieCatalog = movieCatalog;
this.customerPreferenceDao = customerPreferenceDao;
// ...
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean class="example.SimpleMovieCatalog">
<qualifier value="main"/> 1
</bean>
<bean class="example.SimpleMovieCatalog">
<qualifier value="action"/> 2
</bean>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 97/373
6/10/22, 3:58 PM Core Technologies
</beans>
1 The bean with the main qualifier value is wired with the constructor argument that
is qualified with the same value.
2 The bean with the action qualifier value is wired with the constructor argument that
is qualified with the same value.
For a fallback match, the bean name is considered a default qualifier value. Thus, you
can define the bean
with an id of main instead of the nested qualifier element, leading
to the same matching result.
However, although you can use this convention to refer to
specific beans by name, @Autowired is
fundamentally about type-driven injection with
optional semantic qualifiers. This means that qualifier
values, even with the bean name
fallback, always have narrowing semantics within the set of type
matches. They do not
semantically express a reference to a unique bean id . Good qualifier values are
main
or EMEA or persistent , expressing characteristics of a specific component that are
independent
from the bean id , which may be auto-generated in case of an anonymous bean
definition such as the
one in the preceding example.
Letting qualifier values select against target bean names, within the type-matching
candidates, does
not require a @Qualifier annotation at the injection point.
If there is no other resolution indicator
(such as a qualifier or a primary marker),
for a non-unique dependency situation, Spring matches the
injection point name
(that is, the field name or parameter name) against the target bean names and
chooses the
same-named candidate, if any.
For beans that are themselves defined as a collection, Map , or array type, @Resource
is a fine solution,
referring to the specific collection or array bean by unique name.
That said, as of 4.3, you can match
collection, Map , and array types through Spring’s
@Autowired type matching algorithm as well, as long as
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 98/373
6/10/22, 3:58 PM Core Technologies
As of 4.3, @Autowired also considers self references for injection (that is, references
back to the bean that
is currently injected). Note that self injection is a fallback.
Regular dependencies on other components
always have precedence. In that sense, self
references do not participate in regular candidate selection
and are therefore in
particular never primary. On the contrary, they always end up as lowest precedence.
In practice, you should use self references as a last resort only (for example, for
calling other methods on
the same instance through the bean’s transactional proxy).
Consider factoring out the affected methods to
a separate delegate bean in such a scenario.
Alternatively, you can use @Resource , which may obtain a
proxy back to the current bean
by its unique name.
Trying to inject the results from @Bean methods on the same configuration class is
effectively a self-
reference scenario as well. Either lazily resolve such references
in the method signature where it is
actually needed (as opposed to an autowired field
in the configuration class) or declare the affected
@Bean methods as static ,
decoupling them from the containing configuration class instance and
its lifecycle.
Otherwise, such beans are only considered in the fallback phase, with matching beans
on
other configuration classes selected as primary candidates instead (if available).
You can create your own custom qualifier annotations. To do so, define an annotation and
provide the
@Qualifier annotation within your definition, as the following example shows:
Java Kotlin
JAVA
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Genre {
String value();
Then you can provide the custom qualifier on autowired fields and parameters, as the
following example
shows:
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 99/373
6/10/22, 3:58 PM Core Technologies
JAVA
public class MovieRecommender {
@Autowired
@Genre("Action")
@Autowired
this.comedyCatalog = comedyCatalog;
// ...
}
Next, you can provide the information for the candidate bean definitions. You can add
<qualifier/> tags
as sub-elements of the <bean/> tag and then specify the type and
value to match your custom
qualifier annotations. The type is matched against the
fully-qualified class name of the annotation.
Alternately, as a convenience if no risk of
conflicting names exists, you can use the short class name. The
following example
demonstrates both approaches:
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean class="example.SimpleMovieCatalog">
</bean>
<bean class="example.SimpleMovieCatalog">
</bean>
</beans>
In Classpath Scanning and Managed Components, you can see an annotation-based alternative to
providing the qualifier metadata in XML. Specifically, see Providing Qualifier Metadata with Annotations.
In some cases, using an annotation without a value may suffice. This can be
useful when the annotation
serves a more generic purpose and can be applied across
several different types of dependencies. For
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 100/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Offline {
Then add the annotation to the field or property to be autowired, as shown in the
following example:
Java Kotlin
JAVA
public class MovieRecommender {
@Autowired
@Offline 1
// ...
}
Now the bean definition only needs a qualifier type , as shown in the following example:
XML
<bean class="example.SimpleMovieCatalog">
<qualifier type="Offline"/> 1
</bean>
You can also define custom qualifier annotations that accept named attributes in
addition to or instead of
the simple value attribute. If multiple attribute values are
then specified on a field or parameter to be
autowired, a bean definition must match
all such attribute values to be considered an autowire candidate.
As an example,
consider the following annotation definition:
Java Kotlin
JAVA
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MovieQualifier {
String genre();
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 101/373
6/10/22, 3:58 PM Core Technologies
Format format();
Java Kotlin
JAVA
public enum Format {
The fields to be autowired are annotated with the custom qualifier and include values
for both attributes:
genre and format , as the following example shows:
Java Kotlin
JAVA
public class MovieRecommender {
@Autowired
@MovieQualifier(format=Format.VHS, genre="Action")
@Autowired
@MovieQualifier(format=Format.VHS, genre="Comedy")
@Autowired
@MovieQualifier(format=Format.DVD, genre="Action")
@Autowired
@MovieQualifier(format=Format.BLURAY, genre="Comedy")
// ...
}
Finally, the bean definitions should contain matching qualifier values. This example
also demonstrates
that you can use bean meta attributes instead of the
<qualifier/> elements. If available, the
<qualifier/> element and its attributes take
precedence, but the autowiring mechanism falls back on
the values provided within the
<meta/> tags if no such qualifier is present, as in the last two bean
definitions in
the following example:
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 102/373
6/10/22, 3:58 PM Core Technologies
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean class="example.SimpleMovieCatalog">
<qualifier type="MovieQualifier">
</qualifier>
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
<qualifier type="MovieQualifier">
</qualifier>
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
</bean>
<bean class="example.SimpleMovieCatalog">
</bean>
</beans>
Java Kotlin
JAVA
@Configuration
@Bean
@Bean
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 103/373
6/10/22, 3:58 PM Core Technologies
Assuming that the preceding beans implement a generic interface, (that is, Store<String> and
Store<Integer> ), you can @Autowire the Store interface and the generic is
used as a qualifier, as the
following example shows:
Java Kotlin
JAVA
@Autowired
private Store<String> s1; // <String> qualifier, injects the stringStore bean
@Autowired
private Store<Integer> s2; // <Integer> qualifier, injects the integerStore bean
Generic qualifiers also apply when autowiring lists, Map instances and arrays. The
following example
autowires a generic List :
Java Kotlin
JAVA
// Inject all Store beans as long as they have an <Integer> generic
@Autowired
private List<Store<Integer>> s;
XML
<bean id="customAutowireConfigurer"
class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer">
<property name="customQualifierTypes">
<set>
<value>example.CustomQualifier</value>
</set>
</property>
</bean>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 104/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
public class SimpleMovieLister {
@Resource(name="myMovieFinder") 1
this.movieFinder = movieFinder;
}
}
If no name is explicitly specified, the default name is derived from the field name or
setter method. In case
of a field, it takes the field name. In case of a setter method,
it takes the bean property name. The
following example is going to have the bean
named movieFinder injected into its setter method:
Java Kotlin
JAVA
public class SimpleMovieLister {
@Resource
this.movieFinder = movieFinder;
}
}
The name provided with the annotation is resolved as a bean name by the
ApplicationContext of
which the CommonAnnotationBeanPostProcessor is aware.
The names can be resolved through JNDI if
you configure Spring’s
SimpleJndiBeanFactory
explicitly. However, we recommend that you rely on
the default behavior and
use Spring’s JNDI lookup capabilities to preserve the level of indirection.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 105/373
6/10/22, 3:58 PM Core Technologies
In the exclusive case of @Resource usage with no explicit name specified, and similar
to @Autowired ,
@Resource finds a primary type match instead of a specific named bean
and resolves well known
resolvable dependencies: the BeanFactory ,
ApplicationContext , ResourceLoader ,
ApplicationEventPublisher , and MessageSource
interfaces.
Thus, in the following example, the customerPreferenceDao field first looks for a bean
named
"customerPreferenceDao" and then falls back to a primary type match for the type
CustomerPreferenceDao :
Java Kotlin
JAVA
public class MovieRecommender {
@Resource
@Resource
public MovieRecommender() {
// ...
}
Java Kotlin
JAVA
@Component
public class MovieRecommender {
this.catalog = catalog;
}
}
Java Kotlin
JAVA
@Configuration
@PropertySource("classpath:application.properties")
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 106/373
6/10/22, 3:58 PM Core Technologies
public class AppConfig { }
JAVA
catalog.name=MovieCatalog
In that case, the catalog parameter and field will be equal to the MovieCatalog value.
A default lenient embedded value resolver is provided by Spring. It will try to resolve the
property value
and if it cannot be resolved, the property name (for example ${catalog.name} )
will be injected as the
value. If you want to maintain strict control over nonexistent
values, you should declare a
PropertySourcesPlaceholderConfigurer bean, as the following
example shows:
Java Kotlin
JAVA
@Configuration
@Bean
}
}
Using the above configuration ensures Spring initialization failure if any ${}
placeholder could not be
resolved. It is also possible to use methods like
setPlaceholderPrefix , setPlaceholderSuffix , or
setValueSeparator to customize
placeholders.
Built-in converter support provided by Spring allows simple type conversion (to Integer
or int for
example) to be automatically handled. Multiple comma-separated values can be
automatically converted
to String array without extra effort.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 107/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Component
public class MovieRecommender {
this.catalog = catalog;
}
}
Java Kotlin
JAVA
@Configuration
@Bean
return conversionService;
}
}
Java Kotlin
JAVA
@Component
public class MovieRecommender {
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 108/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Component
public class MovieRecommender {
public MovieRecommender(
}
}
Java Kotlin
JAVA
public class CachingMovieLister {
@PostConstruct
@PreDestroy
}
}
For details about the effects of combining various lifecycle mechanisms, see
Combining Lifecycle
Mechanisms.
Like @Resource , the @PostConstruct and @PreDestroy annotation types were a part
of the
standard Java libraries from JDK 6 to 8. However, the entire javax.annotation
package got
separated from the core Java modules in JDK 9 and eventually removed in
JDK 11. If needed, the
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 109/373
6/10/22, 3:58 PM Core Technologies
Starting with Spring 3.0, many features provided by the Spring JavaConfig project are
part of the core
Spring Framework. This allows you to define beans using Java rather
than using the traditional XML
files. Take a look at the @Configuration , @Bean ,
@Import , and @DependsOn annotations for
examples of how to use these new features.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 110/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component 1
// ...
}
You can also combine meta-annotations to create “composed annotations”. For example,
the
@RestController annotation from Spring MVC is composed of @Controller and
@ResponseBody .
Java Kotlin
JAVA
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Scope(WebApplicationContext.SCOPE_SESSION)
/**
*/
@AliasFor(annotation = Scope.class)
You can then use @SessionScope without declaring the proxyMode as follows:
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 111/373
6/10/22, 3:58 PM Core Technologies
JAVA
@Service
@SessionScope
You can also override the value for the proxyMode , as the following example shows:
Java Kotlin
JAVA
@Service
@SessionScope(proxyMode = ScopedProxyMode.INTERFACES)
// ...
}
Java Kotlin
JAVA
@Service
this.movieFinder = movieFinder;
}
}
Java Kotlin
JAVA
@Repository
To autodetect these classes and register the corresponding beans, you need to add
@ComponentScan to
your @Configuration class, where the basePackages attribute
is a common parent package for the two
classes. (Alternatively, you can specify a
comma- or semicolon- or space-separated list that includes the
parent package of each class.)
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 112/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Configuration
@ComponentScan(basePackages = "org.example")
// ...
}
For brevity, the preceding example could have used the value attribute of the
annotation (that is,
@ComponentScan("org.example") ).
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.example"/>
</beans>
On JDK 9’s module path (Jigsaw), Spring’s classpath scanning generally works as expected.
However,
make sure that your component classes are exported in your module-info
descriptors. If you expect
Spring to invoke non-public members of your classes, make
sure that they are 'opened' (that is, that
they use an opens declaration instead of an
exports declaration in your module-info descriptor).
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 113/373
6/10/22, 3:58 PM Core Technologies
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 114/373
6/10/22, 3:58 PM Core Technologies
The following example shows the configuration ignoring all @Repository annotations
and using “stub”
repositories instead:
Java Kotlin
JAVA
@Configuration
@ComponentScan(basePackages = "org.example",
excludeFilters = @Filter(Repository.class))
// ...
}
XML
<beans>
<context:component-scan base-package="org.example">
<context:include-filter type="regex"
expression=".*Stub.*Repository"/>
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
</beans>
You can also disable the default filters by setting useDefaultFilters=false on the
annotation or by
providing use-default-filters="false" as an attribute of the
<component-scan/> element. This
effectively disables automatic detection of classes
annotated or meta-annotated with @Component ,
@Repository , @Service , @Controller ,
@RestController , or @Configuration .
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 115/373
6/10/22, 3:58 PM Core Technologies
JAVA
@Component
public class FactoryMethodComponent {
@Bean
@Qualifier("public")
}
}
The preceding class is a Spring component that has application-specific code in its
doWork() method.
However, it also contributes a bean definition that has a factory
method referring to the method
publicInstance() . The @Bean annotation identifies the
factory method and other bean definition
properties, such as a qualifier value through
the @Qualifier annotation. Other method-level annotations
that can be specified are
@Scope , @Lazy , and custom qualifier annotations.
In addition to its role for component initialization, you can also place the @Lazy
annotation on
injection points marked with @Autowired or @Inject . In this context,
it leads to the injection of a
lazy-resolution proxy. However, such a proxy approach
is rather limited. For sophisticated lazy
interactions, in particular in combination
with optional dependencies, we recommend
ObjectProvider<MyTargetBean> instead.
Autowired fields and methods are supported, as previously discussed, with additional
support for
autowiring of @Bean methods. The following example shows how to do so:
Java Kotlin
JAVA
@Component
public class FactoryMethodComponent {
@Bean
@Qualifier("public")
@Bean
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 116/373
6/10/22, 3:58 PM Core Technologies
tb.setSpouse(spouse);
tb.setCountry(country);
return tb;
@Bean
@Bean
@RequestScope
}
}
The example autowires the String method parameter country to the value of the age
property on
another bean named privateInstance . A Spring Expression Language element
defines the value of the
property through the notation #{ <expression> } . For @Value
annotations, an expression resolver is
preconfigured to look for bean names when
resolving expression text.
As of Spring Framework 4.3, you may also declare a factory method parameter of type
InjectionPoint
(or its more specific subclass: DependencyDescriptor ) to
access the requesting injection point that triggers
the creation of the current bean.
Note that this applies only to the actual creation of bean instances, not to
the
injection of existing instances. As a consequence, this feature makes most sense for
beans of
prototype scope. For other scopes, the factory method only ever sees the
injection point that triggered the
creation of a new bean instance in the given scope
(for example, the dependency that triggered the
creation of a lazy singleton bean).
You can use the provided injection point metadata with semantic care in
such scenarios.
The following example shows how to use InjectionPoint :
Java Kotlin
JAVA
@Component
public class FactoryMethodComponent {
@Bean @Scope("prototype")
}
}
The @Bean methods in a regular Spring component are processed differently than their
counterparts
inside a Spring @Configuration class. The difference is that @Component
classes are not enhanced with
CGLIB to intercept the invocation of methods and fields.
CGLIB proxying is the means by which invoking
methods or fields within @Bean methods
in @Configuration classes creates bean metadata references to
collaborating objects.
Such methods are not invoked with normal Java semantics but rather go through
the
container in order to provide the usual lifecycle management and proxying of Spring
beans, even
when referring to other beans through programmatic calls to @Bean methods.
In contrast, invoking a
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 117/373
6/10/22, 3:58 PM Core Technologies
You may declare @Bean methods as static , allowing for them to be called without
creating their
containing configuration class as an instance. This makes particular
sense when defining post-
processor beans (for example, of type BeanFactoryPostProcessor
or BeanPostProcessor ), since
such beans get initialized early in the container
lifecycle and should avoid triggering other parts of
the configuration at that point.
Calls to static methods never get intercepted by the container, not even within
@Bean
@Configuration classes (as described earlier in this section), due to technical
limitations: CGLIB
subclassing can override only non-static methods. As a consequence,
a direct call to another @Bean
method has standard Java semantics, resulting
in an independent instance being returned straight
from the factory method itself.
The Java language visibility of @Bean methods does not have an immediate impact on
the resulting
bean definition in Spring’s container. You can freely declare your
factory methods as you see fit in
non- @Configuration classes and also for static
methods anywhere. However, regular @Bean
methods in @Configuration classes need
to be overridable — that is, they must not be declared as
private or final .
Finally, a single class may hold multiple @Bean methods for the same
bean, as an arrangement of
multiple factory methods to use depending on available
dependencies at runtime. This is the same
algorithm as for choosing the “greediest”
constructor or factory method in other configuration
scenarios: The variant with
the largest number of satisfiable dependencies is picked at construction
time,
analogous to how the container selects between multiple @Autowired constructors.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 118/373
6/10/22, 3:58 PM Core Technologies
If such an annotation contains no name value or for any other detected component
(such as those
discovered by custom filters), the default bean name generator returns
the uncapitalized non-qualified
class name. For example, if the following component
classes were detected, the names would be
myMovieLister and movieFinderImpl :
Java Kotlin
JAVA
@Service("myMovieLister")
// ...
}
Java Kotlin
JAVA
@Repository
// ...
}
If you do not want to rely on the default bean-naming strategy, you can provide a custom
bean-naming
strategy. First, implement the
BeanNameGenerator
interface, and be sure to include a default no-arg
constructor. Then, provide the fully
qualified class name when configuring the scanner, as the following
example annotation
and bean definition show.
If you run into naming conflicts due to multiple autodetected components having the
same non-
qualified class name (i.e., classes with identical names but residing in
different packages), you may
need to configure a BeanNameGenerator that defaults to the
fully qualified class name for the
generated bean name. As of Spring Framework 5.2.3, the
FullyQualifiedAnnotationBeanNameGenerator located in package
org.springframework.context.annotation can be used for such purposes.
Java Kotlin
JAVA
@Configuration
// ...
}
XML
<beans>
<context:component-scan base-package="org.example"
name-generator="org.example.MyNameGenerator" />
</beans>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 119/373
6/10/22, 3:58 PM Core Technologies
As a general rule, consider specifying the name with the annotation whenever other
components may be
making explicit references to it. On the other hand, the
auto-generated names are adequate whenever the
container is responsible for wiring.
Java Kotlin
JAVA
@Scope("prototype")
@Repository
// ...
}
@Scope annotations are only introspected on the concrete bean class (for annotated
components)
or the factory method (for @Bean methods). In contrast to XML bean
definitions, there is no notion
of bean definition inheritance, and inheritance
hierarchies at the class level are irrelevant for
metadata purposes.
To provide a custom strategy for scope resolution rather than relying on the
annotation-based
approach, you can implement the
ScopeMetadataResolver
interface. Be sure to include a default no-
arg constructor. Then you can provide the
fully qualified class name when configuring the scanner,
as the following example of both
an annotation and a bean definition shows:
Java Kotlin
JAVA
@Configuration
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 120/373
6/10/22, 3:58 PM Core Technologies
// ...
}
XML
<beans>
When using certain non-singleton scopes, it may be necessary to generate proxies for the
scoped objects.
The reasoning is described in Scoped Beans as Dependencies.
For this purpose, a scoped-proxy attribute
is available on the component-scan
element. The three possible values are: no , interfaces , and
targetClass . For example,
the following configuration results in standard JDK dynamic proxies:
Java Kotlin
JAVA
@Configuration
// ...
}
XML
<beans>
</beans>
Java Kotlin
JAVA
@Component
@Qualifier("Action")
// ...
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 121/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Component
@Genre("Action")
// ...
}
Java Kotlin
JAVA
@Component
@Offline
// ...
}
As with most annotation-based alternatives, keep in mind that the annotation metadata is
bound to
the class definition itself, while the use of XML allows for multiple beans
of the same type to provide
variations in their qualifier metadata, because that
metadata is provided per-instance rather than
per-class.
To generate the index, add an additional dependency to each module that contains
components that are
targets for component scan directives. The following example shows
how to do so with Maven:
XML
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-indexer</artifactId>
<version>5.3.20</version>
<optional>true</optional>
</dependency>
</dependencies>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 122/373
6/10/22, 3:58 PM Core Technologies
With Gradle 4.5 and earlier, the dependency should be declared in the compileOnly
configuration, as
shown in the following example:
GROOVY
dependencies {
compileOnly "org.springframework:spring-context-indexer:5.3.20"
With Gradle 4.6 and later, the dependency should be declared in the annotationProcessor
configuration,
as shown in the following example:
GROOVY
dependencies {
annotationProcessor "org.springframework:spring-context-indexer:5.3.20"
When working with this mode in your IDE, the spring-context-indexer must be
registered as an
annotation processor to make sure the index is up-to-date when
candidate components are
updated.
If you use Maven, the javax.inject artifact is available in the standard Maven
repository (
https://repo1.maven.org/maven2/javax/inject/javax.inject/1/).
You can add the following dependency
to your file pom.xml:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 123/373
6/10/22, 3:58 PM Core Technologies
XML
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
Java Kotlin
JAVA
import javax.inject.Inject;
@Inject
this.movieFinder = movieFinder;
this.movieFinder.findMovies(...);
// ...
}
}
As with @Autowired , you can use @Inject at the field level, method level
and constructor-argument level.
Furthermore, you may declare your injection point as a
Provider , allowing for on-demand access to
beans of shorter scopes or lazy access to
other beans through a Provider.get() call. The following
example offers a variant of the
preceding example:
Java Kotlin
JAVA
import javax.inject.Inject;
import javax.inject.Provider;
@Inject
this.movieFinder = movieFinder;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 124/373
6/10/22, 3:58 PM Core Technologies
this.movieFinder.get().findMovies(...);
// ...
}
}
If you would like to use a qualified name for the dependency that should be injected,
you should use the
@Named annotation, as the following example shows:
Java Kotlin
JAVA
import javax.inject.Inject;
import javax.inject.Named;
@Inject
this.movieFinder = movieFinder;
// ...
}
JAVA
public class SimpleMovieLister {
@Inject
// ...
}
}
Java Kotlin
JAVA
public class SimpleMovieLister {
@Inject
// ...
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 125/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
import javax.inject.Inject;
import javax.inject.Named;
@Inject
this.movieFinder = movieFinder;
// ...
}
It is very common to use @Component without specifying a name for the component.
@Named can be used
in a similar fashion, as the following example shows:
Java Kotlin
JAVA
import javax.inject.Inject;
import javax.inject.Named;
@Named
@Inject
this.movieFinder = movieFinder;
// ...
}
When you use @Named or @ManagedBean , you can use component scanning in the
exact same way as
when you use Spring annotations, as the following example shows:
Java Kotlin
JAVA
@Configuration
@ComponentScan(basePackages = "org.example")
// ...
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 126/373
6/10/22, 3:58 PM Core Technologies
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 127/373
6/10/22, 3:58 PM Core Technologies
@Value - no equivalent
@Required - no equivalent
@Lazy - no equivalent
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 128/373
6/10/22, 3:58 PM Core Technologies
The @Bean annotation is used to indicate that a method instantiates, configures, and
initializes a new
object to be managed by the Spring IoC container. For those familiar
with Spring’s <beans/> XML
configuration, the @Bean annotation plays the same role as
the <bean/> element. You can use @Bean -
annotated methods with any Spring
@Component . However, they are most often used with
@Configuration beans.
Java Kotlin
JAVA
@Configuration
@Bean
The preceding AppConfig class is equivalent to the following Spring <beans/> XML:
XML
<beans>
</beans>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 129/373
6/10/22, 3:58 PM Core Technologies
Unlike full @Configuration , lite @Bean methods cannot declare inter-bean dependencies.
Instead,
they operate on their containing component’s internal state and, optionally, on
arguments that they
may declare. Such a @Bean method should therefore not invoke other
@Bean methods. Each such
method is literally only a factory method for a particular
bean reference, without any special runtime
semantics. The positive side-effect here is
that no CGLIB subclassing has to be applied at runtime, so
there are no limitations in
terms of class design (that is, the containing class may be final and so
forth).
The @Bean and @Configuration annotations are discussed in depth in the following sections.
First,
however, we cover the various ways of creating a spring container by using
Java-based configuration.
When @Configuration classes are provided as input, the @Configuration class itself
is registered as a
bean definition and all declared @Bean methods within the class
are also registered as bean definitions.
When @Component and JSR-330 classes are provided, they are registered as bean
definitions, and it is
assumed that DI metadata such as @Autowired or @Inject are
used within those classes where
necessary.
Simple Construction
In much the same way that Spring XML files are used as input when instantiating a
ClassPathXmlApplicationContext , you can use @Configuration classes as input when
instantiating an
AnnotationConfigApplicationContext . This allows for completely
XML-free usage of the Spring container,
as the following example shows:
Java Kotlin
JAVA
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 130/373
6/10/22, 3:58 PM Core Technologies
myService.doStuff();
Java Kotlin
JAVA
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(MyServiceImpl.class, Dependency
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
The preceding example assumes that MyServiceImpl , Dependency1 , and Dependency2 use Spring
dependency injection annotations such as @Autowired .
Java Kotlin
JAVA
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class, OtherConfig.class);
ctx.register(AdditionalConfig.class);
ctx.refresh();
myService.doStuff();
To enable component scanning, you can annotate your @Configuration class as follows:
Java Kotlin
JAVA
@Configuration
@ComponentScan(basePackages = "com.acme") 1
// ...
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 131/373
6/10/22, 3:58 PM Core Technologies
Experienced Spring users may be familiar with the XML declaration equivalent from
Spring’s
context: namespace, shown in the following example:
XML
<beans>
<context:component-scan base-package="com.acme"/>
</beans>
In the preceding example, the com.acme package is scanned to look for any
@Component -annotated
classes, and those classes are registered as Spring bean
definitions within the container.
AnnotationConfigApplicationContext exposes the
scan(String… ) method to allow for the same
component-scanning functionality, as the
following example shows:
Java Kotlin
JAVA
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan("com.acme");
ctx.refresh();
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 132/373
6/10/22, 3:58 PM Core Technologies
XML
<web-app>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.acme.AppConfig</param-value>
</context-param>
<!-- Bootstrap the root application context as usual using ContextLoaderListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<!-- Again, config locations must consist of one or more comma- or space-delimited
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.acme.web.MvcConfig</param-value>
</init-param>
</servlet>
<!-- map all requests for /app/* to the dispatcher servlet -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 133/373
6/10/22, 3:58 PM Core Technologies
init-method
destroy-method
autowiring
name .
Declaring a Bean
To declare a bean, you can annotate a method with the @Bean annotation. You use this
method to
register a bean definition within an ApplicationContext of the type
specified as the method’s return
value. By default, the bean name is the same as
the method name. The following example shows a @Bean
method declaration:
Java Kotlin
JAVA
@Configuration
@Bean
}
}
XML
<beans>
</beans>
You can also use default methods to define beans. This allows composition of bean
configurations by
implementing interfaces with bean definitions on default methods.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 134/373
6/10/22, 3:58 PM Core Technologies
Java
JAVA
public interface BaseConfig {
@Bean
}
}
@Configuration
You can also declare your @Bean method with an interface (or base class)
return type, as the following
example shows:
Java Kotlin
JAVA
@Configuration
@Bean
}
}
However, this limits the visibility for advance type prediction to the specified
interface type
( TransferService ). Then, with the full type ( TransferServiceImpl )
known to the container only once the
affected singleton bean has been instantiated.
Non-lazy singleton beans get instantiated according to their
declaration order,
so you may see different type matching results depending on when another component
tries to match by a non-declared type (such as @Autowired TransferServiceImpl ,
which resolves only
once the transferService bean has been instantiated).
Bean Dependencies
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 135/373
6/10/22, 3:58 PM Core Technologies
A @Bean -annotated method can have an arbitrary number of parameters that describe the
dependencies
required to build that bean. For instance, if our TransferService
requires an AccountRepository , we can
materialize that dependency with a method
parameter, as the following example shows:
Java Kotlin
JAVA
@Configuration
@Bean
}
}
Java Kotlin
JAVA
public class BeanOne {
// initialization logic
}
}
// destruction logic
}
}
@Configuration
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 136/373
6/10/22, 3:58 PM Core Technologies
public class AppConfig {
@Bean(initMethod = "init")
@Bean(destroyMethod = "cleanup")
}
}
By default, beans defined with Java configuration that have a public close or shutdown
method are
automatically enlisted with a destruction callback. If you have a public
close or shutdown method
and you do not wish for it to be called when the container
shuts down, you can add
@Bean(destroyMethod="") to your bean definition to disable the
default (inferred) mode.
You may want to do that by default for a resource that you acquire with JNDI, as its
lifecycle is
managed outside the application. In particular, make sure to always do it
for a DataSource , as it is
known to be problematic on Java EE application servers.
The following example shows how to prevent an automatic destruction callback for a
DataSource :
Java Kotlin
JAVA
@Bean(destroyMethod="")
Also, with methods, you typically use programmatic JNDI lookups, either by
using Spring’s
@Bean
JndiTemplate or JndiLocatorDelegate helpers or straight JNDI
InitialContext usage but not the
JndiObjectFactoryBean variant (which would force
you to declare the return type as the
FactoryBean type instead of the actual target
type, making it harder to use for cross-reference calls
in other @Bean methods that
intend to refer to the provided resource here).
In the case of BeanOne from the example above the preceding note, it would be equally valid to call the
init()
method directly during construction, as the following example shows:
Java Kotlin
JAVA
@Configuration
@Bean
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 137/373
6/10/22, 3:58 PM Core Technologies
public BeanOne beanOne() {
beanOne.init();
return beanOne;
// ...
}
When you work directly in Java, you can do anything you like with your objects and do
not always
need to rely on the container lifecycle.
You can specify that your beans defined with the @Bean annotation should have a
specific scope. You can
use any of the standard scopes specified in the
Bean Scopes section.
The default scope is singleton , but you can override this with the @Scope annotation,
as the following
example shows:
Java Kotlin
JAVA
@Configuration
@Bean
@Scope("prototype")
// ...
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 138/373
6/10/22, 3:58 PM Core Technologies
If you port the scoped proxy example from the XML reference documentation (see
scoped proxies) to our
@Bean using Java,
it resembles the following:
Java Kotlin
JAVA
// an HTTP Session-scoped bean exposed as a proxy
@Bean
@SessionScope
@Bean
public Service userService() {
UserService service = new SimpleUserService();
service.setUserPreferences(userPreferences());
return service;
Java Kotlin
JAVA
@Configuration
@Bean("myThing")
}
}
Bean Aliasing
As discussed in Naming Beans, it is sometimes desirable to give a single bean
multiple names, otherwise
known as bean aliasing. The name attribute of the @Bean
annotation accepts a String array for this
purpose. The following example shows how to set
a number of aliases for a bean:
Java Kotlin
JAVA
@Configuration
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 139/373
6/10/22, 3:58 PM Core Technologies
}
}
Bean Description
Sometimes, it is helpful to provide a more detailed textual description of a bean. This can
be particularly
useful when beans are exposed (perhaps through JMX) for monitoring purposes.
Java Kotlin
JAVA
@Configuration
@Bean
}
}
Java Kotlin
JAVA
@Configuration
@Bean
@Bean
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 140/373
6/10/22, 3:58 PM Core Technologies
}
}
This method of declaring inter-bean dependencies works only when the @Bean method
is declared
within a @Configuration class. You cannot declare inter-bean dependencies
by using plain
@Component classes.
Java Kotlin
JAVA
public abstract class CommandManager {
command.setState(commandState);
return command.execute();
Java Kotlin
JAVA
@Bean
@Scope("prototype")
return command;
@Bean
public CommandManager commandManager() {
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 141/373
6/10/22, 3:58 PM Core Technologies
// return new anonymous implementation of CommandManager with createCommand()
return asyncCommand();
}
}
Java Kotlin
JAVA
@Configuration
@Bean
clientService.setClientDao(clientDao());
return clientService;
@Bean
clientService.setClientDao(clientDao());
return clientService;
@Bean
The behavior could be different according to the scope of your bean. We are talking
about singletons
here.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 142/373
6/10/22, 3:58 PM Core Technologies
As of Spring 3.2, it is no longer necessary to add CGLIB to your classpath because CGLIB
classes have
been repackaged under org.springframework.cglib and included directly
within the spring-core
JAR.
There are a few restrictions due to the fact that CGLIB dynamically adds features at
startup-time. In
particular, configuration classes must not be final. However, as
of 4.3, any constructors are allowed
on configuration classes, including the use of
@Autowired or a single non-default constructor
declaration for default injection.
If you prefer to avoid any CGLIB-imposed limitations, consider declaring your @Bean
methods on
non- @Configuration classes (for example, on plain @Component classes instead).
Cross-method calls
between @Bean methods are not then intercepted, so you have
to exclusively rely on dependency
injection at the constructor or method level there.
Java Kotlin
JAVA
@Configuration
@Bean
public A a() {
}
}
@Configuration
@Import(ConfigA.class)
@Bean
public B b() {
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 143/373
6/10/22, 3:58 PM Core Technologies
}
}
Now, rather than needing to specify both ConfigA.class and ConfigB.class when
instantiating the
context, only ConfigB needs to be supplied explicitly, as the
following example shows:
Java Kotlin
JAVA
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);
A a = ctx.getBean(A.class);
B b = ctx.getBean(B.class);
This approach simplifies container instantiation, as only one class needs to be dealt
with, rather than
requiring you to remember a potentially large number of
@Configuration classes during construction.
The preceding example works but is simplistic. In most practical scenarios, beans have
dependencies on
one another across configuration classes. When using XML, this is not an
issue, because no compiler is
involved, and you can declare
ref="someBean" and trust Spring to work it out during container
initialization.
When using @Configuration classes, the Java compiler places constraints on
the
configuration model, in that references to other beans must be valid Java syntax.
Java Kotlin
JAVA
@Configuration
@Bean
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 144/373
6/10/22, 3:58 PM Core Technologies
}
@Configuration
@Bean
}
}
@Configuration
@Import({ServiceConfig.class, RepositoryConfig.class})
@Bean
}
}
There is another way to achieve the same result. Remember that @Configuration classes are
ultimately
only another bean in the container: This means that they can take advantage of
@Autowired and @Value
injection and other features the same as any other bean.
Make sure that the dependencies you inject that way are of the simplest kind only. @Configuration
classes are processed quite early during the initialization of the context, and forcing a dependency
to
be injected this way may lead to unexpected early initialization. Whenever possible, resort to
parameter-based injection, as in the preceding example.
The following example shows how one bean can be autowired to another bean:
Java Kotlin
JAVA
@Configuration
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 145/373
6/10/22, 3:58 PM Core Technologies
@Autowired
@Bean
}
}
@Configuration
this.dataSource = dataSource;
@Bean
}
}
@Configuration
@Import({ServiceConfig.class, RepositoryConfig.class})
@Bean
}
}
In cases where this ambiguity is not acceptable and you wish to have direct navigation
from within your
IDE from one @Configuration class to another, consider autowiring the
configuration classes themselves.
The following example shows how to do so:
Java Kotlin
JAVA
@Configuration
@Autowired
@Bean
}
}
Java Kotlin
JAVA
@Configuration
@Autowired
@Bean
}
}
@Configuration
@Bean
AccountRepository accountRepository();
@Configuration
@Bean
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 147/373
6/10/22, 3:58 PM Core Technologies
return new JdbcAccountRepository(...);
}
}
@Configuration
@Bean
// return DataSource
If you want to influence the startup creation order of certain beans, consider
declaring some of them
as @Lazy (for creation on first access instead of on startup)
or as @DependsOn certain other beans
(making sure that specific other beans are
created before the current bean, beyond what the latter’s
direct dependencies imply).
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 148/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Override
if (context.getEnvironment().acceptsProfiles(((String[]) value))) {
return true;
return false;
}
return true;
It may be preferable to bootstrap the Spring container from XML and include
@Configuration classes in
an ad-hoc fashion. For example, in a large existing codebase
that uses Spring XML, it is easier to create
@Configuration classes on an
as-needed basis and include them from the existing XML files. Later in this
section, we cover the
options for using @Configuration classes in this kind of “XML-centric” situation.
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 149/373
6/10/22, 3:58 PM Core Technologies
JAVA
@Configuration
@Autowired
@Bean
@Bean
}
}
XML
<beans>
<context:annotation-config/>
<context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>
<bean class="com.acme.AppConfig"/>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource">
</bean>
</beans>
jdbc.url=jdbc:hsqldb:hsql://localhost/xdb
jdbc.username=sa
jdbc.password=
Java Kotlin
JAVA
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/com/acme/system-test-co
TransferService transferService = ctx.getBean(TransferService.class);
// ...
}
XML
<beans>
<context:component-scan base-package="com.acme"/>
<context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource">
</bean>
</beans>
In applications where @Configuration classes are the primary mechanism for configuring
the container, it
is still likely necessary to use at least some XML. In these
scenarios, you can use @ImportResource and
define only as much XML as you need. Doing
so achieves a “Java-centric” approach to configuring the
container and keeps XML to a
bare minimum. The following example (which includes a configuration class,
an XML file
that defines a bean, a properties file, and the main class) shows how to use
the
@ImportResource annotation to achieve “Java-centric” configuration that uses XML
as needed:
Java Kotlin
JAVA
@Configuration
@ImportResource("classpath:/com/acme/properties-config.xml")
@Value("${jdbc.url}")
@Value("${jdbc.username}")
@Value("${jdbc.password}")
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 151/373
6/10/22, 3:58 PM Core Technologies
private String password;
@Bean
}
}
XML
properties-config.xml
<beans>
<context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>
</beans>
jdbc.properties
jdbc.url=jdbc:hsqldb:hsql://localhost/xdb
jdbc.username=sa
jdbc.password=
Java Kotlin
JAVA
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
// ...
}
Properties play an important role in almost all applications and may originate from
a variety of sources:
properties files, JVM system properties, system environment
variables, JNDI, servlet context parameters,
ad-hoc Properties objects, Map objects, and so
on. The role of the Environment object with relation to
properties is to provide the
user with a convenient service interface for configuring property sources and
resolving
properties from them.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 152/373
6/10/22, 3:58 PM Core Technologies
Bean definition profiles provide a mechanism in the core container that allows for
registration of different
beans in different environments. The word, “environment,”
can mean different things to different users,
and this feature can help with many
use cases, including:
Java Kotlin
JAVA
@Bean
public DataSource dataSource() {
.setType(EmbeddedDatabaseType.HSQL)
.addScript("my-schema.sql")
.addScript("my-test-data.sql")
.build();
Java Kotlin
JAVA
@Bean(destroyMethod="")
The problem is how to switch between using these two variations based on the
current environment. Over
time, Spring users have devised a number of ways to
get this done, usually relying on a combination of
system environment variables
and XML <import/> statements containing ${placeholder} tokens that
resolve
to the correct configuration file path depending on the value of an environment
variable. Bean
definition profiles is a core container feature that provides a
solution to this problem.
If we generalize the use case shown in the preceding example of environment-specific bean
definitions,
we end up with the need to register certain bean definitions in
certain contexts but not in others. You
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 153/373
6/10/22, 3:58 PM Core Technologies
Using @Profile
The @Profile
annotation lets you indicate that a component is eligible for registration
when one or more
specified profiles are active. Using our preceding example, we
can rewrite the dataSource configuration
as follows:
Java Kotlin
JAVA
@Configuration
@Profile("development")
@Bean
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:com/bank/config/sql/schema.sql")
.addScript("classpath:com/bank/config/sql/test-data.sql")
.build();
}
}
Java Kotlin
JAVA
@Configuration
@Profile("production")
@Bean(destroyMethod="")
}
}
As mentioned earlier, with @Bean methods, you typically choose to use programmatic
JNDI lookups,
by using either Spring’s JndiTemplate / JndiLocatorDelegate helpers or the
straight JNDI
InitialContext usage shown earlier but not the JndiObjectFactoryBean
variant, which would force
you to declare the return type as the FactoryBean type.
The profile string may contain a simple profile name (for example, production ) or a
profile expression. A
profile expression allows for more complicated profile logic to be
expressed (for example, production &
us-east ). The following operators are supported in
profile expressions:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 154/373
6/10/22, 3:58 PM Core Technologies
You cannot mix the & and | operators without using parentheses. For example,
production & us-
east | eu-central is not a valid expression. It must be expressed as
production & (us-east | eu-
central) .
Java Kotlin
JAVA
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Profile("production")
If a @Configuration class is marked with @Profile , all of the @Bean methods and
@Import
annotations associated with that class are bypassed unless one or more of
the specified profiles are
active. If a @Component or @Configuration class is marked
with @Profile({"p1", "p2"}) , that class
is not registered or processed unless
profiles 'p1' or 'p2' have been activated. If a given profile is
prefixed with the
NOT operator ( ! ), the annotated element is registered only if the profile is not
active. For example, given @Profile({"p1", "!p2"}) , registration will occur if profile
'p1' is active or
if profile 'p2' is not active.
@Profile can also be declared at the method level to include only one particular bean
of a configuration
class (for example, for alternative variants of a particular bean), as
the following example shows:
Java Kotlin
JAVA
@Configuration
@Bean("dataSource")
@Profile("development") 1
.setType(EmbeddedDatabaseType.HSQL)
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 155/373
6/10/22, 3:58 PM Core Technologies
.addScript("classpath:com/bank/config/sql/schema.sql")
.addScript("classpath:com/bank/config/sql/test-data.sql")
.build();
@Bean("dataSource")
@Profile("production") 2
}
}
With @Profile on @Bean methods, a special scenario may apply: In the case of
overloaded @Bean
methods of the same Java method name (analogous to constructor
overloading), a @Profile
condition needs to be consistently declared on all
overloaded methods. If the conditions are
inconsistent, only the condition on the
first declaration among the overloaded methods matters.
Therefore, @Profile can
not be used to select an overloaded method with a particular argument
signature over
another. Resolution between all factory methods for the same bean follows Spring’s
constructor resolution algorithm at creation time.
XML
<beans profile="development"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="...">
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:com/bank/config/sql/schema.sql"/>
<jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/>
</jdbc:embedded-database>
</beans>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 156/373
6/10/22, 3:58 PM Core Technologies
XML
<beans profile="production"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="...">
</beans>
It is also possible to avoid that split and nest <beans/> elements within the same file,
as the following
example shows:
XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="...">
<beans profile="development">
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:com/bank/config/sql/schema.sql"/>
<jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/>
</jdbc:embedded-database>
</beans>
<beans profile="production">
</beans>
</beans>
The spring-bean.xsd has been constrained to allow such elements only as the
last ones in the file. This
should help provide flexibility without incurring
clutter in the XML files.
The XML counterpart does not support the profile expressions described earlier. It is possible,
however, to negate a profile by using the ! operator. It is also possible to apply a logical
“and” by
nesting the profiles, as the following example shows:
XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="...">
<beans profile="production">
<beans profile="us-east">
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 157/373
6/10/22, 3:58 PM Core Technologies
</beans>
</beans>
</beans>
In the preceding example, the dataSource bean is exposed if both the production and
us-east
profiles are active.
Activating a Profile
Now that we have updated our configuration, we still need to instruct Spring which
profile is active. If we
started our sample application right now, we would see
a NoSuchBeanDefinitionException thrown,
because the container could not find
the Spring bean named dataSource .
Activating a profile can be done in several ways, but the most straightforward is to do
it programmatically
against the Environment API which is available through an
ApplicationContext . The following example
shows how to do so:
Java Kotlin
JAVA
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("development");
ctx.refresh();
Note that profiles are not an “either-or” proposition. You can activate multiple
profiles at once.
Programmatically, you can provide multiple profile names to the
setActiveProfiles() method, which
accepts String… varargs. The following example
activates multiple profiles:
Java Kotlin
JAVA
ctx.getEnvironment().setActiveProfiles("profile1", "profile2");
-Dspring.profiles.active="profile1,profile2"
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 158/373
6/10/22, 3:58 PM Core Technologies
Default Profile
The default profile represents the profile that is enabled by default. Consider the
following example:
Java Kotlin
JAVA
@Configuration
@Profile("default")
@Bean
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:com/bank/config/sql/schema.sql")
.build();
}
}
You can change the name of the default profile by using setDefaultProfiles() on
the Environment or,
declaratively, by using the spring.profiles.default property.
Java Kotlin
JAVA
ApplicationContext ctx = new GenericApplicationContext();
In the preceding snippet, we see a high-level way of asking Spring whether the my-property property is
defined for the current environment. To answer this question, the Environment object performs
a search
over a set of PropertySource
objects. A PropertySource is a simple abstraction over any source of key-
value pairs, and
Spring’s StandardEnvironment
is configured with two PropertySource objects — one
representing the set of JVM system properties
( System.getProperties() ) and one representing the set of
system environment variables
( System.getenv() ).
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 159/373
6/10/22, 3:58 PM Core Technologies
These default property sources are present for StandardEnvironment , for use in standalone
applications. StandardServletEnvironment
is populated with additional default property sources
including servlet config and servlet
context parameters. It can optionally enable a
JndiPropertySource .
See the javadoc for details.
The search performed is hierarchical. By default, system properties have precedence over
environment variables. So, if the my-property property happens to be set in both places during
a
call to env.getProperty("my-property") , the system property value “wins” and is returned.
Note
that property values are not merged
but rather completely overridden by a preceding entry.
Most importantly, the entire mechanism is configurable. Perhaps you have a custom source
of properties
that you want to integrate into this search. To do so, implement
and instantiate your own PropertySource
and add it to the set of PropertySources for the
current Environment . The following example shows how
to do so:
Java Kotlin
JAVA
ConfigurableApplicationContext ctx = new GenericApplicationContext();
sources.addFirst(new MyPropertySource());
In the preceding code, MyPropertySource has been added with highest precedence in the
search. If it
contains a my-property property, the property is detected and returned, in favor of
any my-property
property in any other PropertySource . The
MutablePropertySources
API exposes a number of methods
that allow for precise manipulation of the set of
property sources.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 160/373
6/10/22, 3:58 PM Core Technologies
Given a file called app.properties that contains the key-value pair testbean.name=myTestBean ,
the
following @Configuration class uses @PropertySource in such a way that
a call to testBean.getName()
returns myTestBean :
Java Kotlin
JAVA
@Configuration
@PropertySource("classpath:/com/myco/app.properties")
@Autowired
Environment env;
@Bean
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
Java Kotlin
JAVA
@Configuration
@PropertySource("classpath:/com/${my.placeholder:default/path}/app.properties")
@Autowired
Environment env;
@Bean
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
XML
<beans>
<import resource="com/bank/service/${customer}-config.xml"/>
</beans>
To enable load-time weaving, you can add the @EnableLoadTimeWeaving to one of your
@Configuration
classes, as the following example shows:
Java Kotlin
JAVA
@Configuration
@EnableLoadTimeWeaving
Alternatively, for XML configuration, you can use the context:load-time-weaver element:
XML
<beans>
<context:load-time-weaver/>
</beans>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 162/373
6/10/22, 3:58 PM Core Technologies
Once configured for the ApplicationContext , any bean within that ApplicationContext
may implement
LoadTimeWeaverAware , thereby receiving a reference to the load-time
weaver instance. This is particularly
useful in combination with
Spring’s JPA support where load-time weaving may be
necessary for JPA class
transformation.
Consult the
LocalContainerEntityManagerFactoryBean
javadoc for more detail. For more
on AspectJ load-time weaving, see Load-time Weaving with AspectJ in the Spring Framework.
String getMessage(String code, Object[] args, String default, Locale loc) : The basic
method
used to retrieve a message from the MessageSource . When no message is found
for the specified
locale, the default message is used. Any arguments passed in become
replacement values, using the
MessageFormat functionality provided by the standard
library.
String getMessage(String code, Object[] args, Locale loc) : Essentially the same as
the previous
method but with one difference: No default message can be specified. If
the message cannot be found,
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 163/373
6/10/22, 3:58 PM Core Technologies
a NoSuchMessageException is thrown.
String getMessage(MessageSourceResolvable resolvable, Locale locale) : All properties
used in the
preceding methods are also wrapped in a class named
MessageSourceResolvable , which you can use
with this method.
XML
<beans>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>format</value>
<value>exceptions</value>
<value>windows</value>
</list>
</property>
</bean>
</beans>
The example assumes that you have three resource bundles called format , exceptions and windows
defined in your classpath. Any request to resolve a message is
handled in the JDK-standard way of
resolving messages through ResourceBundle objects. For the
purposes of the example, assume the
contents of two of the above resource bundle files
are as follows:
# in format.properties
message=Alligators rock!
# in exceptions.properties
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 164/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
public static void main(String[] args) {
MessageSource resources = new ClassPathXmlApplicationContext("beans.xml");
System.out.println(message);
Alligators rock!
The next example shows arguments passed to the message lookup. These arguments are
converted into
String objects and inserted into placeholders in the lookup message.
XML
<beans>
</bean>
<!-- lets inject the above MessageSource into this POJO -->
</beans>
Java Kotlin
JAVA
public class Example {
this.messages = messages;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 165/373
6/10/22, 3:58 PM Core Technologies
}
System.out.println(message);
}
}
The resulting output from the invocation of the execute() method is as follows:
# in exceptions_en_GB.properties
Java Kotlin
JAVA
public static void main(final String[] args) {
System.out.println(message);
The resulting output from the running of the above program is as follows:
You can also use the MessageSourceAware interface to acquire a reference to any
MessageSource that has
been defined. Any bean that is defined in an
ApplicationContext that implements the
MessageSourceAware interface is injected with
the application context’s MessageSource when the bean is
created and configured.
the same base name, but will only use the first bundle found.
Subsequent message bundles with the
same base name are ignored.
As of Spring 4.2, the event infrastructure has been significantly improved and offers
an annotation-
based model as well as the
ability to publish any arbitrary event (that is, an object that does not
necessarily
extend from ApplicationEvent ). When such an object is published, we wrap it in an
event for you.
The following table describes the standard events that Spring provides:
Event Explanation
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 167/373
6/10/22, 3:58 PM Core Technologies
Event Explanation
RequestHandledEvent A web-specific event telling all beans that an HTTP request has been
serviced. This
event is published after the request is complete. This
event is only applicable to
web applications that use Spring’s
DispatcherServlet .
You can also create and publish your own custom events. The following example shows a
simple class that
extends Spring’s ApplicationEvent base class:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 168/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
public class BlockedListEvent extends ApplicationEvent {
super(source);
this.address = address;
this.content = content;
Java Kotlin
JAVA
public class EmailService implements ApplicationEventPublisherAware {
this.blockedList = blockedList;
this.publisher = publisher;
if (blockedList.contains(address)) {
return;
// send email...
}
}
To receive the custom ApplicationEvent , you can create a class that implements
ApplicationListener
and register it as a Spring bean. The following example
shows such a class:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 169/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
public class BlockedListNotifier implements ApplicationListener<BlockedListEvent> {
this.notificationAddress = notificationAddress;
}
}
The following example shows the bean definitions used to register and configure each of
the classes
above:
XML
<bean id="emailService" class="example.EmailService">
<property name="blockedList">
<list>
<value>known.spammer@example.org</value>
<value>known.hacker@example.org</value>
<value>john.doe@example.org</value>
</list>
</property>
</bean>
</bean>
Putting it all together, when the sendEmail() method of the emailService bean is
called, if there are any
email messages that should be blocked, a custom event of type
BlockedListEvent is published. The
blockedListNotifier bean is registered as an
ApplicationListener and receives the
BlockedListEvent , at which point it can
notify appropriate parties.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 170/373
6/10/22, 3:58 PM Core Technologies
Spring’s eventing mechanism is designed for simple communication between Spring beans
within the
same application context. However, for more sophisticated enterprise
integration needs, the
separately maintained
Spring Integration project provides
complete support for building lightweight,
pattern-oriented, event-driven
architectures that build upon the well-known Spring programming
model.
Java Kotlin
JAVA
public class BlockedListNotifier {
this.notificationAddress = notificationAddress;
@EventListener
}
}
The method signature once again declares the event type to which it listens,
but, this time, with a flexible
name and without implementing a specific listener interface.
The event type can also be narrowed
through generics as long as the actual event type
resolves your generic parameter in its implementation
hierarchy.
If your method should listen to several events or if you want to define it with no
parameter at all, the event
types can also be specified on the annotation itself. The
following example shows how to do so:
Java Kotlin
JAVA
@EventListener({ContextStartedEvent.class, ContextRefreshedEvent.class})
// ...
}
It is also possible to add additional runtime filtering by using the condition attribute
of the annotation
that defines a SpEL expression, which should match
to actually invoke the method for a particular event.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 171/373
6/10/22, 3:58 PM Core Technologies
The following example shows how our notifier can be rewritten to be invoked only if the
content
attribute of the event is equal to my-event :
Java Kotlin
JAVA
@EventListener(condition = "#blEvent.content == 'my-event'")
Each SpEL expression evaluates against a dedicated context. The following table lists the
items made
available to the context so that you can use them for conditional event processing:
Argument name evaluation context The name of any of the #blEvent or #a0 (you
method arguments. If, can also use #p0 or
for some reason, the #p<#arg> parameter
names are not notation as an alias)
available
(for example,
because there is no
debug information in
the compiled byte
code), individual
arguments are also
available using the
#a<#arg> syntax
where <#arg> stands
for the
argument index
(starting from 0).
Note that #root.event gives you access to the underlying event, even if your method
signature actually
refers to an arbitrary object that was published.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 172/373
6/10/22, 3:58 PM Core Technologies
If you need to publish an event as the result of processing another event, you can change the
method
signature to return the event that should be published, as the following example shows:
Java Kotlin
JAVA
@EventListener
Asynchronous Listeners
If you want a particular listener to process events asynchronously, you can reuse the
regular @Async
support.
The following example shows how to do so:
Java Kotlin
JAVA
@EventListener
@Async
Ordering Listeners
If you need one listener to be invoked before another one, you can add the @Order
annotation to the
method declaration, as the following example shows:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 173/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@EventListener
@Order(42)
public void processBlockedListEvent(BlockedListEvent event) {
Generic Events
You can also use generics to further define the structure of your event. Consider using an
EntityCreatedEvent<T> where T is the type of the actual entity that got created. For example, you
can
create the following listener definition to receive only EntityCreatedEvent for a
Person :
Java Kotlin
JAVA
@EventListener
// ...
}
Due to type erasure, this works only if the event that is fired resolves the generic
parameters on which the
event listener filters (that is, something like
class PersonCreatedEvent extends
EntityCreatedEvent<Person> { …} ).
In certain circumstances, this may become quite tedious if all events follow the same
structure (as should
be the case for the event in the preceding example). In such a case,
you can implement
ResolvableTypeProvider to guide the framework beyond what the runtime
environment provides. The
following event shows how to do so:
Java Kotlin
JAVA
public class EntityCreatedEvent<T> extends ApplicationEvent implements ResolvableTypeProvider {
super(entity);
@Override
This works not only for ApplicationEvent but any arbitrary object that you send as
an event.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 174/373
6/10/22, 3:58 PM Core Technologies
You can configure a bean deployed into the application context to implement the special
callback
interface, ResourceLoaderAware , to be automatically called back at
initialization time with the application
context itself passed in as the ResourceLoader .
You can also expose properties of type Resource , to be
used to access static resources.
They are injected into it like any other properties. You can specify those
Resource
properties as simple String paths and rely on automatic conversion from those text
strings to
actual Resource objects when the bean is deployed.
Tracking the application startup steps with specific metrics can help understand where
time is being spent
during the startup phase, but it can also be used as a way to better
understand the context lifecycle as a
whole.
Java Kotlin
JAVA
// create a startup step and start recording
this.scanner.scan(basePackages);
scanPackages.end();
Developers can also use the ApplicationStartup infrastructure if they’re providing their own
AbstractApplicationContext subclass, or if they wish to collect more precise data.
To start collecting custom StartupStep , components can either get the ApplicationStartup
instance
from the application context directly, make their component implement ApplicationStartupAware ,
or ask
for the ApplicationStartup type on any injection point.
Developers should not use the "spring.*" namespace when creating custom startup steps.
This
namespace is reserved for internal Spring usage and is subject to change.
XML
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
The listener inspects the contextConfigLocation parameter. If the parameter does not
exist, the listener
uses /WEB-INF/applicationContext.xml as a default. When the
parameter does exist, the listener
separates the String by using predefined
delimiters (comma, semicolon, and whitespace) and uses the
values as locations where
application contexts are searched. Ant-style path patterns are supported as
well.
Examples are /WEB-INF/*Context.xml (for all files with names that end with
Context.xml and that
reside in the WEB-INF directory) and /WEB-INF/**/*Context.xml
(for all such files in any subdirectory of
WEB-INF ).
RAR deployment is ideal for application contexts that do not need HTTP entry points but
rather consist
only of message endpoints and scheduled jobs. Beans in such a context can
use application server
resources such as the JTA transaction manager and JNDI-bound JDBC
DataSource instances and JMS
ConnectionFactory instances and can also register with
the platform’s JMX server — all through Spring’s
standard transaction management and JNDI
and JMX support facilities. Application components can also
interact with the application
server’s JCA WorkManager through Spring’s TaskExecutor abstraction.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 177/373
6/10/22, 3:58 PM Core Technologies
1. Package
all application classes into a RAR file (which is a standard JAR file with a different
file
extension).
2. Add all required library JARs into the root of the RAR archive.
3. Add a
META-INF/ra.xml deployment descriptor (as shown in the javadoc for
SpringContextResourceAdapter )
and the corresponding Spring XML bean definition file(s) (typically
META-INF/applicationContext.xml ).
Such RAR deployment units are usually self-contained. They do not expose components
to the
outside world, not even to other modules of the same application. Interaction with a
RAR-based
ApplicationContext usually occurs through JMS destinations that it shares with
other modules. A
RAR-based ApplicationContext may also, for example, schedule some jobs
or react to new files in
the file system (or the like). If it needs to allow synchronous
access from the outside, it could (for
example) export RMI endpoints, which may be used
by other application modules on the same
machine.
Note that the core BeanFactory API level and its DefaultListableBeanFactory
implementation do not
make assumptions about the configuration format or any
component annotations to be used. All of these
flavors come in through extensions
(such as XmlBeanDefinitionReader and
AutowiredAnnotationBeanPostProcessor ) and
operate on shared BeanDefinition objects as a core
metadata representation.
This is the essence of what makes Spring’s container so flexible and extensible.
You should use an unless you have a good reason for not doing so, with
ApplicationContext
GenericApplicationContext and its subclass AnnotationConfigApplicationContext
as the common
implementations for custom bootstrapping. These are the primary entry
points to Spring’s core container
for all common purposes: loading of configuration
files, triggering a classpath scan, programmatically
registering bean definitions
and annotated classes, and (as of 5.0) registering functional bean definitions.
For many extended container features, such as annotation processing and AOP proxying,
the
BeanPostProcessor extension point is essential.
If you use only a plain DefaultListableBeanFactory ,
such post-processors do not
get detected and activated by default. This situation could be confusing,
because
nothing is actually wrong with your bean configuration. Rather, in such a scenario,
the container
needs to be fully bootstrapped through additional setup.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 179/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor());
factory.addBeanPostProcessor(new MyBeanPostProcessor());
Java Kotlin
JAVA
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
reader.loadBeanDefinitions(new FileSystemResource("beans.xml"));
cfg.setLocation(new FileSystemResource("jdbc.properties"));
cfg.postProcessBeanFactory(factory);
2. Resources
This chapter covers how Spring handles resources and how you can work with resources in
Spring. It
includes the following topics:
Introduction
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 180/373
6/10/22, 3:58 PM Core Technologies
2.1. Introduction
Java’s standard java.net.URL class and standard handlers for various URL prefixes,
unfortunately, are not
quite adequate enough for all access to low-level resources. For
example, there is no standardized URL
implementation that may be used to access a
resource that needs to be obtained from the classpath or
relative to a
ServletContext . While it is possible to register new handlers for specialized URL
prefixes
(similar to existing handlers for prefixes such as http: ), this is generally
quite complicated, and the URL
interface still lacks some desirable functionality,
such as a method to check for the existence of the
resource being pointed to.
JAVA
public interface Resource extends InputStreamSource {
boolean exists();
boolean isReadable();
boolean isOpen();
boolean isFile();
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 181/373
6/10/22, 3:58 PM Core Technologies
String getFilename();
String getDescription();
JAVA
public interface InputStreamSource {
Some of the most important methods from the Resource interface are:
Other methods let you obtain an actual URL or File object representing the
resource (if the underlying
implementation is compatible and supports that
functionality).
While the Resource interface is used a lot with Spring and by Spring, it is actually
very convenient to use
as a general utility class by itself in your own code, for access
to resources, even when your code does not
know or care about any other parts of Spring.
While this couples your code to Spring, it really only couples
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 182/373
6/10/22, 3:58 PM Core Technologies
UrlResource
ClassPathResource
FileSystemResource
PathResource
ServletContextResource
InputStreamResource
ByteArrayResource
2.3.1. UrlResource
UrlResource wraps a java.net.URL and can be used to access any object that is
normally accessible with
a URL, such as files, an HTTPS target, an FTP target, and
others. All URLs have a standardized String
representation, such that appropriate
standardized prefixes are used to indicate one URL type from
another. This includes
file: for accessing filesystem paths, https: for accessing resources through the
HTTPS protocol, ftp: for accessing resources through FTP, and others.
2.3.2. ClassPathResource
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 183/373
6/10/22, 3:58 PM Core Technologies
This class represents a resource that should be obtained from the classpath. It uses
either the thread
context class loader, a given class loader, or a given class for
loading resources.
2.3.3. FileSystemResource
This is a Resource implementation for java.io.File handles. It also supports
java.nio.file.Path
handles, applying Spring’s standard String-based path
transformations but performing all operations via
the java.nio.file.Files API. For pure
java.nio.path.Path based support use a PathResource instead.
FileSystemResource
supports resolution as a File and as a URL .
2.3.4. PathResource
This is a Resource implementation for java.nio.file.Path handles, performing all
operations and
transformations via the Path API. It supports resolution as a File and
as a URL and also implements
the extended WritableResource interface. PathResource
is effectively a pure java.nio.path.Path based
alternative to FileSystemResource with
different createRelative behavior.
2.3.5. ServletContextResource
This is a Resource implementation for ServletContext resources that interprets
relative paths within the
relevant web application’s root directory.
It always supports stream access and URL access but allows java.io.File access only
when the web
application archive is expanded and the resource is physically on the
filesystem. Whether or not it is
expanded and on the filesystem or accessed
directly from the JAR or somewhere else like a database
(which is conceivable) is actually
dependent on the Servlet container.
2.3.6. InputStreamResource
An InputStreamResource is a Resource implementation for a given InputStream . It
should be used only
if no specific Resource implementation is applicable. In
particular, prefer ByteArrayResource or any of
the file-based Resource
implementations where possible.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 184/373
6/10/22, 3:58 PM Core Technologies
2.3.7. ByteArrayResource
This is a Resource implementation for a given byte array. It creates a
ByteArrayInputStream for the given
byte array.
It is useful for loading content from any given byte array without having to resort to a
single-use
InputStreamResource .
JAVA
public interface ResourceLoader {
ClassLoader getClassLoader();
When you call getResource() on a specific application context, and the location path
specified doesn’t
have a specific prefix, you get back a Resource type that is
appropriate to that particular application
context. For example, assume the following
snippet of code was run against a
ClassPathXmlApplicationContext instance:
Java Kotlin
JAVA
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
As a result, you can load resources in a fashion appropriate to the particular application
context.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 185/373
6/10/22, 3:58 PM Core Technologies
On the other hand, you may also force ClassPathResource to be used, regardless of the
application
context type, by specifying the special classpath: prefix, as the following
example shows:
Java Kotlin
JAVA
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
Similarly, you can force a UrlResource to be used by specifying any of the standard
java.net.URL
prefixes. The following examples use the file and https prefixes:
Java Kotlin
JAVA
Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");
Java Kotlin
JAVA
Resource template = ctx.getResource("https://myhost.com/resource/path/myTemplate.txt");
The following table summarizes the strategy for converting String objects to Resource
objects:
JAVA
public interface ResourcePatternResolver extends ResourceLoader {
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 186/373
6/10/22, 3:58 PM Core Technologies
String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
As can be seen above, this interface also defines a special classpath*: resource prefix
for all matching
resources from the class path. Note that the resource location is
expected to be a path without
placeholders in this case — for example,
classpath*:/config/beans.xml . JAR files or different directories
in the class path can
contain multiple files with the same path and the same name. See
Wildcards in
Application Context Constructor Resource Paths and its subsections for further details
on wildcard
support with the classpath*: resource prefix.
JAVA
public interface ResourceLoaderAware {
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 187/373
6/10/22, 3:58 PM Core Technologies
In application components, you may also rely upon autowiring of the ResourceLoader as
an alternative to
implementing the ResourceLoaderAware interface. The traditional constructor and byType autowiring
modes (as described in Autowiring Collaborators)
are capable of providing a ResourceLoader for either a
constructor argument or a
setter method parameter, respectively. For more flexibility (including the ability
to
autowire fields and multiple parameter methods), consider using the annotation-based
autowiring
features. In that case, the ResourceLoader is autowired into a field,
constructor argument, or method
parameter that expects the ResourceLoader type as long
as the field, constructor, or method in question
carries the @Autowired annotation.
For more information, see Using @Autowired .
To load one or more Resource objects for a resource path that contains wildcards
or makes use of
the special classpath*: resource prefix, consider having an instance of
ResourcePatternResolver
autowired into your
application components instead of ResourceLoader .
What makes it trivial to then inject these properties is that all application contexts
register and use a
special JavaBeans PropertyEditor , which can convert String paths
to Resource objects. For example,
the following MyBean class has a template
property of type Resource .
Java Kotlin
JAVA
package example;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 188/373
6/10/22, 3:58 PM Core Technologies
public class MyBean {
this.template = template;
// ...
}
In an XML configuration file, the template property can be configured with a simple
string for that
resource, as the following example shows:
XML
<bean id="myBean" class="example.MyBean">
</bean>
Note that the resource path has no prefix. Consequently, because the application context
itself is going to
be used as the ResourceLoader , the resource is loaded through a
ClassPathResource , a
FileSystemResource , or a ServletContextResource , depending on
the exact type of the application
context.
If you need to force a specific Resource type to be used, you can use a prefix. The
following two examples
show how to force a ClassPathResource and a UrlResource (the
latter being used to access a file in the
filesystem):
XML
<property name="template" value="classpath:some/resource/path/myTemplate.txt">
XML
<property name="template" value="file:///some/resource/path/myTemplate.txt"/>
Java Kotlin
JAVA
@Component
public class MyBean {
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 189/373
6/10/22, 3:58 PM Core Technologies
public MyBean(@Value("${template.path}") Resource template) {
this.template = template;
// ...
}
If we want to support multiple templates discovered under the same path in multiple
locations in the
classpath — for example, in multiple jars in the classpath — we can
use the special classpath*: prefix and
wildcarding to define a templates.path key as
classpath*:/config/templates/*.txt . If we redefine the
MyBean class as follows,
Spring will convert the template path pattern into an array of Resource objects
that
can be injected into the MyBean constructor.
Java Kotlin
JAVA
@Component
public class MyBean {
this.templates = templates;
// ...
}
When such a location path does not have a prefix, the specific Resource type built from
that path and
used to load the bean definitions depends on and is appropriate to the
specific application context. For
example, consider the following example, which creates a
ClassPathXmlApplicationContext :
Java Kotlin
JAVA
ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 190/373
6/10/22, 3:58 PM Core Technologies
The bean definitions are loaded from the classpath, because a ClassPathResource is
used. However,
consider the following example, which creates a FileSystemXmlApplicationContext :
Java Kotlin
JAVA
ApplicationContext ctx =
new FileSystemXmlApplicationContext("conf/appContext.xml");
Now the bean definitions are loaded from a filesystem location (in this case, relative to
the current
working directory).
Note that the use of the special classpath prefix or a standard URL prefix on the
location path overrides
the default type of Resource created to load the bean
definitions. Consider the following example:
Java Kotlin
JAVA
ApplicationContext ctx =
new FileSystemXmlApplicationContext("classpath:conf/appContext.xml");
com/
example/
services.xml
repositories.xml
MessengerService.class
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 191/373
6/10/22, 3:58 PM Core Technologies
JAVA
ApplicationContext ctx = new ClassPathXmlApplicationContext(
One use for this mechanism is when you need to do component-style application assembly. All
components can publish context definition fragments to a well-known location path, and,
when the final
application context is created using the same path prefixed with
classpath*: , all component fragments
are automatically picked up.
Note that this wildcarding is specific to the use of resource paths in application context
constructors (or
when you use the PathMatcher utility class hierarchy directly) and is
resolved at construction time. It has
nothing to do with the Resource type itself.
You cannot use the classpath*: prefix to construct an actual
Resource , as
a resource points to just one resource at a time.
Ant-style Patterns
Path locations can contain Ant-style patterns, as the following example shows:
/WEB-INF/*-context.xml
com/mycompany/**/applicationContext.xml
file:C:/some/path/*-context.xml
classpath:com/mycompany/**/applicationContext.xml
When the path location contains an Ant-style pattern, the resolver follows a more complex
procedure to
try to resolve the wildcard. It produces a Resource for the path up to the
last non-wildcard segment and
obtains a URL from it. If this URL is not a jar: URL or
container-specific variant (such as zip: in
WebLogic, wsjar in WebSphere, and so on),
a java.io.File is obtained from it and used to resolve the
wildcard by traversing the
filesystem. In the case of a jar URL, the resolver either gets a
java.net.JarURLConnection from it or manually parses the jar URL and then traverses the
contents of the
jar file to resolve the wildcards.
Implications on Portability
If the specified path is already a file URL (either implicitly because the base
ResourceLoader is a
filesystem one or explicitly), wildcarding is guaranteed to
work in a completely portable fashion.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 192/373
6/10/22, 3:58 PM Core Technologies
If the specified path is a classpath location, the resolver must obtain the last
non-wildcard path segment
URL by making a Classloader.getResource() call. Since this
is just a node of the path (not the file at the
end), it is actually undefined (in the
ClassLoader javadoc) exactly what sort of a URL is returned in this
case. In practice,
it is always a java.io.File representing the directory (where the classpath resource
resolves to a filesystem location) or a jar URL of some sort (where the classpath resource
resolves to a jar
location). Still, there is a portability concern on this operation.
If a jar URL is obtained for the last non-wildcard segment, the resolver must be able to
get a
java.net.JarURLConnection from it or manually parse the jar URL, to be able to
walk the contents of the
jar and resolve the wildcard. This does work in most environments
but fails in others, and we strongly
recommend that the wildcard resolution of resources
coming from jars be thoroughly tested in your
specific environment before you rely on it.
Java Kotlin
JAVA
ApplicationContext ctx =
new ClassPathXmlApplicationContext("classpath*:conf/appContext.xml");
This special prefix specifies that all classpath resources that match the given name
must be obtained
(internally, this essentially happens through a call to
ClassLoader.getResources(…) ) and then merged to
form the final application
context definition.
You can also combine the classpath*: prefix with a PathMatcher pattern in the
rest of the location path
(for example, classpath*:META-INF/*-beans.xml ). In this
case, the resolution strategy is fairly simple: A
ClassLoader.getResources() call is
used on the last non-wildcard path segment to get all the matching
resources in the
class loader hierarchy and then, off each resource, the same PathMatcher resolution
strategy described earlier is used for the wildcard subpath.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 193/373
6/10/22, 3:58 PM Core Technologies
On JDK 9’s module path (Jigsaw), Spring’s classpath scanning generally works as expected.
Putting
resources into a dedicated directory is highly recommendable here as well,
avoiding the
aforementioned portability problems with searching the jar file root level.
Ant-style patterns with classpath: resources are not guaranteed to find matching
resources if the root
package to search is available in multiple classpath locations.
Consider the following example of a
resource location:
com/mycompany/package1/service-context.xml
Now consider an Ant-style path that someone might use to try to find that file:
classpath:com/mycompany/**/service-context.xml
Such a resource may exist in only one location in the classpath, but when a path such as
the preceding
example is used to try to resolve it, the resolver works off the (first)
URL returned by
getResource("com/mycompany"); . If this base package node exists in
multiple ClassLoader locations, the
desired resource may not exist in the first
location found. Therefore, in such cases you should prefer using
classpath*: with the
same Ant-style pattern, which searches all classpath locations that contain the
com.mycompany base package: classpath*:com/mycompany/**/service-context.xml .
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 194/373
6/10/22, 3:58 PM Core Technologies
For backwards compatibility (historical) reasons however, this changes when the
FileSystemApplicationContext is the ResourceLoader . The
FileSystemApplicationContext forces all
attached FileSystemResource instances
to treat all location paths as relative, whether they start with a
leading slash or not.
In practice, this means the following examples are equivalent:
Java Kotlin
JAVA
ApplicationContext ctx =
new FileSystemXmlApplicationContext("conf/context.xml");
Java Kotlin
JAVA
ApplicationContext ctx =
new FileSystemXmlApplicationContext("/conf/context.xml");
The following examples are also equivalent (even though it would make sense for them to be different, as
one
case is relative and the other absolute):
Java Kotlin
JAVA
FileSystemXmlApplicationContext ctx = ...;
ctx.getResource("some/resource/path/myTemplate.txt");
Java Kotlin
JAVA
FileSystemXmlApplicationContext ctx = ...;
ctx.getResource("/some/resource/path/myTemplate.txt");
In practice, if you need true absolute filesystem paths, you should avoid using
absolute paths with
FileSystemResource or FileSystemXmlApplicationContext and
force the use of a UrlResource by using
the file: URL prefix. The following examples
show how to do so:
Java Kotlin
JAVA
// actual context type doesn't matter, the Resource will always be UrlResource
ctx.getResource("file:///some/resource/path/myTemplate.txt");
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 195/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
// force this FileSystemXmlApplicationContext to load its definition via a UrlResource
ApplicationContext ctx =
new FileSystemXmlApplicationContext("file:///conf/context.xml");
Data binding is useful for letting user input be dynamically bound to the domain
model of an application
(or whatever objects you use to process user input). Spring
provides the aptly named DataBinder to do
exactly that. The Validator and the
DataBinder make up the validation package, which is primarily
used in but not
limited to the web layer.
The BeanWrapper is a fundamental concept in the Spring Framework and is used in a lot
of places.
However, you probably do not need to use the BeanWrapper
directly. Because this is reference
documentation, however, we felt that some explanation
might be in order. We explain the BeanWrapper in
this chapter, since, if you are
going to use it at all, you are most likely do so when trying to bind data to
objects.
Spring supports Java Bean Validation through setup infrastructure and an adaptor to
Spring’s own
Validator contract. Applications can enable Bean Validation once globally,
as described in Java Bean
Validation, and use it exclusively for all validation
needs. In the web layer, applications can further register
controller-local Spring
Validator instances per DataBinder , as described in Configuring a DataBinder ,
which can
be useful for plugging in custom validation logic.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 196/373
6/10/22, 3:58 PM Core Technologies
Spring features a Validator interface that you can use to validate objects. The
Validator interface
works by using an Errors object so that, while validating,
validators can report validation failures to the
Errors object.
Java Kotlin
JAVA
public class Person {
The next example provides validation behavior for the Person class by implementing the
following two
methods of the org.springframework.validation.Validator interface:
Java Kotlin
JAVA
public class PersonValidator implements Validator {
/**
*/
return Person.class.equals(clazz);
if (p.getAge() < 0) {
e.rejectValue("age", "negativevalue");
e.rejectValue("age", "too.darn.old");
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 197/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
public class CustomerValidator implements Validator {
if (addressValidator == null) {
if (!addressValidator.supports(Address.class)) {
this.addressValidator = addressValidator;
/**
* This Validator validates Customer instances, and any subclasses of Customer too
*/
return Customer.class.isAssignableFrom(clazz);
try {
errors.pushNestedPath("address");
} finally {
errors.popNestedPath();
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 198/373
6/10/22, 3:58 PM Core Technologies
Validation errors are reported to the Errors object passed to the validator. In the case
of Spring Web
MVC, you can use the <spring:bind/> tag to inspect the error messages, but
you can also inspect the
Errors object yourself. More information about the
methods it offers can be found in the javadoc.
More information on the MessageCodesResolver and the default strategy can be found
in the javadoc of
MessageCodesResolver and
DefaultMessageCodesResolver ,
respectively.
One quite important class in the beans package is the BeanWrapper interface and its
corresponding
implementation ( BeanWrapperImpl ). As quoted from the javadoc, the
BeanWrapper offers functionality to
set and get property values (individually or in
bulk), get property descriptors, and query properties to
determine if they are
readable or writable. Also, the BeanWrapper offers support for nested properties,
enabling the setting of properties on sub-properties to an unlimited depth. The
BeanWrapper also
supports the ability to add standard JavaBeans PropertyChangeListeners
and VetoableChangeListeners ,
without the need for supporting code in the target class.
Last but not least, the BeanWrapper provides
support for setting indexed properties.
The BeanWrapper usually is not used by application code directly
but is used by the
DataBinder and the BeanFactory .
The way the BeanWrapper works is partly indicated by its name: it wraps a bean to
perform actions on that
bean, such as setting and retrieving properties.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 199/373
6/10/22, 3:58 PM Core Technologies
Expression Explanation
(This next section is not vitally important to you if you do not plan to work with
the BeanWrapper directly.
If you use only the DataBinder and the BeanFactory
and their default implementations, you should skip
ahead to the
section on PropertyEditors .)
The following two example classes use the BeanWrapper to get and set
properties:
Java Kotlin
JAVA
public class Company {
return this.name;
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 200/373
6/10/22, 3:58 PM Core Technologies
this.name = name;
return this.managingDirector;
this.managingDirector = managingDirector;
}
}
Java Kotlin
JAVA
public class Employee {
return this.name;
}
this.name = name;
return salary;
this.salary = salary;
}
}
The following code snippets show some examples of how to retrieve and manipulate some of
the
properties of instantiated Company s and Employee s:
Java Kotlin
JAVA
BeanWrapper company = new BeanWrapperImpl(new Company());
company.setPropertyValue(value);
company.setPropertyValue("managingDirector", jim.getWrappedInstance());
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 201/373
6/10/22, 3:58 PM Core Technologies
// retrieving the salary of the managingDirector through the company
Class Explanation
ByteArrayPropertyEditor Editor for byte arrays. Converts strings to their corresponding byte
representations. Registered by default by BeanWrapperImpl .
ClassEditor Parses Strings that represent classes to actual classes and vice-versa.
When a
class is not found, an IllegalArgumentException is thrown. By
default, registered by
BeanWrapperImpl .
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 202/373
6/10/22, 3:58 PM Core Technologies
Class Explanation
InputStreamEditor One-way property editor that can take a string and produce (through
an
intermediate ResourceEditor and Resource ) an InputStream so
that InputStream
properties may be directly set as strings. Note that
the default usage does not close
the InputStream for you. By default,
registered by BeanWrapperImpl .
LocaleEditor Can resolve strings to Locale objects and vice-versa (the string format
is
[language]_[country]_[variant] , same as the toString() method
of
Locale ). Also accepts spaces as separators, as an alternative to
underscores.
By default, registered by BeanWrapperImpl .
PropertiesEditor Can convert strings (formatted with the format defined in the javadoc
of the
java.util.Properties class) to Properties objects. By default,
registered
by BeanWrapperImpl .
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 203/373
6/10/22, 3:58 PM Core Technologies
Class Explanation
Spring uses the java.beans.PropertyEditorManager to set the search path for property
editors that might
be needed. The search path also includes sun.bean.editors , which
includes PropertyEditor
implementations for types such as Font , Color , and most of
the primitive types. Note also that the
standard JavaBeans infrastructure
automatically discovers PropertyEditor classes (without you having to
register them
explicitly) if they are in the same package as the class they handle and have the same
name
as that class, with Editor appended. For example, one could have the following
class and package
structure, which would be sufficient for the SomethingEditor class to be
recognized and used as the
PropertyEditor for Something -typed properties.
com
chank
pop
Something
Note that you can also use the standard BeanInfo JavaBeans mechanism here as well
(described to some
extent
here). The
following example uses the BeanInfo mechanism to explicitly register one or more
PropertyEditor instances with the properties of an associated class:
com
chank
pop
Something
The following Java source code for the referenced SomethingBeanInfo class
associates a
CustomNumberEditor with the age property of the Something class:
Java Kotlin
JAVA
public class SomethingBeanInfo extends SimpleBeanInfo {
try {
@Override
return numberPE;
};
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 204/373
6/10/22, 3:58 PM Core Technologies
}
}
}
Note that all bean factories and application contexts automatically use a number of
built-in property
editors, through their use of a BeanWrapper to
handle property conversions. The standard property
editors that the BeanWrapper
registers are listed in the previous section.
Additionally,
ApplicationContext s also override or add additional editors to handle
resource lookups in a manner
appropriate to the specific application context type.
Consider the following example, which defines a user class called ExoticType and
another class called
DependsOnExoticType , which needs ExoticType set as a property:
Java Kotlin
JAVA
package example;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 205/373
6/10/22, 3:58 PM Core Technologies
this.name = name;
}
}
this.type = type;
}
}
When things are properly set up, we want to be able to assign the type property as a
string, which a
PropertyEditor converts into an actual
ExoticType instance. The following bean definition shows how
to set up this relationship:
XML
<bean id="sample" class="example.DependsOnExoticType">
</bean>
Java Kotlin
JAVA
// converts string representation to ExoticType object
package example;
}
}
Finally, the following example shows how to use CustomEditorConfigurer to register the new
PropertyEditor with the
ApplicationContext , which will then be able to use it as needed:
XML
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
</map>
</property>
</bean>
Using PropertyEditorRegistrar
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 206/373
6/10/22, 3:58 PM Core Technologies
Another mechanism for registering property editors with the Spring container is to
create and use a
PropertyEditorRegistrar . This interface is particularly useful when
you need to use the same set of
property editors in several different situations.
You can write a corresponding registrar and reuse it in
each case.
PropertyEditorRegistrar instances work in conjunction with an interface called
PropertyEditorRegistry , an interface that is implemented by the Spring BeanWrapper
(and DataBinder ).
PropertyEditorRegistrar instances are particularly convenient
when used in conjunction with
CustomEditorConfigurer (described
here), which exposes a property
called
setPropertyEditorRegistrars(..) . PropertyEditorRegistrar instances added
to a
CustomEditorConfigurer in this fashion can easily be shared with DataBinder and
Spring MVC
controllers. Furthermore, it avoids the need for synchronization on custom
editors: A
PropertyEditorRegistrar is expected to create fresh PropertyEditor
instances for each bean creation
attempt.
The following example shows how to create your own PropertyEditorRegistrar implementation:
Java Kotlin
JAVA
package com.foo.editors.spring;
// you could register as many custom property editors as are required here...
}
}
The next example shows how to configure a CustomEditorConfigurer and inject an instance
of our
CustomPropertyEditorRegistrar into it:
XML
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<ref bean="customPropertyEditorRegistrar"/>
</list>
</property>
</bean>
<bean id="customPropertyEditorRegistrar"
class="com.foo.editors.spring.CustomPropertyEditorRegistrar"/>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 207/373
6/10/22, 3:58 PM Core Technologies
Finally (and in a bit of a departure from the focus of this chapter) for those of you
using Spring’s MVC web
framework, using a PropertyEditorRegistrar in
conjunction with data-binding web controllers can be
very convenient. The following
example uses a PropertyEditorRegistrar in the implementation of an
@InitBinder method:
Java Kotlin
JAVA
@Controller
RegisterUserController(PropertyEditorRegistrar propertyEditorRegistrar) {
this.customPropertyEditorRegistrar = propertyEditorRegistrar;
@InitBinder
this.customPropertyEditorRegistrar.registerCustomEditors(binder);
JAVA
package org.springframework.core.convert.converter;
T convert(S source);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 208/373
6/10/22, 3:58 PM Core Technologies
To create your own converter, implement the Converter interface and parameterize S
as the type you
are converting from and T as the type you are converting to. You can also transparently apply such a
converter if a collection or array of S needs to be
converted to an array or collection of T , provided that
a delegating array or collection
converter has been registered as well (which DefaultConversionService
does by default).
For each call to convert(S) , the source argument is guaranteed to not be null. Your
Converter may
throw any unchecked exception if conversion fails. Specifically, it should throw an
IllegalArgumentException to report an invalid source value.
Take care to ensure that your Converter
implementation is thread-safe.
JAVA
package org.springframework.core.convert.support;
return Integer.valueOf(source);
}
}
JAVA
package org.springframework.core.convert.converter;
Parameterize S to be the type you are converting from and R to be the base type defining
the range of
classes you can convert to. Then implement getConverter(Class<T>) ,
where T is a subclass of R.
JAVA
package org.springframework.core.convert.support;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 209/373
6/10/22, 3:58 PM Core Technologies
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
this.enumType = enumType;
}
}
JAVA
package org.springframework.core.convert.converter;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 210/373
6/10/22, 3:58 PM Core Technologies
Using ConditionalGenericConverter
Sometimes, you want a Converter to run only if a specific condition holds true. For
example, you might
want to run a Converter only if a specific annotation is present
on the target field, or you might want to
run a Converter only if a specific method
(such as a static valueOf method) is defined on the target
class.
ConditionalGenericConverter is the union of the GenericConverter and
ConditionalConverter
interfaces that lets you define such custom matching criteria:
JAVA
public interface ConditionalConverter {
JAVA
package org.springframework.core.convert;
To register a default ConversionService with Spring, add the following bean definition
with an id of
conversionService :
XML
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean"/>
XML
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="example.MyCustomConverter"/>
</set>
</property>
</bean>
In certain situations, you may wish to apply formatting during conversion. See
The FormatterRegistry SPI
for details on using FormattingConversionServiceFactoryBean .
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 212/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Service
this.conversionService = conversionService;
this.conversionService.convert(...)
}
}
For most use cases, you can use the convert method that specifies the targetType , but it
does not work
with more complex types, such as a collection of a parameterized element.
For example, if you want to
convert a List of Integer to a List of String programmatically,
you need to provide a formal
definition of the source and target types.
Java Kotlin
JAVA
DefaultConversionService cs = new DefaultConversionService();
cs.convert(input,
TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(String.class)));
Converters for value types are reused for arrays and collections, so there is
no need to create a specific
converter to convert from a Collection of S to a
Collection of T , assuming that standard collection
handling is appropriate.
Now consider the type conversion requirements of a typical client environment, such as a
web or desktop
application. In such environments, you typically convert from String
to support the client postback
process, as well as back to String to support the
view rendering process. In addition, you often need to
localize String values. The more
general core.convert Converter SPI does not address such
formatting requirements
directly. To directly address them, Spring 3 introduced a convenient Formatter
SPI that
provides a simple and robust alternative to PropertyEditor implementations for client
environments.
In general, you can use the Converter SPI when you need to implement general-purpose type
conversion
logic — for example, for converting between a java.util.Date and a Long .
You can use the Formatter
SPI when you work in a client environment (such as a web
application) and need to parse and print
localized field values. The ConversionService
provides a unified type conversion API for both SPIs.
JAVA
package org.springframework.format;
Formatter extends from the Printer and Parser building-block interfaces. The
following listing shows
the definitions of those two interfaces:
JAVA
public interface Printer<T> {
JAVA
import java.text.ParseException;
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 214/373
6/10/22, 3:58 PM Core Technologies
To create your own Formatter , implement the Formatter interface shown earlier.
Parameterize T to be
the type of object you wish to format — for example,
java.util.Date . Implement the print() operation
to print an instance of T for
display in the client locale. Implement the parse() operation to parse an
instance of
T from the formatted representation returned from the client locale. Your Formatter
should
throw a ParseException or an IllegalArgumentException if a parse attempt fails. Take
care to ensure
that your Formatter implementation is thread-safe.
Java Kotlin
JAVA
package org.springframework.format.datetime;
this.pattern = pattern;
if (date == null) {
return "";
return getDateFormat(locale).format(date);
if (formatted.length() == 0) {
return null;
return getDateFormat(locale).parse(formatted);
dateFormat.setLenient(false);
return dateFormat;
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 215/373
6/10/22, 3:58 PM Core Technologies
JAVA
package org.springframework.format;
Set<Class<?>> getFieldTypes();
To create an implementation:
Java Kotlin
JAVA
public final class NumberFormatAnnotationFormatterFactory
implements AnnotationFormatterFactory<NumberFormat> {
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 216/373
6/10/22, 3:58 PM Core Technologies
return new NumberStyleFormatter(annotation.pattern());
} else {
if (style == Style.PERCENT) {
} else {
return new NumberStyleFormatter();
}
}
To trigger formatting, you can annotate fields with @NumberFormat, as the following
example shows:
Java Kotlin
JAVA
public class MyModel {
@NumberFormat(style=Style.CURRENCY)
Java Kotlin
JAVA
public class MyModel {
@DateTimeFormat(iso=ISO.DATE)
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 217/373
6/10/22, 3:58 PM Core Technologies
JAVA
package org.springframework.format;
As shown in the preceding listing, you can register formatters by field type or by annotation.
The FormatterRegistry SPI lets you configure formatting rules centrally, instead of
duplicating such
configuration across your controllers. For example, you might want to
enforce that all date fields are
formatted a certain way or that fields with a specific
annotation are formatted in a certain way. With a
shared FormatterRegistry , you define
these rules once, and they are applied whenever formatting is
needed.
JAVA
package org.springframework.format;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 218/373
6/10/22, 3:58 PM Core Technologies
To do that, ensure that Spring does not register default formatters. Instead, register
formatters manually
with the help of:
org.springframework.format.datetime.standard.DateTimeFormatterRegistrar
org.springframework.format.datetime.DateFormatterRegistrar
For example, the following Java configuration registers a global yyyyMMdd format:
Java Kotlin
JAVA
@Configuration
@Bean
conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory
registrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyyMMdd"));
registrar.registerFormatters(conversionService);
registrar.setFormatter(new DateFormatter("yyyyMMdd"));
registrar.registerFormatters(conversionService);
return conversionService;
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 219/373
6/10/22, 3:58 PM Core Technologies
XML
<?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>
<property name="formatters">
<set>
<bean class="org.springframework.format.number.NumberFormatAnnotationFormatterFacto
</set>
</property>
<property name="formatterRegistrars">
<set>
<bean class="org.springframework.format.datetime.standard.DateTimeFormatterRegistra
<property name="dateFormatter">
<bean class="org.springframework.format.datetime.standard.DateTimeFormatter
<property name="pattern" value="yyyyMMdd"/>
</bean>
</property>
</bean>
</set>
</property>
</bean>
</beans>
Note there are extra considerations when configuring date and time formats in web
applications. Please
see
WebMVC Conversion and Formatting or
WebFlux Conversion and Formatting.
Consider the following example, which shows a simple PersonForm model with two properties:
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 220/373
6/10/22, 3:58 PM Core Technologies
JAVA
public class PersonForm {
Bean Validation lets you declare constraints as the following example shows:
Java Kotlin
JAVA
public class PersonForm {
@NotNull
@Size(max=64)
@Min(0)
A Bean Validation validator then validates instances of this class based on the declared
constraints. See
Bean Validation for general information about
the API. See the Hibernate Validator documentation for
specific constraints. To learn how to set up a bean validation provider as a Spring
bean, keep reading.
Java XML
JAVA
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@Configuration
@Bean
}
}
The basic configuration in the preceding example triggers bean validation to initialize by
using its default
bootstrap mechanism. A Bean Validation provider, such as the Hibernate
Validator, is expected to be
present in the classpath and is automatically detected.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 221/373
6/10/22, 3:58 PM Core Technologies
Injecting a Validator
LocalValidatorFactoryBean implements both javax.validation.ValidatorFactory and
javax.validation.Validator , as well as Spring’s org.springframework.validation.Validator .
You can
inject a reference to either of these interfaces into beans that need to invoke
validation logic.
You can inject a reference to javax.validation.Validator if you prefer to work with the Bean
Validation
API directly, as the following example shows:
Java Kotlin
JAVA
import javax.validation.Validator;
@Service
@Autowired
Java Kotlin
JAVA
import org.springframework.validation.Validator;
@Service
@Autowired
A @Constraint annotation that declares the constraint and its configurable properties.
An implementation of the javax.validation.ConstraintValidator interface that implements
the
constraint’s behavior.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 222/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=MyConstraintValidator.class)
Java Kotlin
JAVA
import javax.validation.ConstraintValidator;
@Autowired;
private Foo aDependency;
// ...
}
As the preceding example shows, a ConstraintValidator implementation can have its dependencies
@Autowired as any other Spring bean.
Java XML
JAVA
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
@Configuration
@Bean
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 223/373
6/10/22, 3:58 PM Core Technologies
To be eligible for Spring-driven method validation, all target classes need to be annotated
with Spring’s
@Validated annotation, which can optionally also declare the validation
groups to use. See
MethodValidationPostProcessor
for setup details with the Hibernate Validator and Bean Validation 1.1
providers.
The following example shows how to use a DataBinder programmatically to invoke validation
logic after
binding to a target object:
Java Kotlin
JAVA
Foo target = new Foo();
binder.setValidator(new FooValidator());
binder.bind(propertyValues);
binder.validate();
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 224/373
6/10/22, 3:58 PM Core Technologies
While there are several other Java expression languages available — OGNL, MVEL, and JBoss
EL, to name a
few — the Spring Expression Language was created to provide the Spring
community with a single well
supported expression language that can be used across all
the products in the Spring portfolio. Its
language features are driven by the
requirements of the projects in the Spring portfolio, including tooling
requirements
for code completion support within the Spring Tools for Eclipse.
That said, SpEL is based on
a technology-agnostic API that lets other expression language
implementations be integrated, should the
need arise.
While SpEL serves as the foundation for expression evaluation within the Spring
portfolio, it is not directly
tied to Spring and can be used independently. To
be self contained, many of the examples in this chapter
use SpEL as if it were an
independent expression language. This requires creating a few bootstrapping
infrastructure classes, such as the parser. Most Spring users need not deal with
this infrastructure and
can, instead, author only expression strings for evaluation.
An example of this typical use is the integration
of SpEL into creating XML or
annotation-based bean definitions, as shown in
Expression support for
defining bean definitions.
This chapter covers the features of the expression language, its API, and its language
syntax. In several
places, Inventor and Society classes are used as the target
objects for expression evaluation. These
class declarations and the data used to
populate them are listed at the end of the chapter.
Literal expressions
Boolean and relational operators
Regular expressions
Class expressions
Accessing properties, arrays, lists, and maps
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 225/373
6/10/22, 3:58 PM Core Technologies
Method invocation
Relational operators
Assignment
Calling constructors
Bean references
Array construction
Inline lists
Inline maps
Ternary operator
Variables
User-defined functions
Collection projection
Collection selection
Templated expressions
4.1. Evaluation
This section introduces the simple use of SpEL interfaces and its expression language.
The complete
language reference can be found in
Language Reference.
The following code introduces the SpEL API to evaluate the literal string expression,
Hello World .
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
The SpEL classes and interfaces you are most likely to use are located in the
org.springframework.expression package and its sub-packages, such as spel.support .
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 226/373
6/10/22, 3:58 PM Core Technologies
SpEL supports a wide range of features, such as calling methods, accessing properties,
and calling
constructors.
In the following example of method invocation, we call the concat method on the string literal:
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
The following example of calling a JavaBean property calls the String property Bytes :
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
// invokes 'getBytes()'
SpEL also supports nested properties by using the standard dot notation (such as
prop1.prop2.prop3 )
and also the corresponding setting of property values.
Public fields may also be accessed.
The following example shows how to use dot notation to get the length of a literal:
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
// invokes 'getBytes().length'
The String’s constructor can be called instead of using a string literal, as the following
example shows:
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
1 Construct a new String from the literal and make it be upper case.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 227/373
6/10/22, 3:58 PM Core Technologies
Note the use of the generic method: public <T> T getValue(Class<T> desiredResultType) .
Using this
method removes the need to cast the value of the expression to the desired
result type. An
EvaluationException is thrown if the value cannot be cast to the
type T or converted by using the
registered type converter.
The more common usage of SpEL is to provide an expression string that is evaluated
against a specific
object instance (called the root object). The following example shows
how to retrieve the name property
from an instance of the Inventor class or
create a boolean condition:
Java Kotlin
JAVA
// Create and set a calendar
c.set(1856, 7, 9);
// result == true
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 228/373
6/10/22, 3:58 PM Core Technologies
Type Conversion
By default, SpEL uses the conversion service available in Spring core
( org.springframework.core.convert.ConversionService ). This conversion service comes
with many built-
in converters for common conversions but is also fully extensible so that
you can add custom conversions
between types. Additionally, it is
generics-aware. This means that, when you work with generic types in
expressions, SpEL attempts conversions to maintain type correctness for any objects
it encounters.
What does this mean in practice? Suppose assignment, using setValue() , is being used
to set a List
property. The type of the property is actually List<Boolean> . SpEL
recognizes that the elements of the list
need to be converted to Boolean before
being placed in it. The following example shows how to do so:
Java Kotlin
JAVA
class Simple {
simple.booleanList.add(true);
// b is false
Boolean b = simple.booleanList.get(0);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 229/373
6/10/22, 3:58 PM Core Technologies
built-in
or custom converter that knows how to set the value, null will remain in the array or
list at the
specified index. The following example demonstrates how to automatically grow
the list:
Java Kotlin
JAVA
class Demo {
// Turn on:
Object o = expression.getValue(demo);
The SpEL compiler is intended to address this need. During evaluation, the compiler
generates a Java class
that embodies the expression behavior at runtime and uses that
class to achieve much faster expression
evaluation. Due to the lack of typing around
expressions, the compiler uses information gathered during
the interpreted evaluations
of an expression when performing compilation. For example, it does not know
the type
of a property reference purely from the expression, but during the first interpreted
evaluation, it
finds out what it is. Of course, basing compilation on such derived
information can cause trouble later if
the types of the various expression elements
change over time. For this reason, compilation is best suited
to expressions whose
type information is not going to change on repeated evaluations.
Because the preceding expression involves array access, some property de-referencing,
and numeric
operations, the performance gain can be very noticeable. In an example
micro benchmark run of 50000
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 230/373
6/10/22, 3:58 PM Core Technologies
Compiler Configuration
The compiler is not turned on by default, but you can turn it on in either of two
different ways. You can
turn it on by using the parser configuration process
(discussed earlier) or by using a Spring property
when
SpEL usage is embedded inside another component. This section discusses both of
these options.
The compiler can operate in one of three modes, which are captured in the
org.springframework.expression.spel.SpelCompilerMode enum. The modes are as follows:
IMMEDIATE mode exists because MIXED mode could cause issues for expressions that
have side effects. If
a compiled expression blows up after partially succeeding, it
may have already done something that has
affected the state of the system. If this
has happened, the caller may not want it to silently re-run in
interpreted mode,
since part of the expression may be running twice.
After selecting a mode, use the SpelParserConfiguration to configure the parser. The
following example
shows how to do so:
Java Kotlin
JAVA
SpelParserConfiguration config = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE,
this.getClass().getClassLoader());
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 231/373
6/10/22, 3:58 PM Core Technologies
When you specify the compiler mode, you can also specify a classloader (passing null is allowed).
Compiled
expressions are defined in a child classloader created under any that is supplied.
It is important to ensure
that, if a classloader is specified, it can see all the types involved in
the expression evaluation process. If
you do not specify a classloader, a default classloader is used
(typically the context classloader for the
thread that is running during expression evaluation).
The second way to configure the compiler is for use when SpEL is embedded inside some
other
component and it may not be possible to configure it through a configuration
object. In these cases, it is
possible to set the spring.expression.compiler.mode
property via a JVM system property (or via the
SpringProperties mechanism) to one of the
SpelCompilerMode enum values ( off , immediate , or
mixed ).
Compiler Limitations
Since Spring Framework 4.1, the basic compilation framework is in place. However, the framework
does
not yet support compiling every kind of expression. The initial focus has been on the
common expressions
that are likely to be used in performance-critical contexts. The following
kinds of expression cannot be
compiled at the moment:
XML
<bean id="numberGuess" class="org.spring.samples.NumberGuess">
</bean>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 232/373
6/10/22, 3:58 PM Core Technologies
All beans in the application context are available as predefined variables with their
common bean name.
This includes standard context beans such as environment (of type
org.springframework.core.env.Environment ) as well as systemProperties and
systemEnvironment (of
type Map<String, Object> ) for access to the runtime environment.
The following example shows access to the systemProperties bean as a SpEL variable:
XML
<bean id="taxCalculator" class="org.spring.samples.TaxCalculator">
</bean>
Note that you do not have to prefix the predefined variable with the # symbol here.
You can also refer to other bean properties by name, as the following example shows:
XML
<bean id="numberGuess" class="org.spring.samples.NumberGuess">
</bean>
</bean>
Java Kotlin
JAVA
public class FieldValueTestBean {
this.defaultLocale = defaultLocale;
return this.defaultLocale;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 233/373
6/10/22, 3:58 PM Core Technologies
}
}
The following example shows the equivalent but on a property setter method:
Java Kotlin
JAVA
public class PropertyValueTestBean {
this.defaultLocale = defaultLocale;
return this.defaultLocale;
}
}
Autowired methods and constructors can also use the @Value annotation, as the following
examples
show:
Java Kotlin
JAVA
public class SimpleMovieLister {
@Autowired
this.movieFinder = movieFinder;
this.defaultLocale = defaultLocale;
// ...
}
Java Kotlin
JAVA
public class MovieRecommender {
this.customerPreferenceDao = customerPreferenceDao;
this.defaultLocale = defaultLocale;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 234/373
6/10/22, 3:58 PM Core Technologies
}
// ...
}
Literal Expressions
Properties, Arrays, Lists, Maps, and Indexers
Inline Lists
Inline Maps
Array Construction
Methods
Operators
Types
Constructors
Variables
Functions
Bean References
Ternary Operator (If-Then-Else)
The Elvis Operator
Safe Navigation Operator
The following listing shows simple usage of literals. Typically, they are not used
in isolation like this but,
rather, as part of a more complex expression — for example,
using a literal on one side of a logical
comparison operator.
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 235/373
6/10/22, 3:58 PM Core Technologies
JAVA
ExpressionParser parser = new SpelExpressionParser();
// evals to 2147483647
Numbers support the use of the negative sign, exponential notation, and decimal points.
By default, real
numbers are parsed by using Double.parseDouble() .
Java Kotlin
JAVA
// evals to 1856
Case insensitivity is allowed for the first letter of property names. Thus, the
expressions in the above
example may be written as Birthdate.Year + 1900 and
PlaceOfBirth.City , respectively. In
addition, properties may optionally be accessed via
method invocations — for example,
getPlaceOfBirth().getCity() instead of
placeOfBirth.city .
The contents of arrays and lists are obtained by using square bracket notation, as the
following example
shows:
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
// Inventions Array
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 236/373
6/10/22, 3:58 PM Core Technologies
// Members List
The contents of maps are obtained by specifying the literal key value within the
brackets. In the following
example, because keys for the officers map are strings, we can specify
string literals:
Java Kotlin
JAVA
// Officer's Dictionary
societyContext, Inventor.class);
// evaluates to "Idvor"
societyContext, String.class);
// setting values
parser.parseExpression("officers['advisors'][0].placeOfBirth.country").setValue(
societyContext, "Croatia");
Java Kotlin
JAVA
// evaluates to a Java list containing the four numbers
{} by itself means an empty list. For performance reasons, if the list is itself
entirely composed of fixed
literals, a constant list is created to represent the
expression (rather than building a new list on each
evaluation).
You can also directly express maps in an expression by using {key:value} notation. The
following
example shows how to do so:
Java Kotlin
JAVA
// evaluates to a Java map containing the two entries
{:} by itself means an empty map. For performance reasons, if the map is itself
composed of fixed
literals or other nested constant structures (lists or maps), a
constant map is created to represent the
expression (rather than building a new map on
each evaluation). Quoting of the map keys is optional
(unless the key contains a period
( . )). The examples above do not use quoted keys.
Java Kotlin
JAVA
int[] numbers1 = (int[]) parser.parseExpression("new int[4]").getValue(context);
You cannot currently supply an initializer when you construct a multi-dimensional array.
4.3.6. Methods
You can invoke methods by using typical Java programming syntax. You can also invoke methods
on
literals. Variable arguments are also supported. The following examples show how to
invoke methods:
Java Kotlin
JAVA
// string literal, evaluates to "bc"
// evaluates to true
societyContext, Boolean.class);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 238/373
6/10/22, 3:58 PM Core Technologies
4.3.7. Operators
The Spring Expression Language supports the following kinds of operators:
Relational Operators
Logical Operators
Mathematical Operators
The Assignment Operator
Relational Operators
The relational operators (equal, not equal, less than, less than or equal, greater than,
and greater than or
equal) are supported by using standard operator notation. The
following listing shows a few examples of
operators:
Java Kotlin
JAVA
// evaluates to true
// evaluates to false
// evaluates to true
Greater-than and less-than comparisons against null follow a simple rule: null is treated as
nothing (that is NOT as zero). As a consequence, any other value is always greater
than null ( X >
null is always true ) and no other value is ever less than nothing
( X < null is always false ).
In addition to the standard relational operators, SpEL supports the instanceof and regular
expression-
based matches operator. The following listing shows examples of both:
Java Kotlin
JAVA
// evaluates to false
// evaluates to true
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 239/373
6/10/22, 3:58 PM Core Technologies
boolean trueValue = parser.parseExpression(
// evaluates to false
Each symbolic operator can also be specified as a purely alphabetic equivalent. This
avoids problems
where the symbols used have special meaning for the document type in
which the expression is
embedded (such as in an XML document). The textual equivalents are:
lt (<)
gt (>)
le ( <= )
ge ( >= )
eq ( == )
ne ( != )
div (/)
mod (%)
not ( ! ).
Logical Operators
SpEL supports the following logical operators:
and ( && )
or ( || )
not (!)
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 240/373
6/10/22, 3:58 PM Core Technologies
JAVA
// -- AND --
// evaluates to false
// evaluates to true
// -- OR --
// evaluates to true
// evaluates to true
// -- NOT --
// evaluates to false
Mathematical Operators
You can use the addition operator ( + ) on both numbers and strings. You can use the
subtraction ( - ),
multiplication ( * ), and division ( / ) operators only on numbers.
You can also use the modulus ( % ) and
exponential power ( ^ ) operators on numbers.
Standard operator precedence is enforced. The following
example shows the mathematical
operators in use:
Java Kotlin
JAVA
// Addition
// Subtraction
// Multiplication
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 241/373
6/10/22, 3:58 PM Core Technologies
// Division
// Modulus
int three = parser.parseExpression("7 % 4").getValue(Integer.class); // 3
// Operator precedence
Java Kotlin
JAVA
Inventor inventor = new Inventor();
// alternatively
4.3.8. Types
You can use the special T operator to specify an instance of java.lang.Class (the
type). Static methods
are invoked by using this operator as well. The
StandardEvaluationContext uses a TypeLocator to find
types, and the
StandardTypeLocator (which can be replaced) is built with an understanding of the
java.lang package. This means that T() references to types within the java.lang
package do not need
to be fully qualified, but all other type references must be. The
following example shows how to use the T
operator:
Java Kotlin
JAVA
Class dateClass = parser.parseExpression("T(java.util.Date)").getValue(Class.class);
.getValue(Boolean.class);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 242/373
6/10/22, 3:58 PM Core Technologies
4.3.9. Constructors
You can invoke constructors by using the new operator. You should use the fully
qualified class name for
all types except those located in the java.lang package
( Integer , Float , String , and so on). The
following example shows how to use the
new operator to invoke constructors:
Java Kotlin
JAVA
Inventor einstein = p.parseExpression(
.getValue(Inventor.class);
p.parseExpression(
"Members.add(new org.spring.samples.spel.inventor.Inventor(
4.3.10. Variables
You can reference variables in the expression by using the #variableName syntax. Variables
are set by
using the setVariable method on EvaluationContext implementations.
Valid variable names must be composed of one or more of the following supported
characters.
letters: A to Z and a to z
digits: 0 to 9
underscore: _
dollar sign: $
Java Kotlin
JAVA
Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
The #this variable is always defined and refers to the current evaluation object
(against which
unqualified references are resolved). The #root variable is always
defined and refers to the root context
object. Although #this may vary as components of
an expression are evaluated, #root always refers to
the root. The following examples
show how to use the #this and #root variables:
Java Kotlin
JAVA
// create an array of integers
primes.addAll(Arrays.asList(2,3,5,7,11,13,17));
context.setVariable("primes", primes);
// all prime numbers > 10 from the list (using selection ?{...})
"#primes.?[#this>10]").getValue(context);
4.3.11. Functions
You can extend SpEL by registering user-defined functions that can be called within the
expression string.
The function is registered through the EvaluationContext . The
following example shows how to register a
user-defined function:
Java Kotlin
JAVA
Method method = ...;
context.setVariable("myFunction", method);
For example, consider the following utility method that reverses a string:
Java Kotlin
JAVA
public abstract class StringUtils {
return backwards.toString();
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 244/373
6/10/22, 3:58 PM Core Technologies
You can then register and use the preceding method, as the following example shows:
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
context.setVariable("reverseString",
StringUtils.class.getDeclaredMethod("reverseString", String.class));
"#reverseString('hello')").getValue(context, String.class);
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
context.setBeanResolver(new MyBeanResolver());
To access a factory bean itself, you should instead prefix the bean name with an & symbol.
The following
example shows how to do so:
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
context.setBeanResolver(new MyBeanResolver());
Java Kotlin
JAVA
String falseString = parser.parseExpression(
In this case, the boolean false results in returning the string value 'falseExp' . A more
realistic example
follows:
Java Kotlin
JAVA
parser.parseExpression("name").setValue(societyContext, "IEEE");
"+ Name + ' Society' : #queryName + ' is not a member of the ' + Name + ' Society'";
.getValue(societyContext, String.class);
See the next section on the Elvis operator for an even shorter syntax for the
ternary operator.
GROOVY
String name = "Elvis Presley";
Instead, you can use the Elvis operator (named for the resemblance to Elvis' hair style).
The following
example shows how to use the Elvis operator:
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
System.out.println(name); // 'Unknown'
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
tesla.setName(null);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 246/373
6/10/22, 3:58 PM Core Technologies
name = parser.parseExpression("name?:'Elvis Presley'").getValue(context, tesla, String.class);
You can use the Elvis operator to apply default values in expressions. The following
example shows
how to use the Elvis operator in a @Value expression:
JAVA
@Value("#{systemProperties['pop3.port'] ?: 25}")
Java Kotlin
JAVA
ExpressionParser parser = new SpelExpressionParser();
tesla.setPlaceOfBirth(new PlaceOfBirth("Smiljan"));
System.out.println(city); // Smiljan
tesla.setPlaceOfBirth(null);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 247/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
List<Inventor> list = (List<Inventor>) parser.parseExpression(
"members.?[nationality == 'Serbian']").getValue(societyContext);
The following expression returns a new map that consists of those elements of the
original map where the
entry’s value is less than 27:
Java Kotlin
JAVA
Map newMap = parser.parseExpression("map.?[value<27]").getValue();
In addition to returning all the selected elements, you can retrieve only the first or
the last element. To
obtain the first element matching the selection, the syntax is
.^[selectionExpression] . To obtain the last
matching selection, the syntax is
.$[selectionExpression] .
Java Kotlin
JAVA
// returns ['Smiljan', 'Idvor' ]
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 248/373
6/10/22, 3:58 PM Core Technologies
Expression templates allow mixing literal text with one or more evaluation blocks.
Each evaluation block is
delimited with prefix and suffix characters that you can
define. A common choice is to use #{ } as the
delimiters, as the following example
shows:
Java Kotlin
JAVA
String randomPhrase = parser.parseExpression(
new TemplateParserContext()).getValue(String.class);
The string is evaluated by concatenating the literal text 'random number is ' with the
result of evaluating
the expression inside the #{ } delimiter (in this case, the result
of calling that random() method). The
second argument to the parseExpression() method
is of the type ParserContext . The ParserContext
interface is used to influence how
the expression is parsed in order to support the expression templating
functionality.
The definition of TemplateParserContext follows:
Java Kotlin
JAVA
public class TemplateParserContext implements ParserContext {
return "#{";
}
return "}";
return true;
}
}
Inventor.Java Inventor.kt
JAVA
package org.spring.samples.spel.inventor;
import java.util.Date;
import java.util.GregorianCalendar;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 249/373
6/10/22, 3:58 PM Core Technologies
private String[] inventions;
this.name = name;
this.nationality = nationality;
this.birthdate = c.getTime();
this.name = name;
this.nationality = nationality;
this.birthdate = birthdate;
public Inventor() {
return name;
}
this.name = name;
return nationality;
this.nationality = nationality;
return birthdate;
this.birthdate = birthdate;
return placeOfBirth;
this.placeOfBirth = placeOfBirth;
this.inventions = inventions;
return inventions;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 250/373
6/10/22, 3:58 PM Core Technologies
}
}
PlaceOfBirth.java PlaceOfBirth.kt
JAVA
package org.spring.samples.spel.inventor;
this.city=city;
this(city);
this.country = country;
return city;
}
this.city = s;
return country;
this.country = country;
}
}
Society.java Society.kt
JAVA
package org.spring.samples.spel.inventor;
import java.util.*;
return members;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 251/373
6/10/22, 3:58 PM Core Technologies
}
return name;
}
this.name = name;
if (inventor.getName().equals(name)) {
return true;
return false;
}
}
One of the key components of Spring is the AOP framework. While the Spring IoC
container does not
depend on AOP (meaning you do not need to use AOP if you don’t want
to), AOP complements Spring IoC
to provide a very capable middleware solution.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 252/373
6/10/22, 3:58 PM Core Technologies
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 253/373
6/10/22, 3:58 PM Core Technologies
Before advice: Advice that runs before a join point but that does not have
the ability to prevent
execution flow proceeding to the join point (unless it throws
an exception).
After returning advice: Advice to be run after a join point completes
normally (for example, if a method
returns without throwing an exception).
After throwing advice: Advice to be run if a method exits by throwing an
exception.
After (finally) advice: Advice to be run regardless of the means by which a
join point exits (normal or
exceptional return).
Around advice: Advice that surrounds a join point such as a method invocation.
This is the most
powerful kind of advice. Around advice can perform custom behavior
before and after the method
invocation. It is also responsible for choosing whether to
proceed to the join point or to shortcut the
advised method execution by returning its
own return value or throwing an exception.
Around advice is the most general kind of advice. Since Spring AOP, like AspectJ,
provides a full range of
advice types, we recommend that you use the least powerful
advice type that can implement the required
behavior. For example, if you need only to
update a cache with the return value of a method, you are
better off implementing an
after returning advice than an around advice, although an around advice can
accomplish
the same thing. Using the most specific advice type provides a simpler programming model
with less potential for errors. For example, you do not need to invoke the proceed()
method on the
JoinPoint used for around advice, and, hence, you cannot fail to invoke it.
All advice parameters are statically typed so that you work with advice parameters of
the appropriate type
(e.g. the type of the return value from a method execution) rather
than Object arrays.
The concept of join points matched by pointcuts is the key to AOP, which distinguishes
it from older
technologies offering only interception. Pointcuts enable advice to be
targeted independently of the
object-oriented hierarchy. For example, you can apply an
around advice providing declarative transaction
management to a set of methods that span
multiple objects (such as all business operations in the service
layer).
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 254/373
6/10/22, 3:58 PM Core Technologies
Spring AOP currently supports only method execution join points (advising the execution
of methods on
Spring beans). Field interception is not implemented, although support for
field interception could be
added without breaking the core Spring AOP APIs. If you need
to advise field access and update join
points, consider a language such as AspectJ.
Spring AOP’s approach to AOP differs from that of most other AOP frameworks. The aim is
not to provide
the most complete AOP implementation (although Spring AOP is quite
capable). Rather, the aim is to
provide a close integration between AOP implementation and
Spring IoC, to help solve common problems
in enterprise applications.
Thus, for example, the Spring Framework’s AOP functionality is normally used in
conjunction with the
Spring IoC container. Aspects are configured by using normal bean
definition syntax (although this allows
powerful “auto-proxying” capabilities). This is a
crucial difference from other AOP implementations. You
cannot do some things
easily or efficiently with Spring AOP, such as advise very fine-grained objects
(typically,
domain objects). AspectJ is the best choice in such cases. However, our
experience is that Spring
AOP provides an excellent solution to most problems in
enterprise Java applications that are amenable to
AOP.
Spring AOP never strives to compete with AspectJ to provide a comprehensive AOP
solution. We believe
that both proxy-based frameworks such as Spring AOP and full-blown
frameworks such as AspectJ are
valuable and that they are complementary, rather than in
competition. Spring seamlessly integrates
Spring AOP and IoC with AspectJ, to enable
all uses of AOP within a consistent Spring-based application
architecture. This integration does not affect the Spring AOP API or the AOP Alliance
API. Spring AOP
remains backward-compatible. See the following chapter
for a discussion of the Spring AOP APIs.
One of the central tenets of the Spring Framework is that of non-invasiveness. This
is the idea that
you should not be forced to introduce framework-specific classes and
interfaces into your business
or domain model. However, in some places, the Spring Framework
does give you the option to
introduce Spring Framework-specific dependencies into your
codebase. The rationale in giving you
such options is because, in certain scenarios, it
might be just plain easier to read or code some
specific piece of functionality in such
a way. However, the Spring Framework (almost) always offers
you the choice: You have the
freedom to make an informed decision as to which option best suits
your particular use
case or scenario.
One such choice that is relevant to this chapter is that of which AOP framework (and
which AOP
style) to choose. You have the choice of AspectJ, Spring AOP, or both. You
also have the choice of
either the @AspectJ annotation-style approach or the Spring XML
configuration-style approach. The
fact that this chapter chooses to introduce the
@AspectJ-style approach first should not be taken as
an indication that the Spring team
favors the @AspectJ annotation-style approach over the Spring
XML configuration-style.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 255/373
6/10/22, 3:58 PM Core Technologies
See Choosing which AOP Declaration Style to Use for a more complete discussion of the “whys and
wherefores” of
each style.
Spring AOP can also use CGLIB proxies. This is necessary to proxy classes rather than
interfaces. By
default, CGLIB is used if a business object does not implement an
interface. As it is good practice to
program to interfaces rather than classes, business
classes normally implement one or more business
interfaces. It is possible to
force the use of CGLIB, in those (hopefully rare) cases where you
need to advise
a method that is not declared on an interface or where you need to
pass a proxied object to a method as a
concrete type.
Using the AspectJ compiler and weaver enables use of the full AspectJ language and
is discussed in
Using AspectJ with Spring Applications.
The @AspectJ support can be enabled with XML- or Java-style configuration. In either
case, you also need
to ensure that AspectJ’s aspectjweaver.jar library is on the
classpath of your application (version 1.8 or
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 256/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Configuration
@EnableAspectJAutoProxy
XML
<aop:aspectj-autoproxy/>
The first of the two example shows a regular bean definition in the application
context that points to a
bean class that has the @Aspect annotation:
XML
<bean id="myAspect" class="org.xyz.NotVeryUsefulAspect">
</bean>
The second of the two examples shows the NotVeryUsefulAspect class definition,
which is annotated with
the org.aspectj.lang.annotation.Aspect annotation;
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 257/373
6/10/22, 3:58 PM Core Technologies
JAVA
package org.xyz;
import org.aspectj.lang.annotation.Aspect;
@Aspect
Aspects (classes annotated with @Aspect ) can have methods and fields, the same as any
other class. They
can also contain pointcut, advice, and introduction (inter-type)
declarations.
An example may help make this distinction between a pointcut signature and a pointcut
expression clear.
The following example defines a pointcut named anyOldTransfer that
matches the execution of any
method named transfer :
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 258/373
6/10/22, 3:58 PM Core Technologies
JAVA
@Pointcut("execution(* transfer(..))") // the pointcut expression
The pointcut expression that forms the value of the @Pointcut annotation is a regular
AspectJ pointcut
expression. For a full discussion of AspectJ’s pointcut language, see
the AspectJ
Programming Guide (and,
for extensions, the
AspectJ 5
Developer’s Notebook) or one of the books on AspectJ (such as Eclipse
AspectJ, by Colyer
et al., or AspectJ in Action, by Ramnivas Laddad).
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 259/373
6/10/22, 3:58 PM Core Technologies
The set of pointcut designators supported by Spring AOP may be extended in future
releases to
support more of the AspectJ pointcut designators.
Because Spring AOP limits matching to only method execution join points, the preceding discussion
of the
pointcut designators gives a narrower definition than you can find in the
AspectJ programming guide. In
addition, AspectJ itself has type-based semantics and, at
an execution join point, both this and target
refer to the same object: the
object executing the method. Spring AOP is a proxy-based system and
differentiates
between the proxy object itself (which is bound to this ) and the target object behind the
proxy (which is bound to target ).
Due to the proxy-based nature of Spring’s AOP framework, calls within the target object
are, by
definition, not intercepted. For JDK proxies, only public interface method
calls on the proxy can be
intercepted. With CGLIB, public and protected method calls on
the proxy are intercepted (and even
package-visible methods, if necessary). However,
common interactions through proxies should
always be designed through public signatures.
Note that pointcut definitions are generally matched against any intercepted method.
If a pointcut is
strictly meant to be public-only, even in a CGLIB proxy scenario with
potential non-public interactions
through proxies, it needs to be defined accordingly.
If your interception needs include method calls or even constructors within the target
class, consider
the use of Spring-driven native AspectJ weaving instead
of Spring’s proxy-based AOP framework. This
constitutes a different mode of AOP usage
with different characteristics, so be sure to make yourself
familiar with weaving
before making a decision.
Spring AOP also supports an additional PCD named bean . This PCD lets you limit
the matching of join
points to a particular named Spring bean or to a set of named
Spring beans (when using wildcards). The
bean PCD has the following form:
Java Kotlin
JAVA
bean(idOrNameOfBean)
The idOrNameOfBean token can be the name of any Spring bean. Limited wildcard
support that uses the
* character is provided, so, if you establish some naming
conventions for your Spring beans, you can
write a bean PCD expression
to select them. As is the case with other pointcut designators, the bean PCD
can
be used with the && (and), || (or), and ! (negation) operators, too.
The bean PCD operates at the instance level (building on the Spring bean name
concept) rather than
at the type level only (to which weaving-based AOP is limited).
Instance-based pointcut designators
are a special capability of Spring’s
proxy-based AOP framework and its close integration with the
Spring bean factory, where
it is natural and straightforward to identify specific beans by name.
Java Kotlin
JAVA
@Pointcut("execution(public * *(..))")
@Pointcut("within(com.xyz.myapp.trading..*)")
It is a best practice to build more complex pointcut expressions out of smaller named
components, as
shown earlier. When referring to pointcuts by name, normal Java visibility
rules apply (you can see private
pointcuts in the same type, protected pointcuts in the
hierarchy, public pointcuts anywhere, and so on).
Visibility does not affect pointcut
matching.
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 261/373
6/10/22, 3:58 PM Core Technologies
JAVA
package com.xyz.myapp;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
/**
* under that.
*/
@Pointcut("within(com.xyz.myapp.web..*)")
/**
* under that.
*/
@Pointcut("within(com.xyz.myapp.service..*)")
/**
* under that.
*/
@Pointcut("within(com.xyz.myapp.dao..*)")
/**
*/
@Pointcut("execution(* com.xyz.myapp..service.*.*(..))")
/**
* dao interface. This definition assumes that interfaces are placed in the
*/
@Pointcut("execution(* com.xyz.myapp.dao.*.*(..))")
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 262/373
6/10/22, 3:58 PM Core Technologies
You can refer to the pointcuts defined in such an aspect anywhere you need a
pointcut expression. For
example, to make the service layer transactional, you could
write the following:
XML
<aop:config>
<aop:advisor
pointcut="com.xyz.myapp.CommonPointcuts.businessService()"
advice-ref="tx-advice"/>
</aop:config>
<tx:advice id="tx-advice">
<tx:attributes>
</tx:attributes>
</tx:advice>
The <aop:config> and <aop:advisor> elements are discussed in Schema-based AOP Support. The
transaction elements are discussed in Transaction Management.
Examples
Spring AOP users are likely to use the execution pointcut designator the most often.
The format of an
execution expression follows:
All parts except the returning type pattern ( ret-type-pattern in the preceding snippet),
the name
pattern, and the parameters pattern are optional. The returning type pattern determines
what the return
type of the method must be in order for a join point to be matched.
* is most frequently used as the
returning type pattern. It matches any return
type. A fully-qualified type name matches only when the
method returns the given
type. The name pattern matches the method name. You can use the * wildcard
as all or
part of a name pattern. If you specify a declaring type pattern,
include a trailing . to join it to the
name pattern component.
The parameters pattern is slightly more complex: () matches a
method that
takes no parameters, whereas (..) matches any number (zero or more) of parameters.
The (*) pattern
matches a method that takes one parameter of any type.
(*,String) matches a method that takes two
parameters. The first can be of any type, while the
second must be a String . Consult the
Language
Semantics section of the AspectJ Programming Guide for more information.
execution(public * *(..))
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 263/373
6/10/22, 3:58 PM Core Technologies
The execution of any method with a name that begins with set :
execution(* set*(..))
execution(* com.xyz.service.AccountService.*(..))
execution(* com.xyz.service.*.*(..))
The execution of any method defined in the service package or one of its sub-packages:
execution(* com.xyz.service..*.*(..))
Any join point (method execution only in Spring AOP) within the service package:
within(com.xyz.service.*)
Any join point (method execution only in Spring AOP) within the service package or one of its
sub-
packages:
within(com.xyz.service..*)
Any join point (method execution only in Spring AOP) where the proxy implements the
AccountService interface:
this(com.xyz.service.AccountService)
thisis more commonly used in a binding form. See the section on Declaring Advice
for how to
make the proxy object available in the advice body.
Any join point (method execution only in Spring AOP) where the target object
implements the
AccountService interface:
target(com.xyz.service.AccountService)
target is more commonly used in a binding form. See the Declaring Advice section
for how to
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 264/373
6/10/22, 3:58 PM Core Technologies
Any join point (method execution only in Spring AOP) that takes a single parameter
and where the
argument passed at runtime is Serializable :
args(java.io.Serializable)
argsis more commonly used in a binding form. See the Declaring Advice section
for how to
make the method arguments available in the advice body.
Note that the pointcut given in this example is different from execution(*
*(java.io.Serializable)) .
The args version matches if the argument passed at runtime is
Serializable , and the execution
version matches if the method signature declares a single
parameter of type Serializable .
Any join point (method execution only in Spring AOP) where the target object has a
@Transactional
annotation:
@target(org.springframework.transaction.annotation.Transactional)
You can also use @target in a binding form. See the Declaring Advice section for
how to make
the annotation object available in the advice body.
Any join point (method execution only in Spring AOP) where the declared type of the
target object has
an @Transactional annotation:
@within(org.springframework.transaction.annotation.Transactional)
You can also use @within in a binding form. See the Declaring Advice section for
how to make
the annotation object available in the advice body.
Any join point (method execution only in Spring AOP) where the executing method has an
@Transactional annotation:
@annotation(org.springframework.transaction.annotation.Transactional)
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 265/373
6/10/22, 3:58 PM Core Technologies
You can also use @annotation in a binding form. See the Declaring Advice section
for how to
make the annotation object available in the advice body.
Any join point (method execution only in Spring AOP) which takes a single parameter,
and where the
runtime type of the argument passed has the @Classified annotation:
@args(com.xyz.security.Classified)
You can also use @args in a binding form. See the Declaring Advice section
how to make the
annotation object(s) available in the advice body.
Any join point (method execution only in Spring AOP) on a Spring bean named
tradeService :
bean(tradeService)
Any join point (method execution only in Spring AOP) on Spring beans having names that
match the
wildcard expression *Service :
bean(*Service)
However, AspectJ can work only with what it is told. For optimal performance of
matching, you should
think about what they are trying to achieve and narrow the search
space for matches as much as possible
in the definition. The existing designators
naturally fall into one of three groups: kinded, scoping, and
contextual:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 266/373
6/10/22, 3:58 PM Core Technologies
A well written pointcut should include at least the first two types (kinded and
scoping). You can include the
contextual designators to match based on
join point context or bind that context for use in the advice.
Supplying only a
kinded designator or only a contextual designator works but could affect weaving
performance (time and memory used), due to extra processing and analysis. Scoping
designators are very
fast to match, and using them means AspectJ can very quickly
dismiss groups of join points that should
not be further processed. A good
pointcut should always include one if possible.
Before Advice
You can declare before advice in an aspect by using the @Before annotation:
Java Kotlin
JAVA
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
@Before("com.xyz.myapp.CommonPointcuts.dataAccessOperation()")
// ...
}
}
If we use an in-place pointcut expression, we could rewrite the preceding example as the
following
example:
Java Kotlin
JAVA
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 267/373
6/10/22, 3:58 PM Core Technologies
@Before("execution(* com.xyz.myapp.dao.*.*(..))")
// ...
}
}
Java Kotlin
JAVA
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
@Aspect
@AfterReturning("com.xyz.myapp.CommonPointcuts.dataAccessOperation()")
// ...
}
}
You can have multiple advice declarations (and other members as well),
all inside the same aspect.
We show only a single advice declaration in these
examples to focus the effect of each one.
Sometimes, you need access in the advice body to the actual value that was returned.
You can use the
form of @AfterReturning that binds the return value to get that
access, as the following example shows:
Java Kotlin
JAVA
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
@Aspect
@AfterReturning(
pointcut="com.xyz.myapp.CommonPointcuts.dataAccessOperation()",
returning="retVal")
// ...
}
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 268/373
6/10/22, 3:58 PM Core Technologies
The name used in the returning attribute must correspond to the name of a parameter
in the advice
method. When a method execution returns, the return value is passed to
the advice method as the
corresponding argument value. A returning clause also
restricts matching to only those method
executions that return a value of the
specified type (in this case, Object , which matches any return value).
Please note that it is not possible to return a totally different reference when
using after returning advice.
Java Kotlin
JAVA
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
@Aspect
@AfterThrowing("com.xyz.myapp.CommonPointcuts.dataAccessOperation()")
// ...
}
}
Often, you want the advice to run only when exceptions of a given type are thrown,
and you also often
need access to the thrown exception in the advice body. You can
use the throwing attribute to both
restrict matching (if desired — use Throwable
as the exception type otherwise) and bind the thrown
exception to an advice parameter.
The following example shows how to do so:
Java Kotlin
JAVA
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
@Aspect
@AfterThrowing(
pointcut="com.xyz.myapp.CommonPointcuts.dataAccessOperation()",
throwing="ex")
// ...
}
}
The name used in the throwing attribute must correspond to the name of a parameter in
the advice
method. When a method execution exits by throwing an exception, the exception
is passed to the advice
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 269/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
@Aspect
@After("com.xyz.myapp.CommonPointcuts.dataAccessOperation()")
// ...
}
}
Note that @After advice in AspectJ is defined as "after finally advice", analogous
to a finally block in
a try-catch statement. It will be invoked for any outcome,
normal return or exception thrown from
the join point (user-declared target method),
in contrast to @AfterReturning which only applies to
successful normal returns.
Around Advice
The last kind of advice is around advice. Around advice runs "around" a matched
method’s execution. It
has the opportunity to do work both before and after the method
runs and to determine when, how, and
even if the method actually gets to run at all.
Around advice is often used if you need to share state before
and after a method
execution in a thread-safe manner – for example, starting and stopping a timer.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 270/373
6/10/22, 3:58 PM Core Technologies
Always use the least powerful form of advice that meets your requirements.
For example, do not use around advice if before advice is sufficient for your needs.
Around advice is declared by annotating a method with the @Around annotation. The
method should
declare Object as its return type, and the first parameter of the method
must be of type
ProceedingJoinPoint . Within the body of the advice method, you must
invoke proceed() on the
ProceedingJoinPoint in order for the underlying method to
run. Invoking proceed() without arguments
will result in the caller’s original
arguments being supplied to the underlying method when it is invoked.
For advanced use
cases, there is an overloaded variant of the proceed() method which accepts an array
of
arguments ( Object[] ). The values in the array will be used as the arguments to the
underlying method
when it is invoked.
The behavior of proceed when called with an Object[] is a little different than the
behavior of
proceed for around advice compiled by the AspectJ compiler. For around
advice written using the
traditional AspectJ language, the number of arguments passed to
proceed must match the number
of arguments passed to the around advice (not the number
of arguments taken by the underlying
join point), and the value passed to proceed in a
given argument position supplants the original value
at the join point for the entity the
value was bound to (do not worry if this does not make sense right
now).
The approach taken by Spring is simpler and a better match to its proxy-based,
execution-only
semantics. You only need to be aware of this difference if you compile
@AspectJ aspects written for
Spring and use proceed with arguments with the AspectJ
compiler and weaver. There is a way to
write such aspects that is 100% compatible across
both Spring AOP and AspectJ, and this is discussed
in the
following section on advice parameters.
The value returned by the around advice is the return value seen by the caller of the
method. For example,
a simple caching aspect could return a value from a cache if it has
one or invoke proceed() (and return
that value) if it does not. Note that proceed
may be invoked once, many times, or not at all within the
body of the around advice. All
of these are legal.
If you declare the return type of your around advice method as void , null
will always be returned
to the caller, effectively ignoring the result of any invocation
of proceed() . It is therefore
recommended that an around advice method declare a return
type of Object . The advice method
should typically return the value returned from an
invocation of proceed() , even if the underlying
method has a void return type.
However, the advice may optionally return a cached value, a
wrapped value, or some other
value depending on the use case.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 271/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
@Aspect
@Around("com.xyz.myapp.CommonPointcuts.businessService()")
// start stopwatch
// stop stopwatch
return retVal;
}
}
Advice Parameters
Spring offers fully typed advice, meaning that you declare the parameters you need in the
advice signature
(as we saw earlier for the returning and throwing examples) rather than
work with Object[] arrays all the
time. We see how to make argument and other contextual
values available to the advice body later in this
section. First, we take a look at how to
write generic advice that can find out about the method the advice
is currently advising.
Any advice method may declare, as its first parameter, a parameter of type
org.aspectj.lang.JoinPoint .
Note that around advice is required to declare a first
parameter of type ProceedingJoinPoint , which is a
subclass of JoinPoint .
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 272/373
6/10/22, 3:58 PM Core Technologies
We have already seen how to bind the returned value or exception value (using after
returning and after
throwing advice). To make argument values available to the advice
body, you can use the binding form of
args . If you use a parameter name in place of a
type name in an args expression, the value of the
corresponding argument is passed as
the parameter value when the advice is invoked. An example should
make this clearer.
Suppose you want to advise the execution of DAO operations that take an Account
object as the first parameter, and you need access to the account in the advice body.
You could write the
following:
Java Kotlin
JAVA
@Before("com.xyz.myapp.CommonPointcuts.dataAccessOperation() && args(account,..)")
// ...
}
The args(account,..) part of the pointcut expression serves two purposes. First, it
restricts matching to
only those method executions where the method takes at least one
parameter, and the argument passed
to that parameter is an instance of Account .
Second, it makes the actual Account object available to the
advice through the account
parameter.
Another way of writing this is to declare a pointcut that "provides" the Account
object value when it
matches a join point, and then refer to the named pointcut
from the advice. This would look as follows:
Java Kotlin
JAVA
@Pointcut("com.xyz.myapp.CommonPointcuts.dataAccessOperation() && args(account,..)")
@Before("accountDataAccessOperation(account)")
// ...
}
The proxy object ( this ), target object ( target ), and annotations ( @within ,
@target , @annotation , and
@args ) can all be bound in a similar fashion. The next
two examples show how to match the execution of
methods annotated with an @Auditable
annotation and extract the audit code:
The first of the two examples shows the definition of the @Auditable annotation:
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 273/373
6/10/22, 3:58 PM Core Technologies
JAVA
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
AuditCode value();
The second of the two examples shows the advice that matches the execution of @Auditable methods:
Java Kotlin
JAVA
@Before("com.xyz.lib.Pointcuts.anyPublicMethod() && @annotation(auditable)")
// ...
}
Spring AOP can handle generics used in class declarations and method parameters. Suppose
you have a
generic type like the following:
Java Kotlin
JAVA
public interface Sample<T> {
Java Kotlin
JAVA
@Before("execution(* ..Sample+.sampleGenericMethod(*)) && args(param)")
// Advice implementation
This approach does not work for generic collections. So you cannot define a
pointcut as follows:
Java Kotlin
JAVA
@Before("execution(* ..Sample+.sampleGenericCollectionMethod(*)) && args(param)")
// Advice implementation
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 274/373
6/10/22, 3:58 PM Core Technologies
To make this work, we would have to inspect every element of the collection, which is not
reasonable, as
we also cannot decide how to treat null values in general. To achieve
something similar to this, you have
to type the parameter to Collection<?> and manually
check the type of the elements.
The parameter binding in advice invocations relies on matching names used in pointcut
expressions to
declared parameter names in advice and pointcut method signatures.
Parameter names are not available
through Java reflection, so Spring AOP uses the
following strategy to determine parameter names:
If the parameter names have been explicitly specified by the user, the specified
parameter names are
used. Both the advice and the pointcut annotations have
an optional argNames attribute that you can
use to specify the argument names of
the annotated method. These argument names are available at
runtime. The following example
shows how to use the argNames attribute:
Java Kotlin
JAVA
@Before(value="com.xyz.lib.Pointcuts.anyPublicMethod() && target(bean) && @annotation(auditable)",
argNames="bean,auditable")
Java Kotlin
JAVA
@Before(value="com.xyz.lib.Pointcuts.anyPublicMethod() && target(bean) && @annotation(auditable)",
argNames="bean,auditable")
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 275/373
6/10/22, 3:58 PM Core Technologies
JAVA
@Before("com.xyz.lib.Pointcuts.anyPublicMethod()")
// ... use jp
If an @AspectJ aspect has been compiled by the AspectJ compiler ( ajc ) even
without the debug
information, you need not add the argNames attribute, as the compiler
retain the needed
information.
If the code has been compiled without the necessary debug information, Spring AOP
tries to deduce
the pairing of binding variables to parameters (for example, if
only one variable is bound in the
pointcut expression, and the advice method
takes only one parameter, the pairing is obvious). If the
binding of variables is
ambiguous given the available information, an AmbiguousBindingException is
thrown.
If all of the above strategies fail, an IllegalArgumentException is thrown.
We remarked earlier that we would describe how to write a proceed call with
arguments that works
consistently across Spring AOP and AspectJ. The solution is
to ensure that the advice signature binds each
of the method parameters in order.
The following example shows how to do so:
Java Kotlin
JAVA
@Around("execution(List<Account> find*(..)) && " +
"args(accountHolderNamePattern)")
In many cases, you do this binding anyway (as in the preceding example).
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 276/373
6/10/22, 3:58 PM Core Technologies
Advice Ordering
What happens when multiple pieces of advice all want to run at the same join point?
Spring AOP follows
the same precedence rules as AspectJ to determine the order of advice
execution. The highest precedence
advice runs first "on the way in" (so, given two pieces
of before advice, the one with highest precedence
runs first). "On the way out" from a
join point, the highest precedence advice runs last (so, given two
pieces of after
advice, the one with the highest precedence will run second).
When two pieces of advice defined in different aspects both need to run at the same
join point, unless you
specify otherwise, the order of execution is undefined. You can
control the order of execution by
specifying precedence. This is done in the normal
Spring way by either implementing the
org.springframework.core.Ordered interface in
the aspect class or annotating it with the @Order
annotation. Given two aspects, the
aspect returning the lower value from Ordered.getOrder() (or the
annotation value) has
the higher precedence.
Each of the distinct advice types of a particular aspect is conceptually meant to apply
to the join point
directly. As a consequence, an @AfterThrowing advice method is not
supposed to receive an
exception from an accompanying @After / @AfterReturning method.
As of Spring Framework 5.2.7, advice methods defined in the same @Aspect class that
need to run at
the same join point are assigned precedence based on their advice type in
the following order, from
highest to lowest precedence: @Around , @Before , @After ,
@AfterReturning , @AfterThrowing .
Note, however, that an @After advice method will
effectively be invoked after any @AfterReturning
or @AfterThrowing advice methods
in the same aspect, following AspectJ’s "after finally advice"
semantics for @After .
When two pieces of the same type of advice (for example, two @After advice methods)
defined in
the same @Aspect class both need to run at the same join point, the ordering
is undefined (since
there is no way to retrieve the source code declaration order through
reflection for javac-compiled
classes). Consider collapsing such advice methods into one
advice method per join point in each
@Aspect class or refactor the pieces of advice into
separate @Aspect classes that you can order at
the aspect level via Ordered or @Order .
5.4.5. Introductions
Introductions (known as inter-type declarations in AspectJ) enable an aspect to declare
that advised
objects implement a given interface, and to provide an implementation of
that interface on behalf of those
objects.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 277/373
6/10/22, 3:58 PM Core Technologies
You can make an introduction by using the @DeclareParents annotation. This annotation
is used to
declare that matching types have a new parent (hence the name). For example,
given an interface named
UsageTracked and an implementation of that interface named
DefaultUsageTracked , the following
aspect declares that all implementors of service
interfaces also implement the UsageTracked interface
(e.g. for statistics via JMX):
Java Kotlin
JAVA
@Aspect
@DeclareParents(value="com.xzy.myapp.service.*+", defaultImpl=DefaultUsageTracked.class)
usageTracked.incrementUseCount();
The interface to be implemented is determined by the type of the annotated field. The
value attribute of
the @DeclareParents annotation is an AspectJ type pattern. Any
bean of a matching type implements the
UsageTracked interface. Note that, in the
before advice of the preceding example, service beans can be
directly used as
implementations of the UsageTracked interface. If accessing a bean programmatically,
you would write the following:
Java Kotlin
JAVA
UsageTracked usageTracked = (UsageTracked) context.getBean("myService");
This is an advanced topic. If you are just starting out with AOP, you can safely skip
it until later.
You can declare a perthis aspect by specifying a perthis clause in the @Aspect
annotation. Consider
the following example:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 278/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Aspect("perthis(com.xyz.myapp.CommonPointcuts.businessService())")
@Before("com.xyz.myapp.CommonPointcuts.businessService()")
// ...
}
}
In the preceding example, the effect of the perthis clause is that one aspect instance
is created for each
unique service object that performs a business service (each unique
object bound to this at join points
matched by the pointcut expression). The aspect
instance is created the first time that a method is
invoked on the service object. The
aspect goes out of scope when the service object goes out of scope.
Before the aspect
instance is created, none of the advice within it runs. As soon as the aspect instance
has
been created, the advice declared within it runs at matched join points, but only
when the service object is
the one with which this aspect is associated. See the AspectJ
Programming Guide for more information on
per clauses.
The pertarget instantiation model works in exactly the same way as perthis , but it
creates one aspect
instance for each unique target object at matched join points.
The execution of business services can sometimes fail due to concurrency issues (for
example, a deadlock
loser). If the operation is retried, it is likely to succeed
on the next try. For business services where it is
appropriate to retry in such
conditions (idempotent operations that do not need to go back to the user for
conflict
resolution), we want to transparently retry the operation to avoid the client seeing a
PessimisticLockingFailureException . This is a requirement that clearly cuts across
multiple services in
the service layer and, hence, is ideal for implementing through an
aspect.
Because we want to retry the operation, we need to use around advice so that we can
call proceed
multiple times. The following listing shows the basic aspect implementation:
Java Kotlin
JAVA
@Aspect
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 279/373
6/10/22, 3:58 PM Core Technologies
private int maxRetries = DEFAULT_MAX_RETRIES;
this.maxRetries = maxRetries;
return this.order;
this.order = order;
@Around("com.xyz.myapp.CommonPointcuts.businessService()")
int numAttempts = 0;
PessimisticLockingFailureException lockFailureException;
do {
numAttempts++;
try {
return pjp.proceed();
catch(PessimisticLockingFailureException ex) {
lockFailureException = ex;
throw lockFailureException;
}
}
Note that the aspect implements the Ordered interface so that we can set the precedence of
the aspect
higher than the transaction advice (we want a fresh transaction each time we
retry). The maxRetries and
order properties are both configured by Spring. The
main action happens in the doConcurrentOperation
around advice. Notice that, for the
moment, we apply the retry logic to each businessService() . We try
to proceed,
and if we fail with a PessimisticLockingFailureException , we try again, unless
we have
exhausted all of our retry attempts.
XML
<aop:aspectj-autoproxy/>
</bean>
To refine the aspect so that it retries only idempotent operations, we might define the following
Idempotent annotation:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 280/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
@Retention(RetentionPolicy.RUNTIME)
We can then use the annotation to annotate the implementation of service operations. The change
to the
aspect to retry only idempotent operations involves refining the pointcut
expression so that only
@Idempotent operations match, as follows:
Java Kotlin
JAVA
@Around("com.xyz.myapp.CommonPointcuts.businessService() && " +
"@annotation(com.xyz.myapp.service.Idempotent)")
// ...
}
To use the aop namespace tags described in this section, you need to import the
spring-aop schema, as
described in XML Schema-based configuration. See the AOP schema
for how to import the tags in the aop
namespace.
Within your Spring configurations, all aspect and advisor elements must be placed within
an
<aop:config> element (you can have more than one <aop:config> element in an
application context
configuration). An <aop:config> element can contain pointcut,
advisor, and aspect elements (note that
these must be declared in that order).
When you use the schema support, an aspect is a regular Java object defined as a bean in
your Spring
application context. The state and behavior are captured in the fields and
methods of the object, and the
pointcut and advice information are captured in the XML.
You can declare an aspect by using the <aop:aspect> element, and reference the backing bean
by using
the ref attribute, as the following example shows:
XML
<aop:config>
...
</aop:aspect>
</aop:config>
...
</bean>
The bean that backs the aspect ( aBean in this case) can of course be configured and
dependency injected
just like any other Spring bean.
A pointcut that represents the execution of any business service in the service layer can
be defined as
follows:
XML
<aop:config>
<aop:pointcut id="businessService"
expression="execution(* com.xyz.myapp.service.*.*(..))"/>
</aop:config>
Note that the pointcut expression itself is using the same AspectJ pointcut expression
language as
described in @AspectJ support. If you use the schema based declaration
style, you can refer to named
pointcuts defined in types (@Aspects) within the
pointcut expression. Another way of defining the above
pointcut would be as follows:
XML
<aop:config>
<aop:pointcut id="businessService"
expression="com.xyz.myapp.CommonPointcuts.businessService()"/>
</aop:config>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 282/373
6/10/22, 3:58 PM Core Technologies
Assume that you have a CommonPointcuts aspect as described in Sharing Common Pointcut Definitions.
Then declaring a pointcut inside an aspect is very similar to declaring a top-level pointcut,
as the following
example shows:
XML
<aop:config>
<aop:pointcut id="businessService"
expression="execution(* com.xyz.myapp.service.*.*(..))"/>
...
</aop:aspect>
</aop:config>
In much the same way as an @AspectJ aspect, pointcuts declared by using the schema based
definition
style can collect join point context. For example, the following pointcut
collects the this object as the join
point context and passes it to the advice:
XML
<aop:config>
<aop:pointcut id="businessService"
...
</aop:aspect>
</aop:config>
The advice must be declared to receive the collected join point context by including
parameters of the
matching names, as follows:
Java Kotlin
JAVA
public void monitor(Object service) {
// ...
}
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 283/373
6/10/22, 3:58 PM Core Technologies
XML
<aop:config>
<aop:pointcut id="businessService"
...
</aop:aspect>
</aop:config>
Note that pointcuts defined in this way are referred to by their XML id and cannot be
used as named
pointcuts to form composite pointcuts. The named pointcut support in the
schema-based definition style
is thus more limited than that offered by the @AspectJ
style.
Before Advice
Before advice runs before a matched method execution. It is declared inside an
<aop:aspect> by using
the <aop:before> element, as the following example shows:
XML
<aop:aspect id="beforeExample" ref="aBean">
<aop:before
pointcut-ref="dataAccessOperation"
method="doAccessCheck"/>
...
</aop:aspect>
XML
<aop:aspect id="beforeExample" ref="aBean">
<aop:before
pointcut="execution(* com.xyz.myapp.dao.*.*(..))"
method="doAccessCheck"/>
...
</aop:aspect>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 284/373
6/10/22, 3:58 PM Core Technologies
As we noted in the discussion of the @AspectJ style, using named pointcuts can
significantly improve the
readability of your code.
The method attribute identifies a method ( doAccessCheck ) that provides the body of
the advice. This
method must be defined for the bean referenced by the aspect element
that contains the advice. Before a
data access operation is performed (a method execution
join point matched by the pointcut expression),
the doAccessCheck method on the aspect
bean is invoked.
XML
<aop:aspect id="afterReturningExample" ref="aBean">
<aop:after-returning
pointcut-ref="dataAccessOperation"
method="doAccessCheck"/>
...
</aop:aspect>
As in the @AspectJ style, you can get the return value within the advice body.
To do so, use the returning
attribute to specify the name of the parameter to which
the return value should be passed, as the
following example shows:
XML
<aop:aspect id="afterReturningExample" ref="aBean">
<aop:after-returning
pointcut-ref="dataAccessOperation"
returning="retVal"
method="doAccessCheck"/>
...
</aop:aspect>
The doAccessCheck method must declare a parameter named retVal . The type of this
parameter
constrains matching in the same way as described for @AfterReturning . For
example, you can declare the
method signature as follows:
Java Kotlin
JAVA
public void doAccessCheck(Object retVal) {...
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 285/373
6/10/22, 3:58 PM Core Technologies
After throwing advice runs when a matched method execution exits by throwing an
exception. It is
declared inside an <aop:aspect> by using the after-throwing element,
as the following example shows:
XML
<aop:aspect id="afterThrowingExample" ref="aBean">
<aop:after-throwing
pointcut-ref="dataAccessOperation"
method="doRecoveryActions"/>
...
</aop:aspect>
As in the @AspectJ style, you can get the thrown exception within the advice body.
To do so, use the
throwing attribute to specify the name of the parameter to
which the exception should be passed as the
following example shows:
XML
<aop:aspect id="afterThrowingExample" ref="aBean">
<aop:after-throwing
pointcut-ref="dataAccessOperation"
throwing="dataAccessEx"
method="doRecoveryActions"/>
...
</aop:aspect>
Java Kotlin
JAVA
public void doRecoveryActions(DataAccessException dataAccessEx) {...
XML
<aop:aspect id="afterFinallyExample" ref="aBean">
<aop:after
pointcut-ref="dataAccessOperation"
method="doReleaseLock"/>
...
</aop:aspect>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 286/373
6/10/22, 3:58 PM Core Technologies
Around Advice
The last kind of advice is around advice. Around advice runs "around" a matched
method’s execution. It
has the opportunity to do work both before and after the method
runs and to determine when, how, and
even if the method actually gets to run at all.
Around advice is often used if you need to share state before
and after a method
execution in a thread-safe manner – for example, starting and stopping a timer.
Always use the least powerful form of advice that meets your requirements.
For example, do not use around advice if before advice is sufficient for your needs.
You can declare around advice by using the aop:around element. The advice method should
declare
Object as its return type, and the first parameter of the method must be of
type ProceedingJoinPoint .
Within the body of the advice method, you must invoke
proceed() on the ProceedingJoinPoint in order
for the underlying method to run.
Invoking proceed() without arguments will result in the caller’s original
arguments
being supplied to the underlying method when it is invoked. For advanced use cases, there
is
an overloaded variant of the proceed() method which accepts an array of arguments
( Object[] ). The
values in the array will be used as the arguments to the underlying
method when it is invoked. See Around
Advice for notes on calling
proceed with an Object[] .
XML
<aop:aspect id="aroundExample" ref="aBean">
<aop:around
pointcut-ref="businessService"
method="doBasicProfiling"/>
...
</aop:aspect>
The implementation of the doBasicProfiling advice can be exactly the same as in the
@AspectJ example
(minus the annotation, of course), as the following example shows:
Java Kotlin
JAVA
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch
// stop stopwatch
return retVal;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 287/373
6/10/22, 3:58 PM Core Technologies
Advice Parameters
The schema-based declaration style supports fully typed advice in the same way as
described for the
@AspectJ support — by matching pointcut parameters by name against
advice method parameters. See
Advice Parameters for details. If you wish
to explicitly specify argument names for the advice methods (not
relying on the
detection strategies previously described), you can do so by using the arg-names
attribute
of the advice element, which is treated in the same manner as the argNames
attribute in an advice
annotation (as described in Determining Argument Names).
The following example shows how to specify
an argument name in XML:
XML
<aop:before
method="audit"
arg-names="auditable"/>
The following slightly more involved example of the XSD-based approach shows
some around advice used
in conjunction with a number of strongly typed parameters:
Java Kotlin
JAVA
package x.y.service;
}
}
Next up is the aspect. Notice the fact that the profile(..) method accepts a number of
strongly-typed
parameters, the first of which happens to be the join point used to
proceed with the method call. The
presence of this parameter is an indication that the
profile(..) is to be used as around advice, as the
following example shows:
Java Kotlin
JAVA
package x.y;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.StopWatch;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 288/373
6/10/22, 3:58 PM Core Technologies
public class SimpleProfiler {
public Object profile(ProceedingJoinPoint call, String name, int age) throws Throwable {
StopWatch clock = new StopWatch("Profiling for '" + name + "' and '" + age + "'");
try {
clock.start(call.toShortString());
return call.proceed();
} finally {
clock.stop();
System.out.println(clock.prettyPrint());
}
}
Finally, the following example XML configuration effects the execution of the
preceding advice for a
particular join point:
XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/sp
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring
<!-- this is the object that will be proxied by Spring's AOP infrastructure -->
<aop:config>
<aop:aspect ref="profiler">
<aop:pointcut id="theExecutionOfSomePersonServiceMethod"
expression="execution(* x.y.service.PersonService.getPerson(String,int))
<aop:around pointcut-ref="theExecutionOfSomePersonServiceMethod"
method="profile"/>
</aop:aspect>
</aop:config>
</beans>
Java Kotlin
JAVA
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import x.y.service.PersonService;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 289/373
6/10/22, 3:58 PM Core Technologies
public final class Boot {
person.getPerson("Pengo", 12);
}
}
With such a Boot class, we would get output similar to the following on standard output:
-----------------------------------------
ms % Task name
-----------------------------------------
00000 ? execution(getFoo)
Advice Ordering
When multiple pieces of advice need to run at the same join point (executing method)
the ordering rules
are as described in Advice Ordering. The precedence
between aspects is determined via the order
attribute in the <aop:aspect> element or
by either adding the @Order annotation to the bean that backs
the aspect or by having
the bean implement the Ordered interface.
In contrast to the precedence rules for advice methods defined in the same @Aspect
class, when
two pieces of advice defined in the same <aop:aspect> element both need to
run at the same join
point, the precedence is determined by the order in which the advice
elements are declared within
the enclosing <aop:aspect> element, from highest to lowest
precedence.
For example, given an around advice and a before advice defined in the same
<aop:aspect>
element that apply to the same join point, to ensure that the around
advice has higher precedence
than the before advice, the <aop:around> element must be
declared before the <aop:before>
element.
As a general rule of thumb, if you find that you have multiple pieces of advice defined
in the same
<aop:aspect> element that apply to the same join point, consider collapsing
such advice methods
into one advice method per join point in each <aop:aspect> element
or refactor the pieces of advice
into separate <aop:aspect> elements that you can order
at the aspect level.
5.5.4. Introductions
Introductions (known as inter-type declarations in AspectJ) let an aspect declare
that advised objects
implement a given interface and provide an implementation of
that interface on behalf of those objects.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 290/373
6/10/22, 3:58 PM Core Technologies
You can make an introduction by using the aop:declare-parents element inside an aop:aspect .
You can
use the aop:declare-parents element to declare that matching types have a new parent (hence the
name).
For example, given an interface named UsageTracked and an implementation of that interface
named
DefaultUsageTracked , the following aspect declares that all implementors of service
interfaces
also implement the UsageTracked interface. (In order to expose statistics
through JMX for example.)
XML
<aop:aspect id="usageTrackerAspect" ref="usageTracking">
<aop:declare-parents
types-matching="com.xzy.myapp.service.*+"
implement-interface="com.xyz.myapp.service.tracking.UsageTracked"
default-impl="com.xyz.myapp.service.tracking.DefaultUsageTracked"/>
<aop:before
pointcut="com.xyz.myapp.CommonPointcuts.businessService()
and this(usageTracked)"
method="recordUsage"/>
</aop:aspect>
The class that backs the usageTracking bean would then contain the following method:
Java Kotlin
JAVA
public void recordUsage(UsageTracked usageTracked) {
usageTracked.incrementUseCount();
Java Kotlin
JAVA
UsageTracked usageTracked = (UsageTracked) context.getBean("myService");
5.5.6. Advisors
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 291/373
6/10/22, 3:58 PM Core Technologies
The concept of “advisors” comes from the AOP support defined in Spring
and does not have a direct
equivalent in AspectJ. An advisor is like a small
self-contained aspect that has a single piece of advice. The
advice itself is
represented by a bean and must implement one of the advice interfaces described in
Advice Types in Spring. Advisors can take advantage of AspectJ pointcut expressions.
Spring supports the advisor concept with the <aop:advisor> element. You most
commonly see it used in
conjunction with transactional advice, which also has its own
namespace support in Spring. The following
example shows an advisor:
XML
<aop:config>
<aop:pointcut id="businessService"
expression="execution(* com.xyz.myapp.service.*.*(..))"/>
<aop:advisor
pointcut-ref="businessService"
advice-ref="tx-advice"/>
</aop:config>
<tx:advice id="tx-advice">
<tx:attributes>
</tx:attributes>
</tx:advice>
As well as the pointcut-ref attribute used in the preceding example, you can also use the
pointcut
attribute to define a pointcut expression inline.
To define the precedence of an advisor so that the advice can participate in ordering,
use the order
attribute to define the Ordered value of the advisor.
The execution of business services can sometimes fail due to concurrency issues (for
example, a deadlock
loser). If the operation is retried, it is likely to succeed
on the next try. For business services where it is
appropriate to retry in such
conditions (idempotent operations that do not need to go back to the user for
conflict
resolution), we want to transparently retry the operation to avoid the client seeing a
PessimisticLockingFailureException . This is a requirement that clearly cuts across
multiple services in
the service layer and, hence, is ideal for implementing through an
aspect.
Because we want to retry the operation, we need to use around advice so that we can
call proceed
multiple times. The following listing shows the basic aspect implementation
(which is a regular Java class
that uses the schema support):
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 292/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
public class ConcurrentOperationExecutor implements Ordered {
this.maxRetries = maxRetries;
return this.order;
this.order = order;
int numAttempts = 0;
PessimisticLockingFailureException lockFailureException;
do {
numAttempts++;
try {
return pjp.proceed();
catch(PessimisticLockingFailureException ex) {
lockFailureException = ex;
throw lockFailureException;
}
}
Note that the aspect implements the Ordered interface so that we can set the precedence of
the aspect
higher than the transaction advice (we want a fresh transaction each time we
retry). The maxRetries and
order properties are both configured by Spring. The
main action happens in the doConcurrentOperation
around advice method. We try to
proceed. If we fail with a PessimisticLockingFailureException , we try
again,
unless we have exhausted all of our retry attempts.
This class is identical to the one used in the @AspectJ example, but with the
annotations removed.
XML
<aop:config>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 293/373
6/10/22, 3:58 PM Core Technologies
<aop:pointcut id="idempotentOperation"
expression="execution(* com.xyz.myapp.service.*.*(..))"/>
<aop:around
pointcut-ref="idempotentOperation"
method="doConcurrentOperation"/>
</aop:aspect>
</aop:config>
<bean id="concurrentOperationExecutor"
class="com.xyz.myapp.service.impl.ConcurrentOperationExecutor">
</bean>
Notice that, for the time being, we assume that all business services are idempotent. If
this is not the case,
we can refine the aspect so that it retries only genuinely
idempotent operations, by introducing an
Idempotent annotation and using the annotation
to annotate the implementation of service operations,
as the following example shows:
Java Kotlin
JAVA
@Retention(RetentionPolicy.RUNTIME)
The
change to the aspect to retry only idempotent operations involves refining the
pointcut expression so
that only @Idempotent operations match, as follows:
XML
<aop:pointcut id="idempotentOperation"
@annotation(com.xyz.myapp.service.Idempotent)"/>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 294/373
6/10/22, 3:58 PM Core Technologies
Use the simplest thing that can work. Spring AOP is simpler than using full AspectJ, as
there is no
requirement to introduce the AspectJ compiler / weaver into your development
and build processes. If you
only need to advise the execution of operations on Spring
beans, Spring AOP is the right choice. If you
need to advise objects not managed by
the Spring container (such as domain objects, typically), you need
to use
AspectJ. You also need to use AspectJ if you wish to advise join points other than
simple method
executions (for example, field get or set join points and so on).
When you use AspectJ, you have the choice of the AspectJ language syntax (also known as
the “code style”)
or the @AspectJ annotation style. Clearly, if you do not use Java
5+, the choice has been made for you: Use
the code style. If aspects play a large
role in your design, and you are able to use the AspectJ
Development
Tools (AJDT) plugin for Eclipse, the AspectJ language syntax is the
preferred option. It is cleaner and
simpler because the language was purposefully
designed for writing aspects. If you do not use Eclipse or
have only a few aspects
that do not play a major role in your application, you may want to consider using
the @AspectJ style, sticking with regular Java compilation in your IDE, and adding
an aspect weaving phase
to your build script.
The XML style may be most familiar to existing Spring users, and it is backed by genuine
POJOs. When
using AOP as a tool to configure enterprise services, XML can be a good
choice (a good test is whether you
consider the pointcut expression to be a part of your
configuration that you might want to change
independently). With the XML style, it is
arguably clearer from your configuration which aspects are
present in the system.
The XML style has two disadvantages. First, it does not fully encapsulate the
implementation of the
requirement it addresses in a single place. The DRY principle says
that there should be a single,
unambiguous, authoritative representation of any piece of
knowledge within a system. When using the
XML style, the knowledge of how a requirement
is implemented is split across the declaration of the
backing bean class and the XML in
the configuration file. When you use the @AspectJ style, this
information is encapsulated
in a single module: the aspect. Secondly, the XML style is slightly more limited
in what
it can express than the @AspectJ style: Only the “singleton” aspect instantiation model
is
supported, and it is not possible to combine named pointcuts declared in XML.
For example, in the
@AspectJ style you can write something like the following:
Java Kotlin
JAVA
@Pointcut("execution(* get*())")
@Pointcut("execution(org.xyz.Account+ *(..))")
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 295/373
6/10/22, 3:58 PM Core Technologies
@Pointcut("propertyAccess() && operationReturningAnAccount()")
In the XML style you can declare the first two pointcuts:
XML
<aop:pointcut id="propertyAccess"
expression="execution(* get*())"/>
<aop:pointcut id="operationReturningAnAccount"
expression="execution(org.xyz.Account+ *(..))"/>
The downside of the XML approach is that you cannot define the
accountPropertyAccess pointcut by
combining these definitions.
The @AspectJ style supports additional instantiation models and richer pointcut
composition. It has the
advantage of keeping the aspect as a modular unit. It also has
the advantage that the @AspectJ aspects
can be understood (and thus consumed) both by
Spring AOP and by AspectJ. So, if you later decide you
need the capabilities of AspectJ
to implement additional requirements, you can easily migrate to a classic
AspectJ setup.
On balance, the Spring team prefers the @AspectJ style for custom aspects beyond simple
configuration of enterprise services.
If the target object to be proxied implements at least one interface, a JDK dynamic
proxy is used. All of the
interfaces implemented by the target type are proxied.
If the target object does not implement any
interfaces, a CGLIB proxy is created.
If you want to force the use of CGLIB proxying (for example, to proxy every method
defined for the target
object, not only those implemented by its interfaces),
you can do so. However, you should consider the
following issues:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 296/373
6/10/22, 3:58 PM Core Technologies
To force the use of CGLIB proxies, set the value of the proxy-target-class attribute
of the <aop:config>
element to true, as follows:
XML
<aop:config proxy-target-class="true">
</aop:config>
To force CGLIB proxying when you use the @AspectJ auto-proxy support, set the
proxy-target-class
attribute of the <aop:aspectj-autoproxy> element to true ,
as follows:
XML
<aop:aspectj-autoproxy proxy-target-class="true"/>
Multiple <aop:config/> sections are collapsed into a single unified auto-proxy creator
at runtime,
which applies the strongest proxy settings that any of the
<aop:config/> sections (typically from
different XML bean definition files) specified.
This also applies to the <tx:annotation-driven/> and
<aop:aspectj-autoproxy/>
elements.
Java Kotlin
JAVA
public class SimplePojo implements Pojo {
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 297/373
6/10/22, 3:58 PM Core Technologies
this.bar();
// some logic...
}
}
Java Kotlin
JAVA
public class Main {
pojo.foo();
}
}
Things change slightly when the reference that client code has is a proxy. Consider the
following diagram
and code snippet:
Java Kotlin
JAVA
public class Main {
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 298/373
6/10/22, 3:58 PM Core Technologies
factory.addInterface(Pojo.class);
factory.addAdvice(new RetryAdvice());
pojo.foo();
}
}
The key thing to understand here is that the client code inside the main(..) method
of the Main class
has a reference to the proxy. This means that method calls on that
object reference are calls on the proxy.
As a result, the proxy can delegate to all of
the interceptors (advice) that are relevant to that particular
method call. However,
once the call has finally reached the target object (the SimplePojo reference in
this
case), any method calls that it may make on itself, such as this.bar() or
this.foo() , are going to be
invoked against the this reference, and not the proxy.
This has important implications. It means that
self-invocation is not going to result
in the advice associated with a method invocation getting a chance to
run.
Okay, so what is to be done about this? The best approach (the term "best" is used
loosely here) is to
refactor your code such that the self-invocation does not happen.
This does entail some work on your
part, but it is the best, least-invasive approach.
The next approach is absolutely horrendous, and we
hesitate to point it out, precisely
because it is so horrendous. You can (painful as it is to us) totally tie the
logic
within your class to Spring AOP, as the following example shows:
Java Kotlin
JAVA
public class SimplePojo implements Pojo {
((Pojo) AopContext.currentProxy()).bar();
// some logic...
}
}
This totally couples your code to Spring AOP, and it makes the class itself aware of
the fact that it is being
used in an AOP context, which flies in the face of AOP. It
also requires some additional configuration when
the proxy is being created, as the
following example shows:
Java Kotlin
JAVA
public class Main {
factory.addInterface(Pojo.class);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 299/373
6/10/22, 3:58 PM Core Technologies
factory.addAdvice(new RetryAdvice());
factory.setExposeProxy(true);
pojo.foo();
}
}
Finally, it must be noted that AspectJ does not have this self-invocation issue because
it is not a proxy-
based AOP framework.
Java Kotlin
JAVA
// create a factory that can generate a proxy for the given target object
// you can call this as many times as you need with different aspects
factory.addAspect(SecurityManager.class);
// you can also add existing aspect instances, the type of the object supplied must be an @AspectJ
factory.addAspect(usageTracker);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 300/373
6/10/22, 3:58 PM Core Technologies
Spring ships with a small AspectJ aspect library, which is available stand-alone in your
distribution as
spring-aspects.jar . You need to add this to your classpath in order
to use the aspects in it. Using
AspectJ to Dependency Inject Domain Objects with Spring and Other Spring aspects for AspectJ discuss the
content of this library and how you can use it. Configuring AspectJ Aspects by Using Spring IoC discusses
how to
dependency inject AspectJ aspects that are woven using the AspectJ compiler. Finally,
Load-time
Weaving with AspectJ in the Spring Framework provides an introduction to load-time weaving for Spring
applications
that use AspectJ.
Java Kotlin
JAVA
package com.xyz.myapp.domain;
import org.springframework.beans.factory.annotation.Configurable;
@Configurable
// ...
}
When used as a marker interface in this way, Spring configures new instances of the
annotated type
( Account , in this case) by using a bean definition (typically
prototype-scoped) with the same name as the
fully-qualified type name
( com.xyz.myapp.domain.Account ). Since the default name for a bean is the
fully-
qualified name of its type, a convenient way to declare the prototype definition
is to omit the id
attribute, as the following example shows:
XML
<bean class="com.xyz.myapp.domain.Account" scope="prototype">
</bean>
If you want to explicitly specify the name of the prototype bean definition to use, you
can do so directly in
the annotation, as the following example shows:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 301/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
package com.xyz.myapp.domain;
import org.springframework.beans.factory.annotation.Configurable;
@Configurable("account")
// ...
}
Spring now looks for a bean definition named account and uses that as the
definition to configure new
Account instances.
You can also use autowiring to avoid having to specify a dedicated bean definition at
all. To have Spring
apply autowiring, use the autowire property of the @Configurable
annotation. You can specify either
@Configurable(autowire=Autowire.BY_TYPE) or
@Configurable(autowire=Autowire.BY_NAME) for
autowiring by type or by name,
respectively. As an alternative, it is preferable to specify explicit,
annotation-driven
dependency injection for your @Configurable beans through @Autowired or @Inject
at the field or method level (see Annotation-based Container Configuration for further details).
Finally, you can enable Spring dependency checking for the object references in the newly
created and
configured object by using the dependencyCheck attribute (for example,
@Configurable(autowire=Autowire.BY_NAME,dependencyCheck=true) ). If this attribute is
set to true ,
Spring validates after configuration that all properties (which
are not primitives or collections) have been
set.
Note that using the annotation on its own does nothing. It is the
AnnotationBeanConfigurerAspect in
spring-aspects.jar that acts on the presence of
the annotation. In essence, the aspect says, “after
returning from the initialization of
a new object of a type annotated with @Configurable , configure the
newly created object
using Spring in accordance with the properties of the annotation”. In this context,
“initialization” refers to newly instantiated objects (for example, objects instantiated
with the new
operator) as well as to Serializable objects that are undergoing
deserialization (for example, through
readResolve()).
One of the key phrases in the above paragraph is “in essence”. For most cases, the
exact semantics
of “after returning from the initialization of a new object” are
fine. In this context, “after initialization”
means that the dependencies are
injected after the object has been constructed. This means that the
dependencies
are not available for use in the constructor bodies of the class. If you want the
dependencies to be injected before the constructor bodies run and thus be
available for use in the
body of the constructors, you need to define this on the
@Configurable declaration, as follows:
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 302/373
6/10/22, 3:58 PM Core Technologies
JAVA
@Configurable(preConstruction = true)
You can find more information about the language semantics of the various pointcut
types in AspectJ
in this
appendix of the AspectJ
Programming Guide.
For this to work, the annotated types must be woven with the AspectJ weaver. You can
either use a build-
time Ant or Maven task to do this (see, for example, the
AspectJ Development
Environment Guide) or load-
time weaving (see Load-time Weaving with AspectJ in the Spring Framework). The
AnnotationBeanConfigurerAspect itself needs to be configured by Spring (in order to obtain
a reference
to the bean factory that is to be used to configure new objects). If you
use Java-based configuration, you
can add @EnableSpringConfigured to any
@Configuration class, as follows:
Java Kotlin
JAVA
@Configuration
@EnableSpringConfigured
XML
<context:spring-configured/>
Instances of @Configurable objects created before the aspect has been configured
result in a message
being issued to the debug log and no configuration of the
object taking place. An example might be a bean
in the Spring configuration that creates
domain objects when it is initialized by Spring. In this case, you can
use the
depends-on bean attribute to manually specify that the bean depends on the
configuration
aspect. The following example shows how to use the depends-on attribute:
XML
<bean id="myService"
class="com.xzy.myapp.service.MyService"
depends-on="org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect">
</bean>
Do not activate @Configurable processing through the bean configurer aspect unless you
really
mean to rely on its semantics at runtime. In particular, make sure that you do
not use
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 303/373
6/10/22, 3:58 PM Core Technologies
Consider a typical Spring web application configuration that has a shared parent application
context that
defines common business services, everything needed to support those services,
and one child application
context for each servlet (which contains definitions particular
to that servlet). All of these contexts co-exist
within the same classloader hierarchy,
and so the AnnotationBeanConfigurerAspect can hold a reference
to only one of them.
In this case, we recommend defining the @EnableSpringConfigured bean in the
shared
(parent) application context. This defines the services that you are likely to want to
inject into
domain objects. A consequence is that you cannot configure domain objects
with references to beans
defined in the child (servlet-specific) contexts by using the
@Configurable mechanism (which is probably
not something you want to do anyway).
When deploying multiple web applications within the same container, ensure that each
web application
loads the types in spring-aspects.jar by using its own classloader
(for example, by placing spring-
aspects.jar in WEB-INF/lib ). If spring-aspects.jar
is added only to the container-wide classpath (and
hence loaded by the shared parent
classloader), all web applications share the same aspect instance
(which is probably
not what you want).
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 304/373
6/10/22, 3:58 PM Core Technologies
Since Spring Framework 4.2, spring-aspects provides a similar aspect that offers the
exact same
features for the standard javax.transaction.Transactional annotation. Check
JtaAnnotationTransactionAspect for more details.
For AspectJ programmers who want to use the Spring configuration and transaction
management support
but do not want to (or cannot) use annotations, spring-aspects.jar
also contains abstract aspects you
can extend to provide your own pointcut
definitions. See the sources for the
AbstractBeanConfigurerAspect and
AbstractTransactionAspect aspects for more information. As an
example, the following
excerpt shows how you could write an aspect to configure all instances of objects
defined in the domain model by using prototype bean definitions that match the
fully qualified class
names:
JAVA
public aspect DomainObjectConfiguration extends AbstractBeanConfigurerAspect {
public DomainObjectConfiguration() {
setBeanWiringInfoResolver(new ClassNameBeanWiringInfoResolver());
initialization(new(..)) &&
CommonPointcuts.inDomainModel() &&
this(beanInstance);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 305/373
6/10/22, 3:58 PM Core Technologies
When you use AspectJ aspects with Spring applications, it is natural to both want and
expect to be able to
configure such aspects with Spring. The AspectJ runtime itself is
responsible for aspect creation, and the
means of configuring the AspectJ-created
aspects through Spring depends on the AspectJ instantiation
model (the per-xxx clause)
used by the aspect.
XML
<bean id="profiler" class="com.xyz.profiler.Profiler"
factory-method="aspectOf"> 1
</bean>
If you have some @AspectJ aspects that you want to weave with AspectJ (for example,
using load-time
weaving for domain model types) and other @AspectJ aspects that you want
to use with Spring AOP, and
these aspects are all configured in Spring, you
need to tell the Spring AOP @AspectJ auto-proxying support
which exact subset of the
@AspectJ aspects defined in the configuration should be used for auto-proxying.
You can
do this by using one or more <include/> elements inside the <aop:aspectj-autoproxy/>
declaration. Each <include/> element specifies a name pattern, and only beans with
names matched by
at least one of the patterns are used for Spring AOP auto-proxy
configuration. The following example
shows how to use <include/> elements:
XML
<aop:aspectj-autoproxy>
<aop:include name="thisBean"/>
<aop:include name="thatBean"/>
</aop:aspectj-autoproxy>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 306/373
6/10/22, 3:58 PM Core Technologies
The value that the Spring Framework brings to AspectJ LTW is in enabling much
finer-grained control over
the weaving process. 'Vanilla' AspectJ LTW is effected by using
a Java (5+) agent, which is switched on by
specifying a VM argument when starting up a
JVM. It is, thus, a JVM-wide setting, which may be fine in
some situations but is often a
little too coarse. Spring-enabled LTW lets you switch on LTW on a
per-
ClassLoader basis, which is more fine-grained and which can make more
sense in a 'single-JVM-multiple-
application' environment (such as is found in a typical
application server environment).
Now that the sales pitch is over, let us first walk through a quick example of AspectJ
LTW that uses Spring,
followed by detailed specifics about elements introduced in the
example. For a complete example, see the
Petclinic sample application.
A First Example
Assume that you are an application developer who has been tasked with diagnosing
the cause of some
performance problems in a system. Rather than break out a
profiling tool, we are going to switch on a
simple profiling aspect that lets us
quickly get some performance metrics. We can then apply a finer-
grained profiling
tool to that specific area immediately afterwards.
The example presented here uses XML configuration. You can also configure and
use @AspectJ with
Java configuration. Specifically, you can use the
@EnableLoadTimeWeaving annotation as an
alternative to <context:load-time-weaver/>
(see below for details).
The following example shows the profiling aspect, which is not fancy.
It is a time-based profiler that uses
the @AspectJ-style of aspect declaration:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 307/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
package foo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.util.StopWatch;
import org.springframework.core.annotation.Order;
@Aspect
@Around("methodsToBeProfiled()")
try {
sw.start(pjp.getSignature().getName());
return pjp.proceed();
} finally {
sw.stop();
System.out.println(sw.prettyPrint());
@Pointcut("execution(public * foo..*.*(..))")
We also need to create an META-INF/aop.xml file, to inform the AspectJ weaver that
we want to weave our
ProfilingAspect into our classes. This file convention, namely
the presence of a file (or files) on the Java
classpath called META-INF/aop.xml is
standard AspectJ. The following example shows the aop.xml file:
XML
<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "https://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
<weaver>
<include within="foo.*"/>
</weaver>
<aspects>
<aspect name="foo.ProfilingAspect"/>
</aspects>
</aspectj>
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="entitlementCalculationService"
class="foo.StubEntitlementCalculationService"/>
<context:load-time-weaver/>
</beans>
Now that all the required artifacts (the aspect, the META-INF/aop.xml
file, and the Spring configuration)
are in place, we can create the following
driver class with a main(..) method to demonstrate the LTW in
action:
Java Kotlin
JAVA
package foo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
EntitlementCalculationService entitlementCalculationService =
(EntitlementCalculationService) ctx.getBean("entitlementCalculationService");
entitlementCalculationService.calculateEntitlement();
}
}
We have one last thing to do. The introduction to this section did say that one could
switch on LTW
selectively on a per- ClassLoader basis with Spring, and this is true.
However, for this example, we use a
Java agent (supplied with Spring) to switch on LTW.
We use the following command to run the Main class
shown earlier:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 309/373
6/10/22, 3:58 PM Core Technologies
The output from the execution of the Main program looks something like the next example.
(I have
introduced a Thread.sleep(..) statement into the calculateEntitlement()
implementation so that the
profiler actually captures something other than 0
milliseconds (the 01234 milliseconds is not an overhead
introduced by the AOP).
The following listing shows the output we got when we ran our profiler:
Calculating entitlement
ms % Task name
Since this LTW is effected by using full-blown AspectJ, we are not limited only to advising
Spring beans. The
following slight variation on the Main program yields the same
result:
Java Kotlin
JAVA
package foo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
EntitlementCalculationService entitlementCalculationService =
new StubEntitlementCalculationService();
entitlementCalculationService.calculateEntitlement();
}
}
Notice how, in the preceding program, we bootstrap the Spring container and
then create a new instance
of the StubEntitlementCalculationService totally outside
the context of Spring. The profiling advice still
gets woven in.
Admittedly, the example is simplistic. However, the basics of the LTW support in Spring
have all been
introduced in the earlier example, and the rest of this section explains
the “why” behind each bit of
configuration and usage in detail.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 310/373
6/10/22, 3:58 PM Core Technologies
The ProfilingAspect used in this example may be basic, but it is quite useful. It is a
nice example of
a development-time aspect that developers can use during development
and then easily exclude
from builds of the application being deployed
into UAT or production.
Aspects
The aspects that you use in LTW have to be AspectJ aspects. You can write them in
either the AspectJ
language itself, or you can write your aspects in the @AspectJ-style.
Your aspects are then both valid
AspectJ and Spring AOP aspects.
Furthermore, the compiled aspect classes need to be available on the
classpath.
'META-INF/aop.xml'
The AspectJ LTW infrastructure is configured by using one or more META-INF/aop.xml
files that are on the
Java classpath (either directly or, more typically, in jar files).
The structure and contents of this file is detailed in the LTW part of the
AspectJ reference
documentation.
Because the aop.xml file is 100% AspectJ, we do not describe it further here.
spring-aop.jar
aspectjweaver.jar
spring-instrument.jar
Spring Configuration
The key component in Spring’s LTW support is the LoadTimeWeaver interface (in the
org.springframework.instrument.classloading package), and the numerous implementations
of it that
ship with the Spring distribution. A LoadTimeWeaver is responsible for
adding one or more
java.lang.instrument.ClassFileTransformers to a ClassLoader at
runtime, which opens the door to all
manner of interesting applications, one of which
happens to be the LTW of aspects.
If you are unfamiliar with the idea of runtime class file transformation, see the
javadoc API
documentation for the java.lang.instrument package before continuing.
While that documentation
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 311/373
6/10/22, 3:58 PM Core Technologies
To enable the Spring Framework’s LTW support, you need to configure a LoadTimeWeaver ,
which typically
is done by using the @EnableLoadTimeWeaving annotation, as follows:
Java Kotlin
JAVA
@Configuration
@EnableLoadTimeWeaving
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:load-time-weaver/>
</beans>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 312/373
6/10/22, 3:58 PM Core Technologies
Running in Oracle’s
WebLogic WebLogicLoadTimeWeaver
Note that the table lists only the that are autodetected when you
use the
LoadTimeWeavers
DefaultContextLoadTimeWeaver . You can specify exactly which LoadTimeWeaver
implementation to use.
Java Kotlin
JAVA
@Configuration
@EnableLoadTimeWeaving
@Override
}
}
If you use XML-based configuration, you can specify the fully qualified classname
as the value of the
weaver-class attribute on the <context:load-time-weaver/>
element. Again, the following example
specifies a ReflectiveLoadTimeWeaver :
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 313/373
6/10/22, 3:58 PM Core Technologies
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:load-time-weaver
weaver-class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver"/>
</beans>
The LoadTimeWeaver that is defined and registered by the configuration can be later
retrieved from the
Spring container by using the well known name, loadTimeWeaver .
Remember that the LoadTimeWeaver
exists only as a mechanism for Spring’s LTW
infrastructure to add one or more ClassFileTransformers .
The actual
ClassFileTransformer that does the LTW is the ClassPreProcessorAgentAdapter (from
the
org.aspectj.weaver.loadtime package) class. See the class-level javadoc of the
ClassPreProcessorAgentAdapter class for further details, because the specifics of how
the weaving is
actually effected is beyond the scope of this document.
There is one final attribute of the configuration left to discuss: the aspectjWeaving
attribute (or aspectj-
weaving if you use XML). This attribute controls whether LTW
is enabled or not. It accepts one of three
possible values, with the default value being
autodetect if the attribute is not present. The following table
summarizes the three
possible values:
Environment-specific Configuration
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 314/373
6/10/22, 3:58 PM Core Technologies
This last section contains any additional settings and configuration that you need
when you use Spring’s
LTW support in environments such as application servers and web
containers.
Tomcat, JBoss/WildFly, IBM WebSphere Application Server and Oracle WebLogic Server all
provide a
general app ClassLoader that is capable of local instrumentation. Spring’s
native LTW may leverage those
ClassLoader implementations to provide AspectJ weaving.
You can simply enable load-time weaving, as
described earlier.
Specifically, you do not need to modify the JVM launch script to add
-
javaagent:path/to/spring-instrument.jar .
Note that on JBoss, you may need to disable the app server scanning to prevent it from
loading the classes
before the application actually starts. A quick workaround is to add
to your artifact a file named WEB-
INF/jboss-scanning.xml with the following content:
XML
<scanning xmlns="urn:jboss:scanning:1.0"/>
To use it, you must start the virtual machine with the Spring agent by supplying
the following JVM options:
-javaagent:/path/to/spring-instrument.jar
Note that this requires modification of the JVM launch script, which may prevent you
from using this in
application server environments (depending on your server and your
operation policies). That said, for
one-app-per-JVM deployments such as standalone
Spring Boot applications, you typically control the
entire JVM setup in any case.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 315/373
6/10/22, 3:58 PM Core Technologies
AspectJ in Action, Second Edition by Ramnivas Laddad (Manning, 2009) comes highly
recommended. The
focus of the book is on AspectJ, but a lot of general AOP themes are
explored (in some depth).
6.1.1. Concepts
Spring’s pointcut model enables pointcut reuse independent of advice types. You can
target different
advice with the same pointcut.
JAVA
public interface Pointcut {
ClassFilter getClassFilter();
MethodMatcher getMethodMatcher();
Splitting the Pointcut interface into two parts allows reuse of class and method
matching parts and fine-
grained composition operations (such as performing a “union”
with another method matcher).
The ClassFilter interface is used to restrict the pointcut to a given set of target
classes. If the matches()
method always returns true, all target classes are
matched. The following listing shows the ClassFilter
interface definition:
JAVA
public interface ClassFilter {
The MethodMatcher interface is normally more important. The complete interface follows:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 316/373
6/10/22, 3:58 PM Core Technologies
JAVA
public interface MethodMatcher {
boolean isRuntime();
The matches(Method, Class) method is used to test whether this pointcut ever
matches a given method
on a target class. This evaluation can be performed when an AOP
proxy is created to avoid the need for a
test on every method invocation. If the
two-argument matches method returns true for a given method,
and the isRuntime()
method for the MethodMatcher returns true , the three-argument matches
method is
invoked on every method invocation. This lets a pointcut look at the arguments passed
to the
method invocation immediately before the target advice starts.
Most MethodMatcher implementations are static, meaning that their isRuntime() method
returns
false . In this case, the three-argument matches method is never invoked.
If possible, try to make pointcuts static, allowing the AOP framework to cache the
results of pointcut
evaluation when an AOP proxy is created.
See the previous chapter for a discussion of supported AspectJ pointcut primitives.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 317/373
6/10/22, 3:58 PM Core Technologies
Spring provides several convenient pointcut implementations. You can use some of them
directly; others
are intended to be subclassed in application-specific pointcuts.
Static Pointcuts
Static pointcuts are based on the method and the target class and cannot take into account
the method’s
arguments. Static pointcuts suffice — and are best — for most usages.
Spring can evaluate a static pointcut
only once, when a method is first invoked.
After that, there is no need to evaluate the pointcut again with
each method invocation.
The rest of this section describes some of the static pointcut implementations that are
included with
Spring.
One obvious way to specify static pointcuts is regular expressions. Several AOP
frameworks besides Spring
make this possible.
org.springframework.aop.support.JdkRegexpMethodPointcut is a generic regular
expression pointcut that uses the regular expression support in the JDK.
With the JdkRegexpMethodPointcut class, you can provide a list of pattern strings.
If any of these is a
match, the pointcut evaluates to true . (As a consequence,
the resulting pointcut is effectively the union
of the specified patterns.)
XML
<bean id="settersAndAbsquatulatePointcut"
class="org.springframework.aop.support.JdkRegexpMethodPointcut">
<property name="patterns">
<list>
<value>.*set.*</value>
<value>.*absquatulate</value>
</list>
</property>
</bean>
XML
<bean id="settersAndAbsquatulateAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref bean="beanNameOfAopAllianceInterceptor"/>
</property>
<property name="patterns">
<list>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 318/373
6/10/22, 3:58 PM Core Technologies
<value>.*set.*</value>
<value>.*absquatulate</value>
</list>
</property>
</bean>
Attribute-driven Pointcuts
Dynamic pointcuts
Dynamic pointcuts are costlier to evaluate than static pointcuts. They take into account
method
arguments as well as static information. This means that they must be
evaluated with every method
invocation and that the result cannot be cached, as arguments will
vary.
Spring control flow pointcuts are conceptually similar to AspectJ cflow pointcuts,
although less powerful.
(There is currently no way to specify that a pointcut runs
below a join point matched by another pointcut.)
A control flow pointcut matches the
current call stack. For example, it might fire if the join point was
invoked by a method
in the com.mycompany.web package or by the SomeCaller class. Control flow
pointcuts
are specified by using the org.springframework.aop.support.ControlFlowPointcut class.
Control flow pointcuts are significantly more expensive to evaluate at runtime than even
other
dynamic pointcuts. In Java 1.4, the cost is about five times that of other dynamic
pointcuts.
Because static pointcuts are most useful, you should probably subclass
StaticMethodMatcherPointcut .
This requires implementing only one
abstract method (although you can override other methods to
customize behavior). The
following example shows how to subclass StaticMethodMatcherPointcut :
Java Kotlin
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 319/373
6/10/22, 3:58 PM Core Technologies
JAVA
class TestStaticPointcut extends StaticMethodMatcherPointcut {
}
}
Later versions of Spring may offer support for “semantic pointcuts” as offered by JAC — for example,
“all methods that change instance variables in the target object.”
Per-class advice is used most often. It is appropriate for generic advice, such as
transaction advisors.
These do not depend on the state of the proxied object or add new
state. They merely act on the method
and arguments.
You can use a mix of shared and per-instance advice in the same AOP proxy.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 320/373
6/10/22, 3:58 PM Core Technologies
Spring is compliant with the AOP Alliance interface for around advice that uses method
interception.
Classes that implement MethodInterceptor and that implement around advice should also implement
the
following interface:
JAVA
public interface MethodInterceptor extends Interceptor {
The MethodInvocation argument to the invoke() method exposes the method being
invoked, the target
join point, the AOP proxy, and the arguments to the method. The
invoke() method should return the
invocation’s result: the return value of the join
point.
Java Kotlin
JAVA
public class DebugInterceptor implements MethodInterceptor {
System.out.println("Invocation returned");
return rval;
}
}
Note the call to the proceed() method of MethodInvocation . This proceeds down the
interceptor chain
towards the join point. Most interceptors invoke this method and
return its return value. However, a
MethodInterceptor , like any around advice, can
return a different value or throw an exception rather
than invoke the proceed method.
However, you do not want to do this without good reason.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 321/373
6/10/22, 3:58 PM Core Technologies
Before Advice
A simpler advice type is a before advice. This does not need a MethodInvocation
object, since it is called
only before entering the method.
The main advantage of a before advice is that there is no need to invoke the proceed()
method and,
therefore, no possibility of inadvertently failing to proceed down the
interceptor chain.
JAVA
public interface MethodBeforeAdvice extends BeforeAdvice {
Note that the return type is void . Before advice can insert custom behavior before the join
point runs but
cannot change the return value. If a before advice throws an
exception, it stops further execution of the
interceptor chain. The exception
propagates back up the interceptor chain. If it is unchecked or on the
signature of
the invoked method, it is passed directly to the client. Otherwise, it is
wrapped in an
unchecked exception by the AOP proxy.
The following example shows a before advice in Spring, which counts all method invocations:
Java Kotlin
JAVA
public class CountingBeforeAdvice implements MethodBeforeAdvice {
++count;
return count;
}
}
Throws Advice
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 322/373
6/10/22, 3:58 PM Core Technologies
Throws advice is invoked after the return of the join point if the join point threw
an exception. Spring
offers typed throws advice. Note that this means that the
org.springframework.aop.ThrowsAdvice
interface does not contain any methods. It is a
tag interface identifying that the given object implements
one or more typed throws
advice methods. These should be in the following form:
JAVA
afterThrowing([Method, args, target], subclassOfThrowable)
Only the last argument is required. The method signatures may have either one or four
arguments,
depending on whether the advice method is interested in the method and
arguments. The next two listing
show classes that are examples of throws advice.
Java Kotlin
JAVA
public class RemoteThrowsAdvice implements ThrowsAdvice {
}
}
Java Kotlin
JAVA
public class ServletThrowsAdviceWithArguments implements ThrowsAdvice {
}
}
The final example illustrates how these two methods could be used in a single class
that handles both
RemoteException and ServletException . Any number of throws advice
methods can be combined in a
single class. The following listing shows the final example:
Java Kotlin
JAVA
public static class CombinedThrowsAdvice implements ThrowsAdvice {
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 323/373
6/10/22, 3:58 PM Core Technologies
public void afterThrowing(Method m, Object[] args, Object target, ServletException ex) {
}
}
JAVA
public interface AfterReturningAdvice extends Advice {
throws Throwable;
An after returning advice has access to the return value (which it cannot modify),
the invoked method, the
method’s arguments, and the target.
The following after returning advice counts all successful method invocations that have
not thrown
exceptions:
Java Kotlin
JAVA
public class CountingAfterReturningAdvice implements AfterReturningAdvice {
throws Throwable {
++count;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 324/373
6/10/22, 3:58 PM Core Technologies
return count;
}
}
This advice does not change the execution path. If it throws an exception, it is
thrown up the interceptor
chain instead of the return value.
Introduction Advice
Spring treats introduction advice as a special kind of interception advice.
JAVA
public interface IntroductionInterceptor extends MethodInterceptor {
The invoke() method inherited from the AOP Alliance MethodInterceptor interface must
implement the
introduction. That is, if the invoked method is on an introduced
interface, the introduction interceptor is
responsible for handling the method call — it
cannot invoke proceed() .
Introduction advice cannot be used with any pointcut, as it applies only at the class,
rather than the
method, level. You can only use introduction advice with the
IntroductionAdvisor , which has the
following methods:
JAVA
public interface IntroductionAdvisor extends Advisor, IntroductionInfo {
ClassFilter getClassFilter();
Class<?>[] getInterfaces();
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 325/373
6/10/22, 3:58 PM Core Technologies
Consider an example from the Spring test suite and suppose we want to
introduce the following interface
to one or more objects:
Java Kotlin
JAVA
public interface Lockable {
void lock();
void unlock();
boolean locked();
Note the use of the locked instance variable. This effectively adds additional state
to that held in the
target object.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 326/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
public class LockMixin extends DelegatingIntroductionInterceptor implements Lockable {
this.locked = true;
this.locked = false;
return this.locked;
return super.invoke(invocation);
Java Kotlin
JAVA
public class LockMixinAdvisor extends DefaultIntroductionAdvisor {
public LockMixinAdvisor() {
}
}
We can apply this advisor very simply, because it requires no configuration. (However, it
is impossible to
use an IntroductionInterceptor without an
IntroductionAdvisor .) As usual with introductions, the
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 327/373
6/10/22, 3:58 PM Core Technologies
Apart from the special case of introductions, any advisor can be used with any advice.
org.springframework.aop.support.DefaultPointcutAdvisor is the most commonly used
advisor class. It
can be used with a MethodInterceptor , BeforeAdvice , or
ThrowsAdvice .
It is possible to mix advisor and advice types in Spring in the same AOP proxy. For
example, you could use
an interception around advice, throws advice, and before advice in
one proxy configuration. Spring
automatically creates the necessary interceptor
chain.
The Spring AOP support also uses factory beans under the covers.
6.4.1. Basics
The ProxyFactoryBean , like other Spring FactoryBean implementations, introduces a
level of indirection.
If you define a ProxyFactoryBean named foo , objects that
reference foo do not see the
ProxyFactoryBean instance itself but an object
created by the implementation of the getObject()
method in the ProxyFactoryBean . This
method creates an AOP proxy that wraps a target object.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 328/373
6/10/22, 3:58 PM Core Technologies
If the target class implements one (or more) interfaces, the type of proxy that is
created depends on the
configuration of the ProxyFactoryBean .
If the proxyInterfaces property of the ProxyFactoryBean has been set to one or more
fully qualified
interface names, a JDK-based proxy is created. The created
proxy implements all of the interfaces that
were specified in the proxyInterfaces
property. If the target class happens to implement a whole lot
more interfaces than
those specified in the proxyInterfaces property, that is all well and good, but those
additional interfaces are not implemented by the returned proxy.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 330/373
6/10/22, 3:58 PM Core Technologies
If the proxyInterfaces property of the ProxyFactoryBean has not been set, but
the target class does
implement one (or more) interfaces, the
ProxyFactoryBean auto-detects the fact that the target class
does actually
implement at least one interface, and a JDK-based proxy is created. The interfaces
that are
actually proxied are all of the interfaces that the target class
implements. In effect, this is the same as
supplying a list of each and every
interface that the target class implements to the proxyInterfaces
property. However,
it is significantly less work and less prone to typographical errors.
XML
<bean id="personTarget" class="com.mycompany.PersonImpl">
</bean>
</bean>
</bean>
<bean id="person"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>myAdvisor</value>
<value>debugInterceptor</value>
</list>
</property>
</bean>
Note that the interceptorNames property takes a list of String , which holds the bean names of the
interceptors or advisors in the current factory. You can use advisors, interceptors, before, after
returning,
and throws advice objects. The ordering of advisors is significant.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 331/373
6/10/22, 3:58 PM Core Technologies
You might be wondering why the list does not hold bean references. The reason for this is
that, if the
singleton property of the ProxyFactoryBean is set to false , it must be able to
return independent
proxy instances. If any of the advisors is itself a prototype, an
independent instance would need to
be returned, so it is necessary to be able to obtain
an instance of the prototype from the factory.
Holding a reference is not sufficient.
The person bean definition shown earlier can be used in place of a Person implementation, as
follows:
Java Kotlin
JAVA
Person person = (Person) factory.getBean("person");
Other beans in the same IoC context can express a strongly typed dependency on it, as
with an ordinary
Java object. The following example shows how to do so:
XML
<bean id="personUser" class="com.mycompany.PersonUser">
</bean>
The PersonUser class in this example exposes a property of type Person . As far as
it is concerned, the
AOP proxy can be used transparently in place of a “real” person
implementation. However, its class would
be a dynamic proxy class. It would be possible
to cast it to the Advised interface (discussed later).
You can conceal the distinction between target and proxy by using an anonymous
inner bean. Only the
ProxyFactoryBean definition is different. The
advice is included only for completeness. The following
example shows how to use an
anonymous inner bean:
XML
<bean id="myAdvisor" class="com.mycompany.MyAdvisor">
</bean>
<property name="target">
<bean class="com.mycompany.PersonImpl">
<list>
<value>myAdvisor</value>
<value>debugInterceptor</value>
</list>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 332/373
6/10/22, 3:58 PM Core Technologies
</property>
</bean>
Using an anonymous inner bean has the advantage that there is only one object of type Person . This is
useful if we want
to prevent users of the application context from obtaining a reference to the un-advised
object or need to avoid any ambiguity with Spring IoC autowiring. There is also,
arguably, an advantage in
that the ProxyFactoryBean definition is self-contained.
However, there are times when being able to
obtain the un-advised target from the
factory might actually be an advantage (for example, in certain test
scenarios).
Imagine that in our earlier example, there was no Person interface. We needed to advise
a class called
Person that did not implement any business interface. In this case, you
can configure Spring to use CGLIB
proxying rather than dynamic proxies. To do so, set the
proxyTargetClass property on the
ProxyFactoryBean shown earlier to true . While it is best to
program to interfaces rather than classes,
the ability to advise classes that do not
implement interfaces can be useful when working with legacy
code. (In general, Spring
is not prescriptive. While it makes it easy to apply good practices, it avoids forcing
a
particular approach.)
If you want to, you can force the use of CGLIB in any case, even if you do have
interfaces.
CGLIB proxying works by generating a subclass of the target class at runtime. Spring
configures this
generated subclass to delegate method calls to the original target. The
subclass is used to implement the
Decorator pattern, weaving in the advice.
CGLIB proxying should generally be transparent to users. However, there are some issues
to consider:
There is little performance difference between CGLIB proxying and dynamic proxies.
Performance should
not be a decisive consideration in this case.
XML
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>global*</value>
</list>
</property>
</bean>
First, we create a parent, template, bean definition for the proxy, as follows:
XML
<bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
This is never instantiated itself, so it can actually be incomplete. Then, each proxy
that needs to be created
is a child bean definition, which wraps the target of the
proxy as an inner bean definition, since the target
is never used on its own anyway.
The following example shows such a child bean:
XML
<bean id="myService" parent="txProxyTemplate">
<property name="target">
<bean class="org.springframework.samples.MyServiceImpl">
</bean>
</property>
</bean>
You can override properties from the parent template. In the following example,
we override the
transaction propagation settings:
XML
<bean id="mySpecialService" parent="txProxyTemplate">
<property name="target">
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 334/373
6/10/22, 3:58 PM Core Technologies
<bean class="org.springframework.samples.MySpecialServiceImpl">
</bean>
</property>
<property name="transactionAttributes">
<props>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="store*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
Note that in the parent bean example, we explicitly marked the parent bean definition as
being abstract
by setting the abstract attribute to true , as described
previously, so that it may not actually ever be
instantiated. Application contexts (but not simple bean factories), by default,
pre-instantiate all singletons.
Therefore, it is important (at least for singleton beans)
that, if you have a (parent) bean definition that you
intend to use only as a template,
and this definition specifies a class, you must make sure to set the
abstract
attribute to true . Otherwise, the application context actually tries to
pre-instantiate it.
Java Kotlin
JAVA
ProxyFactory factory = new ProxyFactory(myBusinessInterfaceImpl);
factory.addAdvice(myMethodInterceptor);
factory.addAdvisor(myAdvisor);
You can add advices (with interceptors as a specialized kind of advice), advisors, or both
and manipulate
them for the life of the ProxyFactory . If you add an
IntroductionInterceptionAroundAdvisor , you can
cause the proxy to implement additional
interfaces.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 335/373
6/10/22, 3:58 PM Core Technologies
Integrating AOP proxy creation with the IoC framework is best practice in most
applications. We
recommend that you externalize configuration from Java code with AOP,
as you should in general.
Java Kotlin
JAVA
Advisor[] getAdvisors();
boolean isFrozen();
The addAdvisor() methods can be used to add any Advisor . Usually, the advisor holding
pointcut and
advice is the generic DefaultPointcutAdvisor , which you can use with
any advice or pointcut (but not for
introductions).
The following example shows casting an AOP proxy to the Advised interface and examining and
manipulating its advice:
Java Kotlin
JAVA
Advised advised = (Advised) myObject;
advised.addAdvice(new DebugInterceptor());
Depending on how you created the proxy, you can usually set a frozen flag. In that
case, the Advised
isFrozen() method returns true , and any attempts to modify
advice through addition or removal
results in an AopConfigException . The ability
to freeze the state of an advised object is useful in some
cases (for example, to
prevent calling code removing a security interceptor).
Spring also lets us use “auto-proxy” bean definitions, which can automatically
proxy selected bean
definitions. This is built on Spring’s “bean post processor”
infrastructure, which enables modification of
any bean definition as the container loads.
In this model, you set up some special bean definitions in your XML bean definition file
to configure the
auto-proxy infrastructure. This lets you declare the targets
eligible for auto-proxying. You need not use
ProxyFactoryBean .
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 337/373
6/10/22, 3:58 PM Core Technologies
By using an auto-proxy creator that refers to specific beans in the current context.
A special case of auto-proxy creation that deserves to be considered separately:
auto-proxy creation
driven by source-level metadata attributes.
BeanNameAutoProxyCreator
XML
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="interceptorNames">
<list>
<value>myInterceptor</value>
</list>
</property>
</bean>
Bean definitions whose names match, such as jdkMyBean and onlyJdk in the preceding
example, are
plain old bean definitions with the target class. An AOP proxy is
automatically created by the
BeanNameAutoProxyCreator . The same advice is applied
to all matching beans. Note that, if advisors are
used (rather than the interceptor in
the preceding example), the pointcuts may apply differently to
different beans.
DefaultAdvisorAutoProxyCreator
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 338/373
6/10/22, 3:58 PM Core Technologies
This means that any number of advisors can be applied automatically to each business
object. If no
pointcut in any of the advisors matches any method in a business object,
the object is not proxied. As
bean definitions are added for new business objects,
they are automatically proxied if necessary.
XML
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
<bean class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
</bean>
</bean>
The DefaultAdvisorAutoProxyCreator is very useful if you want to apply the same advice
consistently to
many business objects. Once the infrastructure definitions are in place,
you can add new business objects
without including specific proxy configuration.
You can also easily drop in additional aspects (for example,
tracing or
performance monitoring aspects) with minimal change to configuration.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 339/373
6/10/22, 3:58 PM Core Technologies
Developers who use Spring AOP do not normally need to work directly with TargetSource
implementations, but
this provides a powerful means of supporting pooling, hot swappable, and other
sophisticated targets. For example, a pooling TargetSource can return a different target
instance for each
invocation, by using a pool to manage instances.
The rest of this section describes the standard target sources provided with Spring and how you can use
them.
When using a custom target source, your target will usually need to be a prototype
rather than a
singleton bean definition. This allows Spring to create a new target
instance when required.
You can change the target by using the swap() method on HotSwappableTargetSource, as the follow
example shows:
Java Kotlin
JAVA
HotSwappableTargetSource swapper = (HotSwappableTargetSource) beanFactory.getBean("swapper");
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 340/373
6/10/22, 3:58 PM Core Technologies
XML
<bean id="initialTarget" class="mycompany.OldTarget"/>
<constructor-arg ref="initialTarget"/>
</bean>
</bean>
The preceding swap() call changes the target of the swappable bean. Clients that hold a
reference to that
bean are unaware of the change but immediately start hitting
the new target.
Although this example does not add any advice (it is not necessary to add advice to
use a TargetSource ),
any TargetSource can be used in conjunction with
arbitrary advice.
A crucial difference between Spring pooling and SLSB pooling is that Spring pooling can
be applied to any
POJO. As with Spring in general, this service can be applied in a
non-invasive way.
Commons Pool 1.5+ is also supported but is deprecated as of Spring Framework 4.2.
XML
<bean id="businessObjectTarget" class="com.mycompany.MyBusinessObject"
scope="prototype">
</bean>
</bean>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 341/373
6/10/22, 3:58 PM Core Technologies
<property name="interceptorNames" value="myInterceptor"/>
</bean>
Note that the target object ( businessObjectTarget in the preceding example) must be a
prototype. This
lets the PoolingTargetSource implementation create new instances
of the target to grow the pool as
necessary. See the javadoc of
AbstractPoolingTargetSource and the concrete subclass you wish to use
for information
about its properties. maxSize is the most basic and is always guaranteed to be present.
You can configure Spring to be able to cast any pooled object to the
org.springframework.aop.target.PoolingConfig interface, which exposes information
about the
configuration and current size of the pool through an introduction. You
need to define an advisor similar
to the following:
XML
<bean id="poolConfigAdvisor" class="org.springframework.beans.factory.config.MethodInvokingFactoryB
<property name="targetObject" ref="poolTargetSource"/>
</bean>
Java Kotlin
JAVA
PoolingConfig conf = (PoolingConfig) beanFactory.getBean("businessObject");
Pooling stateless service objects is not usually necessary. We do not believe it should
be the default
choice, as most stateless objects are naturally thread safe, and instance
pooling is problematic if
resources are cached.
Simpler pooling is available by using auto-proxying. You can set the TargetSource implementations
used
by any auto-proxy creator.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 342/373
6/10/22, 3:58 PM Core Technologies
To do this, you could modify the poolTargetSource definition shown earlier as follows
(we also changed
the name, for clarity):
XML
<bean id="prototypeTargetSource" class="org.springframework.aop.target.PrototypeTargetSource">
</bean>
The only property is the name of the target bean. Inheritance is used in the
TargetSource
implementations to ensure consistent naming. As with the pooling target
source, the target bean must be
a prototype bean definition.
XML
<bean id="threadlocalTargetSource" class="org.springframework.aop.target.ThreadLocalTargetSource">
</bean>
ThreadLocal instances come with serious issues (potentially resulting in memory leaks) when
incorrectly using them in multi-threaded and multi-classloader environments. You
should always
consider wrapping a threadlocal in some other class and never directly use
the ThreadLocal itself
(except in the wrapper class). Also, you should
always remember to correctly set and unset (where
the latter simply involves a call to
ThreadLocal.set(null) ) the resource local to the thread.
Unsetting should be done in
any case, since not unsetting it might result in problematic behavior.
Spring’s
ThreadLocal support does this for you and should always be considered in favor of using
ThreadLocal instances without other proper handling code.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 343/373
6/10/22, 3:58 PM Core Technologies
7. Null-safety
Although Java does not let you express null-safety with its type system, the Spring Framework
now
provides the following annotations in the org.springframework.lang package to let you
declare nullability
of APIs and fields:
The Spring Framework itself leverages these annotations, but they can also be used in any
Spring-based
Java project to declare null-safe APIs and optionally null-safe fields.
Generic type arguments, varargs and
array elements nullability are not supported yet but
should be in an upcoming release, see SPR-15942
for
up-to-date information. Nullability declarations are expected to be fine-tuned between
Spring Framework
releases, including minor ones. Nullability of types used inside method
bodies is outside of the scope of
this feature.
Other common libraries such as Reactor and Spring Data provide null-safe APIs that
use a similar
nullability arrangement, delivering a consistent overall experience for
Spring application developers.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 344/373
6/10/22, 3:58 PM Core Technologies
They are also used to make Spring API null-safe in Kotlin projects, since Kotlin natively
supports null-safety.
More details
are available in the Kotlin support documentation.
It is not necessary nor recommended to add a JSR-305 dependency to the project classpath to
take
advantage of Spring null-safe API. Only projects such as Spring-based libraries that use
null-safety
annotations in their codebase should add com.google.code.findbugs:jsr305:3.0.2
with compileOnly
Gradle configuration or Maven provided scope to avoid compile warnings.
8.1. DataBufferFactory
DataBufferFactory is used to create data buffers in one of two ways:
1. Allocate a new data buffer, optionally specifying capacity upfront, if known, which is
more efficient
even though implementations of DataBuffer can grow and shrink on demand.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 345/373
6/10/22, 3:58 PM Core Technologies
2. Wrap an existing byte[] or java.nio.ByteBuffer , which decorates the given data with
a DataBuffer
implementation and that does not involve allocation.
Note that WebFlux applications do not create a DataBufferFactory directly but instead
access it through
the ServerHttpResponse or the ClientHttpRequest on the client side.
The type of factory depends on the
underlying client or server, e.g.
NettyDataBufferFactory for Reactor Netty, DefaultDataBufferFactory
for others.
8.2. DataBuffer
The DataBuffer interface offers similar operations as java.nio.ByteBuffer but also
brings a few
additional benefits some of which are inspired by the Netty ByteBuf .
Below is a partial list of benefits:
Read and write with independent positions, i.e. not requiring a call to flip() to
alternate between
read and write.
Capacity expanded on demand as with java.lang.StringBuilder .
Pooled buffers and reference counting via PooledDataBuffer .
View a buffer as java.nio.ByteBuffer , InputStream , or OutputStream .
Determine the index, or the last index, for a given byte.
8.3. PooledDataBuffer
As explained in the Javadoc for
ByteBuffer,
byte buffers can be direct or non-direct. Direct buffers may
reside outside the Java heap
which eliminates the need for copying for native I/O operations. That makes
direct buffers
particularly useful for receiving and sending data over a socket, but they’re also more
expensive to create and release, which leads to the idea of pooling buffers.
Note that instead of operating on PooledDataBuffer directly, in most cases it’s better
to use the
convenience methods in DataBufferUtils that apply release or retain to a
DataBuffer only if it is an
instance of PooledDataBuffer .
8.4. DataBufferUtils
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 346/373
6/10/22, 3:58 PM Core Technologies
Join a stream of data buffers into a single buffer possibly with zero copy, e.g. via
composite buffers, if
that’s supported by the underlying byte buffer API.
Turn InputStream or NIO Channel into Flux<DataBuffer> , and vice versa a
Publisher<DataBuffer>
into OutputStream or NIO Channel .
8.5. Codecs
The org.springframework.core.codec package provides the following strategy interfaces:
A Decoder is the last to read input data buffers, before creating higher level
objects, and therefore it must
release them as follows:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 347/373
6/10/22, 3:58 PM Core Technologies
Note that DataBufferUtils#join offers a safe and efficient way to aggregate a data
buffer stream into a
single data buffer. Likewise skipUntilByteCount and
takeUntilByteCount are additional safe methods
for decoders to use.
An Encoder allocates data buffers that others must read (and release). So an Encoder
doesn’t have much
to do. However an Encoder must take care to release a data buffer if
a serialization error occurs while
populating the buffer with data. For example:
Java Kotlin
JAVA
DataBuffer buffer = factory.allocateBuffer();
try {
release = false;
}
finally {
if (release) {
DataBufferUtils.release(buffer);
}
}
return buffer;
The consumer of an Encoder is responsible for releasing the data buffers it receives.
In a WebFlux
application, the output of the Encoder is used to write to the HTTP server
response, or to the client HTTP
request, in which case releasing the data buffers is the
responsibility of the code writing to the server
response, or to the client request.
Note that when running on Netty, there are debugging options for
troubleshooting buffer leaks.
9. Logging
Since Spring Framework 5.0, Spring comes with its own Commons Logging bridge implemented
in the
spring-jcl module. The implementation checks for the presence of the Log4j 2.x
API and the SLF4J 1.7
API in the classpath and uses the first one of those found as the
logging implementation, falling back to
the Java platform’s core logging facilities (also
known as JUL or java.util.logging ) if neither Log4j 2.x nor
SLF4J is available.
Put Log4j 2.x or Logback (or another SLF4J provider) in your classpath, without any extra
bridges, and let
the framework auto-adapt to your choice. For further information see the
Spring
Boot Logging Reference
Documentation.
Spring’s Commons Logging variant is only meant to be used for infrastructure logging
purposes in
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 348/373
6/10/22, 3:58 PM Core Technologies
For logging needs within application code, prefer direct use of Log4j 2.x, SLF4J, or JUL.
Java Kotlin
JAVA
public class MyBean {
// ...
}
10. Appendix
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/sp
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spri
</beans>
Using <util:constant/>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 349/373
6/10/22, 3:58 PM Core Technologies
XML
<bean id="..." class="...">
<property name="isolation">
<bean id="java.sql.Connection.TRANSACTION_SERIALIZABLE"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" />
</property>
</bean>
The following XML Schema-based version is more concise, clearly expresses the
developer’s intent (“inject
this constant value”), and it reads better:
XML
<bean id="..." class="...">
<property name="isolation">
<util:constant static-field="java.sql.Connection.TRANSACTION_SERIALIZABLE"/>
</property>
</bean>
FieldRetrievingFactoryBean
is a
that retrieves a static or non-static field value. It is
FactoryBean
typically
used for retrieving public static final constants, which may then be used to set a
property
value or constructor argument for another bean.
The following example shows how a static field is exposed, by using the
staticField
property:
XML
<bean id="myField"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
</bean>
There is also a convenience usage form where the static field is specified as the bean
name, as the
following example shows:
XML
<bean id="java.sql.Connection.TRANSACTION_SERIALIZABLE"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/>
This does mean that there is no longer any choice in what the bean id is (so any other
bean that refers to
it also has to use this longer name), but this form is very
concise to define and very convenient to use as
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 350/373
6/10/22, 3:58 PM Core Technologies
XML
<bean id="..." class="...">
<property name="isolation">
<bean id="java.sql.Connection.TRANSACTION_SERIALIZABLE"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" />
</property>
</bean>
Java Kotlin
JAVA
package javax.persistence;
TRANSACTION,
EXTENDED
Now consider the following setter of type PersistenceContextType and the corresponding bean
definition:
Java Kotlin
JAVA
package example;
this.persistenceContextType = type;
}
}
XML
<bean class="example.Client">
</bean>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 351/373
6/10/22, 3:58 PM Core Technologies
Using <util:property-path/>
Consider the following example:
XML
<!-- target bean to be referenced by name -->
<property name="spouse">
<bean class="org.springframework.beans.TestBean">
<!-- results in 10, which is the value of property 'age' of bean 'testBean' -->
XML
<!-- target bean to be referenced by name -->
<property name="spouse">
<bean class="org.springframework.beans.TestBean">
<!-- results in 10, which is the value of property 'age' of bean 'testBean' -->
The value of the attribute of the <property-path/> element follows the form of
path
beanName.beanProperty . In this case, it picks up the age property of the bean named
testBean . The
value of that age property is 10 .
The following example shows a path being used against another bean, by name:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 352/373
6/10/22, 3:58 PM Core Technologies
XML
<!-- target bean to be referenced by name -->
<property name="spouse">
<bean class="org.springframework.beans.TestBean">
<!-- results in 11, which is the value of property 'spouse.age' of bean 'person' -->
<bean id="theAge"
class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
</bean>
XML
<!-- results in 12, which is the value of property 'age' of the inner bean -->
<bean id="theAge"
class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<property name="targetObject">
<bean class="org.springframework.beans.TestBean">
</bean>
There is also a shortcut form, where the bean name is the property path.
The following example shows
the shortcut form:
XML
<!-- results in 10, which is the value of property 'age' of bean 'person' -->
<bean id="person.age"
class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
This form does mean that there is no choice in the name of the bean. Any reference to it
also has to use
the same id , which is the path. If used as an inner
bean, there is no need to refer to it at all, as the
following example shows:
XML
<bean id="..." class="...">
<property name="age">
<bean id="person.age"
class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
</property>
</bean>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 353/373
6/10/22, 3:58 PM Core Technologies
You can specifically set the result type in the actual definition. This is not necessary
for most use cases, but
it can sometimes be useful. See the javadoc for more info on
this feature.
Using <util:properties/>
Consider the following example:
XML
<!-- creates a java.util.Properties instance with values loaded from the supplied location -->
</bean>
The following example uses a util:properties element to make a more concise representation:
XML
<!-- creates a java.util.Properties instance with values loaded from the supplied location -->
Using <util:list/>
Consider the following example:
XML
<!-- creates a java.util.List instance with values loaded from the supplied 'sourceList' -->
<property name="sourceList">
<list>
<value>pechorin@hero.org</value>
<value>raskolnikov@slums.org</value>
<value>stavrogin@gov.org</value>
<value>porfiry@gov.org</value>
</list>
</property>
</bean>
The following example uses a <util:list/> element to make a more concise representation:
XML
<!-- creates a java.util.List instance with the supplied values -->
<util:list id="emails">
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 354/373
6/10/22, 3:58 PM Core Technologies
<value>pechorin@hero.org</value>
<value>raskolnikov@slums.org</value>
<value>stavrogin@gov.org</value>
<value>porfiry@gov.org</value>
</util:list>
You can also explicitly control the exact type of List that is instantiated and
populated by using the
list-class attribute on the <util:list/> element. For
example, if we really need a
java.util.LinkedList to be instantiated, we could use the
following configuration:
XML
<util:list id="emails" list-class="java.util.LinkedList">
<value>jackshaftoe@vagabond.org</value>
<value>eliza@thinkingmanscrumpet.org</value>
<value>vanhoek@pirate.org</value>
<value>d'Arcachon@nemesis.org</value>
</util:list>
Using <util:map/>
Consider the following example:
XML
<!-- creates a java.util.Map instance with values loaded from the supplied 'sourceMap' -->
<property name="sourceMap">
<map>
</map>
</property>
</bean>
The following example uses a <util:map/> element to make a more concise representation:
XML
<!-- creates a java.util.Map instance with the supplied key-value pairs -->
<util:map id="emails">
</util:map>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 355/373
6/10/22, 3:58 PM Core Technologies
You can also explicitly control the exact type of Map that is instantiated and
populated by using the 'map-
class' attribute on the <util:map/> element. For
example, if we really need a java.util.TreeMap to be
instantiated, we could use the
following configuration:
XML
<util:map id="emails" map-class="java.util.TreeMap">
</util:map>
Using <util:set/>
Consider the following example:
XML
<!-- creates a java.util.Set instance with values loaded from the supplied 'sourceSet' -->
<property name="sourceSet">
<set>
<value>pechorin@hero.org</value>
<value>raskolnikov@slums.org</value>
<value>stavrogin@gov.org</value>
<value>porfiry@gov.org</value>
</set>
</property>
</bean>
The following example uses a <util:set/> element to make a more concise representation:
XML
<!-- creates a java.util.Set instance with the supplied values -->
<util:set id="emails">
<value>pechorin@hero.org</value>
<value>raskolnikov@slums.org</value>
<value>stavrogin@gov.org</value>
<value>porfiry@gov.org</value>
</util:set>
You can also explicitly control the exact type of Set that is instantiated and
populated by using the set-
class attribute on the <util:set/> element. For
example, if we really need a java.util.TreeSet to be
instantiated, we could use the
following configuration:
XML
<util:set id="emails" set-class="java.util.TreeSet">
<value>pechorin@hero.org</value>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 356/373
6/10/22, 3:58 PM Core Technologies
<value>raskolnikov@slums.org</value>
<value>stavrogin@gov.org</value>
<value>porfiry@gov.org</value>
</util:set>
In the interest of completeness, to use the tags in the aop schema, you need to have
the following
preamble at the top of your Spring XML configuration file (the text in the
snippet references the correct
schema so that the tags in the aop namespace
are available to you):
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/sp
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring
</beans>
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/sp
http://www.springframework.org/schema/context https://www.springframework.org/schema/contex
</beans>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 357/373
6/10/22, 3:58 PM Core Technologies
Using <property-placeholder/>
This element activates the replacement of ${…} placeholders, which are resolved against a
specified
properties file (as a Spring resource location). This element
is a convenience mechanism that sets up a
PropertySourcesPlaceholderConfigurer for you. If you need more control over the specific
PropertySourcesPlaceholderConfigurer setup, you can explicitly define it as a bean yourself.
Using <annotation-config/>
This element activates the Spring infrastructure to detect annotations in bean classes:
Using <component-scan/>
This element is detailed in the section on annotation-based container configuration.
Using <load-time-weaver/>
This element is detailed in the section on load-time weaving with AspectJ in the Spring Framework.
Using <spring-configured/>
This element is detailed in the section on using AspectJ to dependency inject domain objects with Spring.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 358/373
6/10/22, 3:58 PM Core Technologies
Using <mbean-export/>
This element is detailed in the section on configuring annotation-based MBean export.
Note that you can add zero or more key-value pairs to <bean/> XML definitions.
What, if anything, is done
with this extra metadata is totally up to your own custom
logic (and so is typically only of use if you write
your own custom elements as described
in the appendix entitled XML Schema Authoring).
The following example shows the <meta/> element in the context of a surrounding <bean/>
(note that,
without any logic to interpret it, the metadata is effectively useless
as it stands).
XML
<?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/sp
</bean>
</beans>
In the case of the preceding example, you could assume that there is some logic that consumes
the bean
definition and sets up some caching infrastructure that uses the supplied metadata.
XML
<myns:dateformat id="dateFormat"
pattern="yyyy-MM-dd HH:mm"
lenient="true"/>
XML
<!-- myns.xsd (inside package org/springframework/samples/xml) -->
<xsd:schema xmlns="http://www.mycompany.example/schema/myns"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:beans="http://www.springframework.org/schema/beans"
targetNamespace="http://www.mycompany.example/schema/myns"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xsd:import namespace="http://www.springframework.org/schema/beans"/>
<xsd:element name="dateformat">
<xsd:complexType>
<xsd:complexContent>
<xsd:extension base="beans:identifiedType"> 1
</xsd:extension>
</xsd:complexContent>
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 360/373
6/10/22, 3:58 PM Core Technologies
</xsd:complexType>
</xsd:element>
</xsd:schema>
1 The indicated line contains an extension base for all identifiable tags
(meaning they have an id attribute that we can use as the bean identifier in the
container). We can use this attribute because we imported the Spring-provided
beans namespace.
XML
<myns:dateformat id="dateFormat"
pattern="yyyy-MM-dd HH:mm"
lenient="true"/>
Note that, after we have created the infrastructure classes, the preceding snippet of XML is
essentially the
same as the following XML snippet:
XML
<bean id="dateFormat" class="java.text.SimpleDateFormat">
</bean>
The schema-based approach to creating configuration format allows for tight integration
with an IDE
that has a schema-aware XML editor. By using a properly authored schema, you
can use
autocompletion to let a user choose between several configuration options
defined in the
enumeration.
Although you can code your own NamespaceHandler for the entire
namespace (and hence provide code
that parses each and every element in the namespace),
it is often the case that each top-level XML
element in a Spring XML configuration file
results in a single bean definition (as in our case, where a single
<myns:dateformat/>
element results in a single SimpleDateFormat bean definition). Spring features a
number of convenience classes that support this scenario. In the following example, we
use the
NamespaceHandlerSupport class:
Java Kotlin
JAVA
package org.springframework.samples.xml;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
}
}
You may notice that there is not actually a whole lot of parsing logic
in this class. Indeed, the
NamespaceHandlerSupport class has a built-in notion of
delegation. It supports the registration of any
number of BeanDefinitionParser
instances, to which it delegates to when it needs to parse an element in
its
namespace. This clean separation of concerns lets a NamespaceHandler handle the
orchestration of the
parsing of all of the custom elements in its namespace while
delegating to BeanDefinitionParsers to do
the grunt work of the XML parsing. This
means that each BeanDefinitionParser contains only the logic
for parsing a single
custom element, as we can see in the next step.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 362/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
package org.springframework.samples.xml;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import java.text.SimpleDateFormat;
return SimpleDateFormat.class; 2
// this will never be null since the schema explicitly requires that a value be supplied
bean.addConstructorArgValue(pattern);
if (StringUtils.hasText(lenient)) {
bean.addPropertyValue("lenient", Boolean.valueOf(lenient));
In this simple case, this is all that we need to do. The creation of our single
BeanDefinition is handled by
the AbstractSingleBeanDefinitionParser superclass, as
is the extraction and setting of the bean
definition’s unique identifier.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 363/373
6/10/22, 3:58 PM Core Technologies
Writing META-INF/spring.handlers
The properties file called spring.handlers contains a mapping of XML Schema URIs to
namespace
handler classes. For our example, we need to write the following:
http\://www.mycompany.example/schema/myns=org.springframework.samples.xml.MyNamespaceHandler
The first part (the key) of the key-value pair is the URI associated with your custom
namespace extension
and needs to exactly match exactly the value of the targetNamespace
attribute, as specified in your
custom XSD schema.
Writing 'META-INF/spring.schemas'
The properties file called spring.schemas contains a mapping of XML Schema locations
(referred to, along
with the schema declaration, in XML files that use the schema as part
of the xsi:schemaLocation
attribute) to classpath resources. This file is needed
to prevent Spring from absolutely having to use a
default EntityResolver that requires
Internet access to retrieve the schema file. If you specify the
mapping in this
properties file, Spring searches for the schema (in this case,
myns.xsd in the
org.springframework.samples.xml package) on the classpath.
The following snippet shows the line we
need to add for our custom schema:
http\://www.mycompany.example/schema/myns/myns.xsd=org/springframework/samples/xml/myns.xsd
You are encouraged to deploy your XSD file (or files) right alongside
the NamespaceHandler and
BeanDefinitionParser classes on the classpath.
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:myns="http://www.mycompany.example/schema/myns"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/sp
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 364/373
6/10/22, 3:58 PM Core Technologies
http://www.mycompany.example/schema/myns http://www.mycompany.com/schema/myns/myns.xsd">
<property name="dateFormat">
</property>
</bean>
</beans>
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:foo="http://www.foo.example/schema/component"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/sp
http://www.foo.example/schema/component http://www.foo.example/schema/component/component.x
<foo:component name="Mother-1">
<foo:component name="Karate-1"/>
<foo:component name="Sport-1"/>
</foo:component>
<foo:component name="Rock-1"/>
</foo:component>
</beans>
The preceding configuration nests custom extensions within each other. The class
that is actually
configured by the <foo:component/> element is the Component
class (shown in the next example). Notice
how the Component class does not expose a
setter method for the components property. This makes it
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 365/373
6/10/22, 3:58 PM Core Technologies
Java Kotlin
JAVA
package com.foo;
import java.util.ArrayList;
import java.util.List;
this.components.add(component);
return components;
return name;
}
this.name = name;
}
}
The typical solution to this issue is to create a custom FactoryBean that exposes a
setter property for the
components property. The following listing shows such a custom
FactoryBean :
Java Kotlin
JAVA
package com.foo;
import org.springframework.beans.factory.FactoryBean;
import java.util.List;
this.parent = parent;
this.children = children;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 366/373
6/10/22, 3:58 PM Core Technologies
}
this.parent.addComponent(child);
return this.parent;
return Component.class;
return true;
}
}
This works nicely, but it exposes a lot of Spring plumbing to the end user. What we are
going to do is write
a custom extension that hides away all of this Spring plumbing.
If we stick to the steps described
previously, we start off
by creating the XSD schema to define the structure of our custom tag, as the
following
listing shows:
XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsd:schema xmlns="http://www.foo.example/schema/component"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.foo.example/schema/component"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xsd:element name="component">
<xsd:complexType>
</xsd:choice>
<xsd:attribute name="id" type="xsd:ID"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Java Kotlin
JAVA
package com.foo;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 367/373
6/10/22, 3:58 PM Core Technologies
}
}
Java Kotlin
JAVA
package com.foo;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
import java.util.List;
return parseComponentElement(element);
parseChildComponents(childElements, factory);
return factory.getBeanDefinition();
return component.getBeanDefinition();
children.add(parseComponentElement(element));
factory.addPropertyValue("children", children);
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 368/373
6/10/22, 3:58 PM Core Technologies
}
}
Finally, the various artifacts need to be registered with the Spring XML infrastructure,
by modifying the
META-INF/spring.handlers and META-INF/spring.schemas files, as follows:
# in 'META-INF/spring.handlers'
http\://www.foo.example/schema/component=com.foo.ComponentNamespaceHandler
# in 'META-INF/spring.schemas'
http\://www.foo.example/schema/component/component.xsd=com/foo/component.xsd
By way of another example, suppose that you define a bean definition for a
service object that (unknown
to it) accesses a clustered
JCache, and you want to ensure that the
named JCache instance is eagerly
started within the surrounding cluster.
The following listing shows such a definition:
XML
<bean id="checkingAccountService" class="com.foo.DefaultCheckingAccountService"
jcache:cache-name="checking.account">
</bean>
Java Kotlin
JAVA
package com.foo;
this.name = name;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 369/373
6/10/22, 3:58 PM Core Technologies
}
}
Now we can move onto the custom extension. First, we need to author
the XSD schema that describes the
custom attribute, as follows:
XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsd:schema xmlns="http://www.foo.example/schema/jcache"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.foo.example/schema/jcache"
elementFormDefault="qualified">
</xsd:schema>
Java Kotlin
JAVA
package com.foo;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
super.registerBeanDefinitionDecoratorForAttribute("cache-name",
new JCacheInitializingBeanDefinitionDecorator());
Next, we need to create the parser. Note that, in this case, because we are going to parse
an XML
attribute, we write a BeanDefinitionDecorator rather than a BeanDefinitionParser .
The following listing
shows our BeanDefinitionDecorator implementation:
Java Kotlin
JAVA
package com.foo;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.BeanDefinitionDecorator;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 370/373
6/10/22, 3:58 PM Core Technologies
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
ParserContext ctx) {
createDependencyOnJCacheInitializer(holder, initializerBeanName);
return holder;
String initializerBeanName) {
if (dependsOn == null) {
} else {
dependencies.add(initializerBeanName);
definition.setDependsOn(dependsOn);
if (!ctx.getRegistry().containsBeanDefinition(beanName)) {
ctx.getRegistry().registerBeanDefinition(beanName, initializer.getBeanDefinition());
return beanName;
}
}
Finally, we need to register the various artifacts with the Spring XML infrastructure
by modifying the META-
INF/spring.handlers and META-INF/spring.schemas files, as follows:
# in 'META-INF/spring.handlers'
http\://www.foo.example/schema/jcache=com.foo.JCacheNamespaceHandler
# in 'META-INF/spring.schemas'
http\://www.foo.example/schema/jcache/jcache.xsd=com/foo/jcache.xsd
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 371/373
6/10/22, 3:58 PM Core Technologies
The name and detailed information about each startup step is not part of the public contract and
is
subject to change; this is considered as an implementation detail of the core container and will follow
its behavior changes.
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 372/373
6/10/22, 3:58 PM Core Technologies
Version 5.3.20
Last updated 2022-05-11 06:55:18 UTC
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans 373/373