diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js
index 3bcfb845f99a4d975b3816f197e770cfbdfead36..19228687ef6f63542235d0dbd1da917cc46daf07 100644
--- a/docs/.vuepress/config.js
+++ b/docs/.vuepress/config.js
@@ -148,21 +148,52 @@ module.exports = {
}
],
sidebar: {
+ '/en/spring-framework/': [
+ {
+ title: 'Spring Framework',
+ sidebarDepth: 2,
+ collapsable: false,
+ children: [
+ "/en/spring-framework/overview.md",
+ "/en/spring-framework/core.md",
+ "/en/spring-framework/testing.md",
+ "/en/spring-framework/data-access.md",
+ "/en/spring-framework/web-servlet.md",
+ "/en/spring-framework/web-reactive.md",
+ "/en/spring-framework/integration.md",
+ "/en/spring-framework/languages.md"
+ ],
+ initialOpenGroupIndex: 0 // 可选的, 默认值是 0
+ }
+ ],
'/en/spring-boot/': [
{
title: 'Spring Boot',
sidebarDepth: 2,
collapsable: false,
children: [
- "/en/spring-boot/build-tool-plugins.md",
- "/en/spring-boot/container-images.md",
- "/en/spring-boot/core-features.md",
+ "/en/spring-boot/legal.md",
+ "/en/spring-boot/getting-help.md",
+ "/en/spring-boot/documentation.md",
+ "/en/spring-boot/getting-started.md",
+ "/en/spring-boot/upgrading.md",
+ "/en/spring-boot/using.md",
+ "/en/spring-boot/features.md",
+ "/en/spring-boot/web.md",
"/en/spring-boot/data.md",
- "/en/spring-boot/deploying-spring-boot-applications.md"
+ "/en/spring-boot/io.md",
+ "/en/spring-boot/messaging.md",
+ "/en/spring-boot/container-images.md",
+ "/en/spring-boot/actuator.md",
+ "/en/spring-boot/deployment.md",
+ "/en/spring-boot/cli.md",
+ "/en/spring-boot/build-tool-plugins.md",
+ "/en/spring-boot/howto.md"
],
initialOpenGroupIndex: 0 // 可选的, 默认值是 0
}
],
+
// fallback
'/en/':
[{
@@ -278,15 +309,45 @@ module.exports = {
'/spring-boot/': [
{
- title: '介绍',
+ title: 'Spring Boot 文档',
sidebarDepth: 2,
collapsable: false,
children: [
- "/spring-boot/build-tool-plugins.md",
- "/spring-boot/container-images.md",
- "/spring-boot/core-features.md",
+ "/spring-boot/legal.md",
+ "/spring-boot/getting-help.md",
+ "/spring-boot/documentation.md",
+ "/spring-boot/getting-started.md",
+ "/spring-boot/upgrading.md",
+ "/spring-boot/using.md",
+ "/spring-boot/features.md",
+ "/spring-boot/web.md",
"/spring-boot/data.md",
- "/spring-boot/deploying-spring-boot-applications.md"
+ "/spring-boot/io.md",
+ "/spring-boot/messaging.md",
+ "/spring-boot/container-images.md",
+ "/spring-boot/actuator.md",
+ "/spring-boot/deployment.md",
+ "/spring-boot/cli.md",
+ "/spring-boot/build-tool-plugins.md",
+ "/spring-boot/howto.md"
+ ],
+ initialOpenGroupIndex: 0 // 可选的, 默认值是 0
+ }
+ ],
+ '/spring-framework/': [
+ {
+ title: 'Spring Framework 文档',
+ sidebarDepth: 2,
+ collapsable: false,
+ children: [
+ "/spring-framework/overview.md",
+ "/spring-framework/core.md",
+ "/spring-framework/testing.md",
+ "/spring-framework/data-access.md",
+ "/spring-framework/web-servlet.md",
+ "/spring-framework/web-reactive.md",
+ "/spring-framework/integration.md",
+ "/spring-framework/languages.md"
],
initialOpenGroupIndex: 0 // 可选的, 默认值是 0
}
diff --git a/docs/en/spring-boot/build-tool-plugins.md b/docs/en/spring-boot/build-tool-plugins.md
index f9c149e17afb9986c3a75dae1d757f46e608c726..abeb91f78aad0d0ddb5d6a876a4986579094c4bf 100644
--- a/docs/en/spring-boot/build-tool-plugins.md
+++ b/docs/en/spring-boot/build-tool-plugins.md
@@ -1,4 +1,4 @@
-# 1. Build Tool Plugins
+# Build Tool Plugins
Spring Boot provides build tool plugins for Maven and Gradle.
The plugins offer a variety of features, including the packaging of executable jars.
diff --git a/docs/en/spring-boot/documentation.md b/docs/en/spring-boot/documentation.md
index 3c484c4c4876ecb2eef30ea67b9172ff46718192..e3f939afb734807725136cba84214b6dee9f2a1c 100644
--- a/docs/en/spring-boot/documentation.md
+++ b/docs/en/spring-boot/documentation.md
@@ -53,7 +53,7 @@ Need more details about Spring Boot’s core features?[The following content is
* **Logging:** [Logging](features.html#features.logging)
-## 5. Web-
+## 5. Web
If you develop Spring Boot web applications, take a look at the following content:
@@ -91,7 +91,7 @@ If your application uses any messaging protocol, see one or more of the followin
* **Spring Integration:** [Auto-configuration for Spring Integration](messaging.html#messaging.spring-integration)
-## 8. IO--
+## 8. IO
If your application needs IO capabilities, see one or more of the following sections:
diff --git a/docs/en/spring-framework/READEME.md b/docs/en/spring-framework/READEME.md
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/docs/en/spring-framework/README.md b/docs/en/spring-framework/README.md
index 5edac6a83dc72d93ef5d143d95960c96f88b352d..a0fa33a12b80e6617e48c199557ecf7fa94d9969 100644
--- a/docs/en/spring-framework/README.md
+++ b/docs/en/spring-framework/README.md
@@ -1 +1 @@
-# Spring Framework
\ No newline at end of file
+# Spring Framework
diff --git a/docs/en/spring-framework/core.md b/docs/en/spring-framework/core.md
index 2feb74a61c456321efd5bd802f5158c11ad0695b..8ee51af7678e80ffbce70e9be63dd1cae0b28348 100644
--- a/docs/en/spring-framework/core.md
+++ b/docs/en/spring-framework/core.md
@@ -1,455 +1,4 @@
-Core Technologies
-==========
-
-version 5.3.16
-
-Table of Contents
-
-* [1. The IoC Container](#beans)
- * [1.1. Introduction to the Spring IoC Container and Beans](#beans-introduction)
- * [1.2. Container Overview](#beans-basics)
- * [1.2.1. Configuration Metadata](#beans-factory-metadata)
- * [1.2.2. Instantiating a Container](#beans-factory-instantiation)
- * [Composing XML-based Configuration Metadata](#beans-factory-xml-import)
- * [The Groovy Bean Definition DSL](#groovy-bean-definition-dsl)
-
- * [1.2.3. Using the Container](#beans-factory-client)
-
- * [1.3. Bean Overview](#beans-definition)
- * [1.3.1. Naming Beans](#beans-beanname)
- * [Aliasing a Bean outside the Bean Definition](#beans-beanname-alias)
-
- * [1.3.2. Instantiating Beans](#beans-factory-class)
- * [Instantiation with a Constructor](#beans-factory-class-ctor)
- * [Instantiation with a Static Factory Method](#beans-factory-class-static-factory-method)
- * [Instantiation by Using an Instance Factory Method](#beans-factory-class-instance-factory-method)
- * [Determining a Bean’s Runtime Type](#beans-factory-type-determination)
-
- * [1.4. Dependencies](#beans-dependencies)
- * [1.4.1. Dependency Injection](#beans-factory-collaborators)
- * [Constructor-based Dependency Injection](#beans-constructor-injection)
- * [Setter-based Dependency Injection](#beans-setter-injection)
- * [Dependency Resolution Process](#beans-dependency-resolution)
- * [Examples of Dependency Injection](#beans-some-examples)
-
- * [1.4.2. Dependencies and Configuration in Detail](#beans-factory-properties-detailed)
- * [Straight Values (Primitives, Strings, and so on)](#beans-value-element)
- * [References to Other Beans (Collaborators)](#beans-ref-element)
- * [Inner Beans](#beans-inner-beans)
- * [Collections](#beans-collection-elements)
- * [Null and Empty String Values](#beans-null-element)
- * [XML Shortcut with the p-namespace](#beans-p-namespace)
- * [XML Shortcut with the c-namespace](#beans-c-namespace)
- * [Compound Property Names](#beans-compound-property-names)
-
- * [1.4.3. Using `depends-on`](#beans-factory-dependson)
- * [1.4.4. Lazy-initialized Beans](#beans-factory-lazy-init)
- * [1.4.5. Autowiring Collaborators](#beans-factory-autowire)
- * [Limitations and Disadvantages of Autowiring](#beans-autowired-exceptions)
- * [Excluding a Bean from Autowiring](#beans-factory-autowire-candidate)
-
- * [1.4.6. Method Injection](#beans-factory-method-injection)
- * [Lookup Method Injection](#beans-factory-lookup-method-injection)
- * [Arbitrary Method Replacement](#beans-factory-arbitrary-method-replacement)
-
- * [1.5. Bean Scopes](#beans-factory-scopes)
- * [1.5.1. The Singleton Scope](#beans-factory-scopes-singleton)
- * [1.5.2. The Prototype Scope](#beans-factory-scopes-prototype)
- * [1.5.3. Singleton Beans with Prototype-bean Dependencies](#beans-factory-scopes-sing-prot-interaction)
- * [1.5.4. Request, Session, Application, and WebSocket Scopes](#beans-factory-scopes-other)
- * [Initial Web Configuration](#beans-factory-scopes-other-web-configuration)
- * [Request scope](#beans-factory-scopes-request)
- * [Session Scope](#beans-factory-scopes-session)
- * [Application Scope](#beans-factory-scopes-application)
- * [WebSocket Scope](#beans-factory-scopes-websocket)
- * [Scoped Beans as Dependencies](#beans-factory-scopes-other-injection)
-
- * [1.5.5. Custom Scopes](#beans-factory-scopes-custom)
- * [Creating a Custom Scope](#beans-factory-scopes-custom-creating)
- * [Using a Custom Scope](#beans-factory-scopes-custom-using)
-
- * [1.6. Customizing the Nature of a Bean](#beans-factory-nature)
- * [1.6.1. Lifecycle Callbacks](#beans-factory-lifecycle)
- * [Initialization Callbacks](#beans-factory-lifecycle-initializingbean)
- * [Destruction Callbacks](#beans-factory-lifecycle-disposablebean)
- * [Default Initialization and Destroy Methods](#beans-factory-lifecycle-default-init-destroy-methods)
- * [Combining Lifecycle Mechanisms](#beans-factory-lifecycle-combined-effects)
- * [Startup and Shutdown Callbacks](#beans-factory-lifecycle-processor)
- * [Shutting Down the Spring IoC Container Gracefully in Non-Web Applications](#beans-factory-shutdown)
-
- * [1.6.2. `ApplicationContextAware` and `BeanNameAware`](#beans-factory-aware)
- * [1.6.3. Other `Aware` Interfaces](#aware-list)
-
- * [1.7. Bean Definition Inheritance](#beans-child-bean-definitions)
- * [1.8. Container Extension Points](#beans-factory-extension)
- * [1.8.1. Customizing Beans by Using a `BeanPostProcessor`](#beans-factory-extension-bpp)
- * [Example: Hello World, `BeanPostProcessor`-style](#beans-factory-extension-bpp-examples-hw)
- * [Example: The `AutowiredAnnotationBeanPostProcessor`](#beans-factory-extension-bpp-examples-aabpp)
-
- * [1.8.2. Customizing Configuration Metadata with a `BeanFactoryPostProcessor`](#beans-factory-extension-factory-postprocessors)
- * [Example: The Class Name Substitution `PropertySourcesPlaceholderConfigurer`](#beans-factory-placeholderconfigurer)
- * [Example: The `PropertyOverrideConfigurer`](#beans-factory-overrideconfigurer)
-
- * [1.8.3. Customizing Instantiation Logic with a `FactoryBean`](#beans-factory-extension-factorybean)
-
- * [1.9. Annotation-based Container Configuration](#beans-annotation-config)
- * [1.9.1. @Required](#beans-required-annotation)
- * [1.9.2. Using `@Autowired`](#beans-autowired-annotation)
- * [1.9.3. Fine-tuning Annotation-based Autowiring with `@Primary`](#beans-autowired-annotation-primary)
- * [1.9.4. Fine-tuning Annotation-based Autowiring with Qualifiers](#beans-autowired-annotation-qualifiers)
- * [1.9.5. Using Generics as Autowiring Qualifiers](#beans-generics-as-qualifiers)
- * [1.9.6. Using `CustomAutowireConfigurer`](#beans-custom-autowire-configurer)
- * [1.9.7. Injection with `@Resource`](#beans-resource-annotation)
- * [1.9.8. Using `@Value`](#beans-value-annotations)
- * [1.9.9. Using `@PostConstruct` and `@PreDestroy`](#beans-postconstruct-and-predestroy-annotations)
-
- * [1.10. Classpath Scanning and Managed Components](#beans-classpath-scanning)
- * [1.10.1. `@Component` and Further Stereotype Annotations](#beans-stereotype-annotations)
- * [1.10.2. Using Meta-annotations and Composed Annotations](#beans-meta-annotations)
- * [1.10.3. Automatically Detecting Classes and Registering Bean Definitions](#beans-scanning-autodetection)
- * [1.10.4. Using Filters to Customize Scanning](#beans-scanning-filters)
- * [1.10.5. Defining Bean Metadata within Components](#beans-factorybeans-annotations)
- * [1.10.6. Naming Autodetected Components](#beans-scanning-name-generator)
- * [1.10.7. Providing a Scope for Autodetected Components](#beans-scanning-scope-resolver)
- * [1.10.8. Providing Qualifier Metadata with Annotations](#beans-scanning-qualifiers)
- * [1.10.9. Generating an Index of Candidate Components](#beans-scanning-index)
-
- * [1.11. Using JSR 330 Standard Annotations](#beans-standard-annotations)
- * [1.11.1. Dependency Injection with `@Inject` and `@Named`](#beans-inject-named)
- * [1.11.2. `@Named` and `@ManagedBean`: Standard Equivalents to the `@Component` Annotation](#beans-named)
- * [1.11.3. Limitations of JSR-330 Standard Annotations](#beans-standard-annotations-limitations)
-
- * [1.12. Java-based Container Configuration](#beans-java)
- * [1.12.1. Basic Concepts: `@Bean` and `@Configuration`](#beans-java-basic-concepts)
- * [1.12.2. Instantiating the Spring Container by Using `AnnotationConfigApplicationContext`](#beans-java-instantiating-container)
- * [Simple Construction](#beans-java-instantiating-container-constructor)
- * [Building the Container Programmatically by Using `register(Class>…)`](#beans-java-instantiating-container-register)
- * [Enabling Component Scanning with `scan(String…)`](#beans-java-instantiating-container-scan)
- * [Support for Web Applications with `AnnotationConfigWebApplicationContext`](#beans-java-instantiating-container-web)
-
- * [1.12.3. Using the `@Bean` Annotation](#beans-java-bean-annotation)
- * [Declaring a Bean](#beans-java-declaring-a-bean)
- * [Bean Dependencies](#beans-java-dependencies)
- * [Receiving Lifecycle Callbacks](#beans-java-lifecycle-callbacks)
- * [Specifying Bean Scope](#beans-java-specifying-bean-scope)
- * [Customizing Bean Naming](#beans-java-customizing-bean-naming)
- * [Bean Aliasing](#beans-java-bean-aliasing)
- * [Bean Description](#beans-java-bean-description)
-
- * [1.12.4. Using the `@Configuration` annotation](#beans-java-configuration-annotation)
- * [Injecting Inter-bean Dependencies](#beans-java-injecting-dependencies)
- * [Lookup Method Injection](#beans-java-method-injection)
- * [Further Information About How Java-based Configuration Works Internally](#beans-java-further-information-java-config)
-
- * [1.12.5. Composing Java-based Configurations](#beans-java-composing-configuration-classes)
- * [Using the `@Import` Annotation](#beans-java-using-import)
- * [Conditionally Include `@Configuration` Classes or `@Bean` Methods](#beans-java-conditional)
- * [Combining Java and XML Configuration](#beans-java-combining)
-
- * [1.13. Environment Abstraction](#beans-environment)
- * [1.13.1. Bean Definition Profiles](#beans-definition-profiles)
- * [Using `@Profile`](#beans-definition-profiles-java)
- * [XML Bean Definition Profiles](#beans-definition-profiles-xml)
- * [Activating a Profile](#beans-definition-profiles-enable)
- * [Default Profile](#beans-definition-profiles-default)
-
- * [1.13.2. `PropertySource` Abstraction](#beans-property-source-abstraction)
- * [1.13.3. Using `@PropertySource`](#beans-using-propertysource)
- * [1.13.4. Placeholder Resolution in Statements](#beans-placeholder-resolution-in-statements)
-
- * [1.14. Registering a `LoadTimeWeaver`](#context-load-time-weaver)
- * [1.15. Additional Capabilities of the `ApplicationContext`](#context-introduction)
- * [1.15.1. Internationalization using `MessageSource`](#context-functionality-messagesource)
- * [1.15.2. Standard and Custom Events](#context-functionality-events)
- * [Annotation-based Event Listeners](#context-functionality-events-annotation)
- * [Asynchronous Listeners](#context-functionality-events-async)
- * [Ordering Listeners](#context-functionality-events-order)
- * [Generic Events](#context-functionality-events-generics)
-
- * [1.15.3. Convenient Access to Low-level Resources](#context-functionality-resources)
- * [1.15.4. Application Startup Tracking](#context-functionality-startup)
- * [1.15.5. Convenient ApplicationContext Instantiation for Web Applications](#context-create)
- * [1.15.6. Deploying a Spring `ApplicationContext` as a Java EE RAR File](#context-deploy-rar)
-
- * [1.16. The `BeanFactory`](#beans-beanfactory)
- * [1.16.1. `BeanFactory` or `ApplicationContext`?](#context-introduction-ctx-vs-beanfactory)
-
-* [2. Resources](#resources)
- * [2.1. Introduction](#resources-introduction)
- * [2.2. The `Resource` Interface](#resources-resource)
- * [2.3. Built-in `Resource` Implementations](#resources-implementations)
- * [2.3.1. `UrlResource`](#resources-implementations-urlresource)
- * [2.3.2. `ClassPathResource`](#resources-implementations-classpathresource)
- * [2.3.3. `FileSystemResource`](#resources-implementations-filesystemresource)
- * [2.3.4. `PathResource`](#resources-implementations-pathresource)
- * [2.3.5. `ServletContextResource`](#resources-implementations-servletcontextresource)
- * [2.3.6. `InputStreamResource`](#resources-implementations-inputstreamresource)
- * [2.3.7. `ByteArrayResource`](#resources-implementations-bytearrayresource)
-
- * [2.4. The `ResourceLoader` Interface](#resources-resourceloader)
- * [2.5. The `ResourcePatternResolver` Interface](#resources-resourcepatternresolver)
- * [2.6. The `ResourceLoaderAware` Interface](#resources-resourceloaderaware)
- * [2.7. Resources as Dependencies](#resources-as-dependencies)
- * [2.8. Application Contexts and Resource Paths](#resources-app-ctx)
- * [2.8.1. Constructing Application Contexts](#resources-app-ctx-construction)
- * [Constructing `ClassPathXmlApplicationContext` Instances — Shortcuts](#resources-app-ctx-classpathxml)
-
- * [2.8.2. Wildcards in Application Context Constructor Resource Paths](#resources-app-ctx-wildcards-in-resource-paths)
- * [Ant-style Patterns](#resources-app-ctx-ant-patterns-in-paths)
- * [The `classpath*:` Prefix](#resources-classpath-wildcards)
- * [Other Notes Relating to Wildcards](#resources-wildcards-in-path-other-stuff)
-
- * [2.8.3. `FileSystemResource` Caveats](#resources-filesystemresource-caveats)
-
-* [3. Validation, Data Binding, and Type Conversion](#validation)
- * [3.1. Validation by Using Spring’s Validator Interface](#validator)
- * [3.2. Resolving Codes to Error Messages](#validation-conversion)
- * [3.3. Bean Manipulation and the `BeanWrapper`](#beans-beans)
- * [3.3.1. Setting and Getting Basic and Nested Properties](#beans-beans-conventions)
- * [3.3.2. Built-in `PropertyEditor` Implementations](#beans-beans-conversion)
- * [Registering Additional Custom `PropertyEditor` Implementations](#beans-beans-conversion-customeditor-registration)
-
- * [3.4. Spring Type Conversion](#core-convert)
- * [3.4.1. Converter SPI](#core-convert-Converter-API)
- * [3.4.2. Using `ConverterFactory`](#core-convert-ConverterFactory-SPI)
- * [3.4.3. Using `GenericConverter`](#core-convert-GenericConverter-SPI)
- * [Using `ConditionalGenericConverter`](#core-convert-ConditionalGenericConverter-SPI)
-
- * [3.4.4. The `ConversionService` API](#core-convert-ConversionService-API)
- * [3.4.5. Configuring a `ConversionService`](#core-convert-Spring-config)
- * [3.4.6. Using a `ConversionService` Programmatically](#core-convert-programmatic-usage)
-
- * [3.5. Spring Field Formatting](#format)
- * [3.5.1. The `Formatter` SPI](#format-Formatter-SPI)
- * [3.5.2. Annotation-driven Formatting](#format-CustomFormatAnnotations)
- * [Format Annotation API](#format-annotations-api)
-
- * [3.5.3. The `FormatterRegistry` SPI](#format-FormatterRegistry-SPI)
- * [3.5.4. The `FormatterRegistrar` SPI](#format-FormatterRegistrar-SPI)
- * [3.5.5. Configuring Formatting in Spring MVC](#format-configuring-formatting-mvc)
-
- * [3.6. Configuring a Global Date and Time Format](#format-configuring-formatting-globaldatetimeformat)
- * [3.7. Java Bean Validation](#validation-beanvalidation)
- * [3.7.1. Overview of Bean Validation](#validation-beanvalidation-overview)
- * [3.7.2. Configuring a Bean Validation Provider](#validation-beanvalidation-spring)
- * [Injecting a Validator](#validation-beanvalidation-spring-inject)
- * [Configuring Custom Constraints](#validation-beanvalidation-spring-constraints)
- * [Spring-driven Method Validation](#validation-beanvalidation-spring-method)
- * [Additional Configuration Options](#validation-beanvalidation-spring-other)
-
- * [3.7.3. Configuring a `DataBinder`](#validation-binder)
- * [3.7.4. Spring MVC 3 Validation](#validation-mvc)
-
-* [4. Spring Expression Language (SpEL)](#expressions)
- * [4.1. Evaluation](#expressions-evaluation)
- * [4.1.1. Understanding `EvaluationContext`](#expressions-evaluation-context)
- * [Type Conversion](#expressions-type-conversion)
-
- * [4.1.2. Parser Configuration](#expressions-parser-configuration)
- * [4.1.3. SpEL Compilation](#expressions-spel-compilation)
- * [Compiler Configuration](#expressions-compiler-configuration)
- * [Compiler Limitations](#expressions-compiler-limitations)
-
- * [4.2. Expressions in Bean Definitions](#expressions-beandef)
- * [4.2.1. XML Configuration](#expressions-beandef-xml-based)
- * [4.2.2. Annotation Configuration](#expressions-beandef-annotation-based)
-
- * [4.3. Language Reference](#expressions-language-ref)
- * [4.3.1. Literal Expressions](#expressions-ref-literal)
- * [4.3.2. Properties, Arrays, Lists, Maps, and Indexers](#expressions-properties-arrays)
- * [4.3.3. Inline Lists](#expressions-inline-lists)
- * [4.3.4. Inline Maps](#expressions-inline-maps)
- * [4.3.5. Array Construction](#expressions-array-construction)
- * [4.3.6. Methods](#expressions-methods)
- * [4.3.7. Operators](#expressions-operators)
- * [Relational Operators](#expressions-operators-relational)
- * [Logical Operators](#expressions-operators-logical)
- * [Mathematical Operators](#expressions-operators-mathematical)
- * [The Assignment Operator](#expressions-assignment)
-
- * [4.3.8. Types](#expressions-types)
- * [4.3.9. Constructors](#expressions-constructors)
- * [4.3.10. Variables](#expressions-ref-variables)
- * [The `#this` and `#root` Variables](#expressions-this-root)
-
- * [4.3.11. Functions](#expressions-ref-functions)
- * [4.3.12. Bean References](#expressions-bean-references)
- * [4.3.13. Ternary Operator (If-Then-Else)](#expressions-operator-ternary)
- * [4.3.14. The Elvis Operator](#expressions-operator-elvis)
- * [4.3.15. Safe Navigation Operator](#expressions-operator-safe-navigation)
- * [4.3.16. Collection Selection](#expressions-collection-selection)
- * [4.3.17. Collection Projection](#expressions-collection-projection)
- * [4.3.18. Expression templating](#expressions-templating)
-
- * [4.4. Classes Used in the Examples](#expressions-example-classes)
-
-* [5. Aspect Oriented Programming with Spring](#aop)
- * [5.1. AOP Concepts](#aop-introduction-defn)
- * [5.2. Spring AOP Capabilities and Goals](#aop-introduction-spring-defn)
- * [5.3. AOP Proxies](#aop-introduction-proxies)
- * [5.4. @AspectJ support](#aop-ataspectj)
- * [5.4.1. Enabling @AspectJ Support](#aop-aspectj-support)
- * [Enabling @AspectJ Support with Java Configuration](#aop-enable-aspectj-java)
- * [Enabling @AspectJ Support with XML Configuration](#aop-enable-aspectj-xml)
-
- * [5.4.2. Declaring an Aspect](#aop-at-aspectj)
- * [5.4.3. Declaring a Pointcut](#aop-pointcuts)
- * [Supported Pointcut Designators](#aop-pointcuts-designators)
- * [Combining Pointcut Expressions](#aop-pointcuts-combining)
- * [Sharing Common Pointcut Definitions](#aop-common-pointcuts)
- * [Examples](#aop-pointcuts-examples)
- * [Writing Good Pointcuts](#writing-good-pointcuts)
-
- * [5.4.4. Declaring Advice](#aop-advice)
- * [Before Advice](#aop-advice-before)
- * [After Returning Advice](#aop-advice-after-returning)
- * [After Throwing Advice](#aop-advice-after-throwing)
- * [After (Finally) Advice](#aop-advice-after-finally)
- * [Around Advice](#aop-ataspectj-around-advice)
- * [Advice Parameters](#aop-ataspectj-advice-params)
- * [Advice Ordering](#aop-ataspectj-advice-ordering)
-
- * [5.4.5. Introductions](#aop-introductions)
- * [5.4.6. Aspect Instantiation Models](#aop-instantiation-models)
- * [5.4.7. An AOP Example](#aop-ataspectj-example)
-
- * [5.5. Schema-based AOP Support](#aop-schema)
- * [5.5.1. Declaring an Aspect](#aop-schema-declaring-an-aspect)
- * [5.5.2. Declaring a Pointcut](#aop-schema-pointcuts)
- * [5.5.3. Declaring Advice](#aop-schema-advice)
- * [Before Advice](#aop-schema-advice-before)
- * [After Returning Advice](#aop-schema-advice-after-returning)
- * [After Throwing Advice](#aop-schema-advice-after-throwing)
- * [After (Finally) Advice](#aop-schema-advice-after-finally)
- * [Around Advice](#aop-schema-advice-around)
- * [Advice Parameters](#aop-schema-params)
- * [Advice Ordering](#aop-ordering)
-
- * [5.5.4. Introductions](#aop-schema-introductions)
- * [5.5.5. Aspect Instantiation Models](#aop-schema-instatiation-models)
- * [5.5.6. Advisors](#aop-schema-advisors)
- * [5.5.7. An AOP Schema Example](#aop-schema-example)
-
- * [5.6. Choosing which AOP Declaration Style to Use](#aop-choosing)
- * [5.6.1. Spring AOP or Full AspectJ?](#aop-spring-or-aspectj)
- * [5.6.2. @AspectJ or XML for Spring AOP?](#aop-ataspectj-or-xml)
-
- * [5.7. Mixing Aspect Types](#aop-mixing-styles)
- * [5.8. Proxying Mechanisms](#aop-proxying)
- * [5.8.1. Understanding AOP Proxies](#aop-understanding-aop-proxies)
-
- * [5.9. Programmatic Creation of @AspectJ Proxies](#aop-aspectj-programmatic)
- * [5.10. Using AspectJ with Spring Applications](#aop-using-aspectj)
- * [5.10.1. Using AspectJ to Dependency Inject Domain Objects with Spring](#aop-atconfigurable)
- * [Unit Testing `@Configurable` Objects](#aop-configurable-testing)
- * [Working with Multiple Application Contexts](#aop-configurable-container)
-
- * [5.10.2. Other Spring aspects for AspectJ](#aop-ajlib-other)
- * [5.10.3. Configuring AspectJ Aspects by Using Spring IoC](#aop-aj-configure)
- * [5.10.4. Load-time Weaving with AspectJ in the Spring Framework](#aop-aj-ltw)
- * [A First Example](#aop-aj-ltw-first-example)
- * [Aspects](#aop-aj-ltw-the-aspects)
- * ['META-INF/aop.xml'](#aop-aj-ltw-aop_dot_xml)
- * [Required libraries (JARS)](#aop-aj-ltw-libraries)
- * [Spring Configuration](#aop-aj-ltw-spring)
- * [Environment-specific Configuration](#aop-aj-ltw-environments)
-
- * [5.11. Further Resources](#aop-resources)
-
-* [6. Spring AOP APIs](#aop-api)
- * [6.1. Pointcut API in Spring](#aop-api-pointcuts)
- * [6.1.1. Concepts](#aop-api-concepts)
- * [6.1.2. Operations on Pointcuts](#aop-api-pointcut-ops)
- * [6.1.3. AspectJ Expression Pointcuts](#aop-api-pointcuts-aspectj)
- * [6.1.4. Convenience Pointcut Implementations](#aop-api-pointcuts-impls)
- * [Static Pointcuts](#aop-api-pointcuts-static)
- * [Dynamic pointcuts](#aop-api-pointcuts-dynamic)
-
- * [6.1.5. Pointcut Superclasses](#aop-api-pointcuts-superclasses)
- * [6.1.6. Custom Pointcuts](#aop-api-pointcuts-custom)
-
- * [6.2. Advice API in Spring](#aop-api-advice)
- * [6.2.1. Advice Lifecycles](#aop-api-advice-lifecycle)
- * [6.2.2. Advice Types in Spring](#aop-api-advice-types)
- * [Interception Around Advice](#aop-api-advice-around)
- * [Before Advice](#aop-api-advice-before)
- * [Throws Advice](#aop-api-advice-throws)
- * [After Returning Advice](#aop-api-advice-after-returning)
- * [Introduction Advice](#aop-api-advice-introduction)
-
- * [6.3. The Advisor API in Spring](#aop-api-advisor)
- * [6.4. Using the `ProxyFactoryBean` to Create AOP Proxies](#aop-pfb)
- * [6.4.1. Basics](#aop-pfb-1)
- * [6.4.2. JavaBean Properties](#aop-pfb-2)
- * [6.4.3. JDK- and CGLIB-based proxies](#aop-pfb-proxy-types)
- * [6.4.4. Proxying Interfaces](#aop-api-proxying-intf)
- * [6.4.5. Proxying Classes](#aop-api-proxying-class)
- * [6.4.6. Using “Global” Advisors](#aop-global-advisors)
-
- * [6.5. Concise Proxy Definitions](#aop-concise-proxy)
- * [6.6. Creating AOP Proxies Programmatically with the `ProxyFactory`](#aop-prog)
- * [6.7. Manipulating Advised Objects](#aop-api-advised)
- * [6.8. Using the "auto-proxy" facility](#aop-autoproxy)
- * [6.8.1. Auto-proxy Bean Definitions](#aop-autoproxy-choices)
- * [`BeanNameAutoProxyCreator`](#aop-api-autoproxy)
- * [`DefaultAdvisorAutoProxyCreator`](#aop-api-autoproxy-default)
-
- * [6.9. Using `TargetSource` Implementations](#aop-targetsource)
- * [6.9.1. Hot-swappable Target Sources](#aop-ts-swap)
- * [6.9.2. Pooling Target Sources](#aop-ts-pool)
- * [6.9.3. Prototype Target Sources](#aop-ts-prototype)
- * [6.9.4. `ThreadLocal` Target Sources](#aop-ts-threadlocal)
-
- * [6.10. Defining New Advice Types](#aop-extensibility)
-
-* [7. Null-safety](#null-safety)
- * [7.1. Use cases](#use-cases)
- * [7.2. JSR-305 meta-annotations](#jsr-305-meta-annotations)
-
-* [8. Data Buffers and Codecs](#databuffers)
- * [8.1. `DataBufferFactory`](#databuffers-factory)
- * [8.2. `DataBuffer`](#databuffers-buffer)
- * [8.3. `PooledDataBuffer`](#databuffers-buffer-pooled)
- * [8.4. `DataBufferUtils`](#databuffers-utils)
- * [8.5. Codecs](#codecs)
- * [8.6. Using `DataBuffer`](#databuffers-using)
-
-* [9. Logging](#spring-jcl)
-* [10. Appendix](#appendix)
- * [10.1. XML Schemas](#xsd-schemas)
- * [10.1.1. The `util` Schema](#xsd-schemas-util)
- * [Using ``](#xsd-schemas-util-constant)
- * [Using ``](#xsd-schemas-util-property-path)
- * [Using ``](#xsd-schemas-util-properties)
- * [Using ``](#xsd-schemas-util-list)
- * [Using ``](#xsd-schemas-util-map)
- * [Using ``](#xsd-schemas-util-set)
-
- * [10.1.2. The `aop` Schema](#xsd-schemas-aop)
- * [10.1.3. The `context` Schema](#xsd-schemas-context)
- * [Using ``](#xsd-schemas-context-pphc)
- * [Using ``](#xsd-schemas-context-ac)
- * [Using ``](#xsd-schemas-context-component-scan)
- * [Using ``](#xsd-schemas-context-ltw)
- * [Using ``](#xsd-schemas-context-sc)
- * [Using ``](#xsd-schemas-context-mbe)
-
- * [10.1.4. The Beans Schema](#xsd-schemas-beans)
-
- * [10.2. XML Schema Authoring](#xml-custom)
- * [10.2.1. Authoring the Schema](#xsd-custom-schema)
- * [10.2.2. Coding a `NamespaceHandler`](#xsd-custom-namespacehandler)
- * [10.2.3. Using `BeanDefinitionParser`](#xsd-custom-parser)
- * [10.2.4. Registering the Handler and the Schema](#xsd-custom-registration)
- * [Writing `META-INF/spring.handlers`](#xsd-custom-registration-spring-handlers)
- * [Writing 'META-INF/spring.schemas'](#xsd-custom-registration-spring-schemas)
-
- * [10.2.5. Using a Custom Extension in Your Spring XML Configuration](#xsd-custom-using)
- * [10.2.6. More Detailed Examples](#xsd-custom-meat)
- * [Nesting Custom Elements within Custom Elements](#xsd-custom-custom-nested)
- * [Custom Attributes on “Normal” Elements](#xsd-custom-custom-just-attributes)
-
- * [10.3. Application Startup Steps](#application-startup-steps)
+# Core Technologies
This part of the reference documentation covers all the technologies that are
absolutely integral to the Spring Framework.
@@ -465,12 +14,11 @@ Coverage of Spring’s integration with AspectJ (currently the richest — i
features — and certainly most mature AOP implementation in the Java enterprise space)
is also provided.
-[](#beans)1. The IoC Container
-----------
+## 1. The IoC Container
This chapter covers Spring’s Inversion of Control (IoC) container.
-### [](#beans-introduction)1.1. Introduction to the Spring IoC Container and Beans ###
+### 1.1. Introduction to the Spring IoC Container and Beans
This chapter covers the Spring Framework implementation of the Inversion of Control
(IoC) principle. IoC is also known as dependency injection (DI). It is a process whereby
@@ -506,7 +54,7 @@ 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.
-### [](#beans-basics)1.2. Container Overview ###
+### 1.2. Container Overview
The `org.springframework.context.ApplicationContext` interface represents the Spring IoC
container and is responsible for instantiating, configuring, and assembling the
@@ -540,7 +88,7 @@ application.
Figure 1. The Spring IoC container
-#### [](#beans-factory-metadata)1.2.1. Configuration Metadata ####
+#### 1.2.1. Configuration Metadata
As the preceding diagram shows, the Spring IoC container consumes a form of
configuration metadata. This configuration metadata represents how you, as an
@@ -608,7 +156,7 @@ The following example shows the basic structure of XML-based configuration metad
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](#beans-dependencies) for more information.
-#### [](#beans-factory-instantiation)1.2.2. Instantiating a Container ####
+#### 1.2.2. Instantiating a Container
The location path or paths
supplied to an `ApplicationContext` constructor are resource strings that let
@@ -682,7 +230,7 @@ name of the JavaBean property, and the `ref` element refers to the name of anoth
definition. This linkage between `id` and `ref` elements expresses the dependency between
collaborating objects. For details of configuring an object’s dependencies, see[Dependencies](#beans-dependencies).
-##### [](#beans-factory-xml-import)Composing XML-based Configuration Metadata #####
+##### Composing XML-based Configuration Metadata
It can be useful to have bean definitions span multiple XML files. Often, each individual
XML configuration file represents a logical layer or module in your architecture.
@@ -718,7 +266,7 @@ The namespace itself provides the import directive feature. Further
configuration features beyond plain bean definitions are available in a selection
of XML namespaces provided by Spring — for example, the `context` and `util` namespaces.
-##### [](#groovy-bean-definition-dsl)The Groovy Bean Definition DSL #####
+##### The Groovy Bean Definition DSL
As a further example for externalized configuration metadata, bean definitions can also
be expressed in Spring’s Groovy Bean Definition DSL, as known from the Grails framework.
@@ -749,7 +297,7 @@ 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.
-#### [](#beans-factory-client)1.2.3. Using the Container ####
+#### 1.2.3. Using the Container
The `ApplicationContext` is the interface for an advanced factory capable of maintaining
a registry of different beans and their dependencies. By using the method`T getBean(String name, Class requiredType)`, you can retrieve instances of your beans.
@@ -849,7 +397,7 @@ Spring’s integration with web frameworks provides dependency injection for var
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).
-### [](#beans-definition)1.3. Bean Overview ###
+### 1.3. Bean Overview
A Spring IoC container manages one or more beans. These beans are created with the
configuration metadata that you supply to the container (for example, in the form of XML`` definitions).
@@ -894,7 +442,7 @@ defined through regular bean definition metadata.
| |Bean metadata and manually supplied singleton instances need to be registered as early as possible, in order for the container to properly reason about them during autowiring and other introspection steps. While overriding existing metadata and existing singleton instances is supported to some degree, the registration of new beans at runtime (concurrently with live access to the factory) is not officially supported and may lead to concurrent access exceptions, inconsistent state in the bean container, or both.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-beanname)1.3.1. Naming Beans ####
+#### 1.3.1. Naming Beans
Every bean has one or more identifiers. These identifiers must be unique within the
container that hosts the bean. A bean usually has only one identifier. However, if it
@@ -929,7 +477,7 @@ related by name.
| |With component scanning in the classpath, Spring generates bean names for unnamed components, following the rules described earlier: essentially, taking the simple class name and turning its initial character to lower-case. However, in the (unusual) special case when there is more than one character and both the first and second characters are upper case, the original casing gets preserved. These are the same rules as defined by `java.beans.Introspector.decapitalize` (which Spring uses here).|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-beanname-alias)Aliasing a Bean outside the Bean Definition #####
+##### Aliasing a Bean outside the Bean Definition
In a bean definition itself, you can supply more than one name for the bean, by using a
combination of up to one name specified by the `id` attribute and any number of other
@@ -973,7 +521,7 @@ Java-configuration
If you use Javaconfiguration, the `@Bean` annotation can be used to provide aliases.
See [Using the `@Bean` Annotation](#beans-java-bean-annotation) for details.
-#### [](#beans-factory-class)1.3.2. Instantiating Beans ####
+#### 1.3.2. Instantiating Beans
A bean definition is essentially a recipe for creating one or more objects. The
container looks at the recipe for a named bean when asked and uses the configuration
@@ -1002,7 +550,7 @@ this `SomeThing` class has a `static` nested class called `OtherThing`, they can
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`.
-##### [](#beans-factory-class-ctor)Instantiation with a Constructor #####
+##### Instantiation with a Constructor
When you create a bean by the constructor approach, all normal classes are usable by and
compatible with Spring. That is, the class being developed does not need to implement
@@ -1029,7 +577,7 @@ With XML-based configuration metadata you can specify your bean class as follows
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](#beans-factory-collaborators).
-##### [](#beans-factory-class-static-factory-method)Instantiation with a Static Factory Method #####
+##### Instantiation with a Static Factory Method
When defining a bean that you create with a static factory method, use the `class`attribute to specify the class that contains the `static` factory method and an attribute
named `factory-method` to specify the name of the factory method itself. You should be
@@ -1077,7 +625,7 @@ For details about the mechanism for supplying (optional) arguments to the factor
and setting object instance properties after the object is returned from the factory,
see [Dependencies and Configuration in Detail](#beans-factory-properties-detailed).
-##### [](#beans-factory-class-instance-factory-method)Instantiation by Using an Instance Factory Method #####
+##### Instantiation by Using an Instance Factory Method
Similar to instantiation through a [static
factory method](#beans-factory-class-static-factory-method), instantiation with an instance factory method invokes a non-static
@@ -1191,7 +739,7 @@ Configuration in Detail](#beans-factory-properties-detailed).
| |In Spring documentation, "factory bean" refers to a bean that is configured in the Spring container and that creates objects through an[instance](#beans-factory-class-instance-factory-method) or[static](#beans-factory-class-static-factory-method) factory method. By contrast,`FactoryBean` (notice the capitalization) refers to a Spring-specific[`FactoryBean`](#beans-factory-extension-factorybean) implementation class.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-factory-type-determination)Determining a Bean’s Runtime Type #####
+##### Determining a Bean’s Runtime Type
The runtime type of a specific bean is non-trivial to determine. A specified class in
the bean metadata definition is just an initial class reference, potentially combined
@@ -1206,7 +754,7 @@ a `BeanFactory.getType` call for the specified bean name. This takes all of the
cases into account and returns the type of object that a `BeanFactory.getBean` call is
going to return for the same bean name.
-### [](#beans-dependencies)1.4. Dependencies ###
+### 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
@@ -1214,7 +762,7 @@ present what the end-user sees as a coherent application. This next section expl
you go from defining a number of bean definitions that stand alone to a fully realized
application where objects collaborate to achieve a goal.
-#### [](#beans-factory-collaborators)1.4.1. Dependency Injection ####
+#### 1.4.1. Dependency Injection
Dependency injection (DI) is a process whereby objects define their dependencies
(that is, the other objects with which they work) only through constructor arguments,
@@ -1234,7 +782,7 @@ which allow for stub or mock implementations to be used in unit tests.
DI exists in two major variants: [Constructor-based
dependency injection](#beans-constructor-injection) and [Setter-based dependency injection](#beans-setter-injection).
-##### [](#beans-constructor-injection)Constructor-based Dependency Injection #####
+##### Constructor-based Dependency Injection
Constructor-based DI is accomplished by the container invoking a constructor with a
number of arguments, each representing a dependency. Calling a `static` factory method
@@ -1272,7 +820,7 @@ class SimpleMovieLister(private val 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.
-###### [](#beans-factory-ctor-arguments-resolution)Constructor Argument Resolution ######
+###### Constructor Argument Resolution
Constructor argument resolution matching occurs by using the argument’s type. If no
potential ambiguity exists in the constructor arguments of a bean definition, the
@@ -1428,7 +976,7 @@ class ExampleBean
constructor(val years: Int, val ultimateAnswer: String)
```
-##### [](#beans-setter-injection)Setter-based Dependency Injection #####
+##### Setter-based Dependency Injection
Setter-based DI is accomplished by the container calling setter methods on your
beans after invoking a no-argument constructor or a no-argument `static` factory method to
@@ -1502,7 +1050,7 @@ with third-party classes for which you do not have the source, the choice is mad
For example, if a third-party class does not expose any setter methods, then constructor
injection may be the only available form of DI.
-##### [](#beans-dependency-resolution)Dependency Resolution Process #####
+##### Dependency Resolution Process
The container performs bean dependency resolution as follows:
@@ -1573,7 +1121,7 @@ pre-instantiated singleton), its dependencies are set, and the relevant lifecycl
methods (such as a [configured init method](#beans-factory-lifecycle-initializingbean)or the [InitializingBean callback method](#beans-factory-lifecycle-initializingbean))
are invoked.
-##### [](#beans-some-examples)Examples of Dependency Injection #####
+##### Examples of Dependency Injection
The following example uses XML-based configuration metadata for setter-based DI. A small
part of a Spring XML configuration file specifies some bean definitions as follows:
@@ -1749,7 +1297,7 @@ contains the `static` factory method (although, in this example, it is). An inst
from the use of the `factory-bean` attribute instead of the `class` attribute), so we
do not discuss those details here.
-#### [](#beans-factory-properties-detailed)1.4.2. Dependencies and Configuration in Detail ####
+#### 1.4.2. Dependencies and Configuration in Detail
As mentioned in the [previous section](#beans-factory-collaborators), you can define bean
properties and constructor arguments as references to other managed beans (collaborators)
@@ -1757,7 +1305,7 @@ or as values defined inline. Spring’s XML-based configuration metadata support
sub-element types within its `` and `` elements for this
purpose.
-##### [](#beans-value-element)Straight Values (Primitives, Strings, and so on) #####
+##### Straight Values (Primitives, Strings, and so on)
The `value` attribute of the `` element specifies a property or constructor
argument as a human-readable string representation. Spring’s[conversion service](#core-convert-ConversionService-API) is used to convert these
@@ -1820,7 +1368,7 @@ The Spring container converts the text inside the `` element into a`java
is a nice shortcut, and is one of a few places where the Spring team do favor the use of
the nested `` element over the `value` attribute style.
-###### [](#beans-idref-element)The `idref` element ######
+###### The `idref` element
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 `` or ``element. The following example shows how to use it:
@@ -1860,7 +1408,7 @@ A common place (at least in versions earlier than Spring 2.0) where the `` elements when you specify the
interceptor names prevents you from misspelling an interceptor ID.
-##### [](#beans-ref-element)References to Other Beans (Collaborators) #####
+##### References to Other Beans (Collaborators)
The `ref` element is the final element inside a `` or ``definition element. Here, you set the value of the specified property of a bean to be a
reference to another bean (a collaborator) managed by the container. The referenced bean
@@ -1909,7 +1457,7 @@ listings shows how to use the `parent` attribute:
| |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.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-inner-beans)Inner Beans #####
+##### Inner Beans
A `` element inside the `` or `` elements defines an
inner bean, as the following example shows:
@@ -1937,7 +1485,7 @@ of the inner bean instance is tied to its containing bean, but destruction callb
participate in the request scope’s lifecycle. This is not a common scenario. Inner beans
typically simply share their containing bean’s scope.
-##### [](#beans-collection-elements)Collections #####
+##### Collections
The ``, ``, ``, and `` elements set the properties
and arguments of the Java `Collection` types `List`, `Set`, `Map`, and `Properties`,
@@ -1984,7 +1532,7 @@ following elements:
bean | ref | idref | list | set | map | props | value | null
```
-###### [](#beans-collection-elements-merging)Collection Merging ######
+###### Collection Merging
The Spring container also supports merging collections. An application
developer can define a parent ``, ``, `` or `` element
@@ -2041,14 +1589,14 @@ exists. Hence, no ordering semantics are in effect for the collection types that
the associated `Map`, `Set`, and `Properties` implementation types that the container
uses internally.
-###### [](#beans-collection-merge-limitations)Limitations of Collection Merging ######
+###### Limitations of Collection Merging
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.
-###### [](#beans-collection-elements-strongly-typed)Strongly-typed collection ######
+###### Strongly-typed collection
With the introduction of generic types in Java 5, you can use strongly typed collections.
That is, it is possible to declare a `Collection` type such that it can only contain
@@ -2097,7 +1645,7 @@ information about the element type of the strongly-typed `Map` 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.
-##### [](#beans-null-element)Null and Empty String Values #####
+##### Null and Empty String Values
Spring treats empty arguments for properties and the like as empty `Strings`. The
following XML-based configuration metadata snippet sets the `email` property to the empty`String` value ("").
@@ -2146,7 +1694,7 @@ Kotlin
exampleBean.email = null
```
-##### [](#beans-p-namespace)XML Shortcut with the p-namespace #####
+##### XML Shortcut with the p-namespace
The p-namespace lets you use the `bean` element’s attributes (instead of nested`` elements) to describe your property values collaborating beans, or both.
@@ -2215,7 +1763,7 @@ 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.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-c-namespace)XML Shortcut with the c-namespace #####
+##### XML Shortcut with the c-namespace
Similar to the [XML Shortcut with the p-namespace](#beans-p-namespace), the c-namespace, introduced in Spring
3.1, allows inlined attributes for configuring the constructor arguments rather
@@ -2269,7 +1817,7 @@ In practice, the constructor resolution[mechanism](#beans-factory-ctor-arguments
arguments, so unless you really need to, we recommend using the name notation
throughout your configuration.
-##### [](#beans-compound-property-names)Compound Property Names #####
+##### Compound Property Names
You can use compound or nested property names when you set bean properties, as long as
all components of the path except the final property name are not `null`. Consider the
@@ -2285,7 +1833,7 @@ The `something` bean has a `fred` property, which has a `bob` property, which ha
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.
-#### [](#beans-factory-dependson)1.4.3. Using `depends-on` ####
+#### 1.4.3. Using `depends-on`
If a bean is a dependency of another bean, that usually means that one bean is set as a
property of another. Typically you accomplish this with the [``element](#beans-ref-element) in XML-based configuration metadata. However, sometimes dependencies between
@@ -2316,7 +1864,7 @@ delimiters):
| |The `depends-on` attribute can specify both an initialization-time dependency and, in the case of [singleton](#beans-factory-scopes-singleton) beans only, a corresponding destruction-time dependency. Dependent beans that define a `depends-on` relationship with a given bean are destroyed first, prior to the given bean itself being destroyed. Thus, `depends-on` can also control shutdown order.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-factory-lazy-init)1.4.4. Lazy-initialized Beans ####
+#### 1.4.4. Lazy-initialized Beans
By default, `ApplicationContext` implementations eagerly create and configure all[singleton](#beans-factory-scopes-singleton) beans as part of the initialization
process. Generally, this pre-instantiation is desirable, because errors in the
@@ -2350,7 +1898,7 @@ You can also control lazy-initialization at the container level by using the`def
```
-#### [](#beans-factory-autowire)1.4.5. Autowiring Collaborators ####
+#### 1.4.5. Autowiring Collaborators
The Spring container can autowire relationships between collaborating beans. You can
let Spring resolve collaborators (other beans) automatically for your bean by
@@ -2384,7 +1932,7 @@ typed collections. In such cases, all autowire candidates within the container t
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.
-##### [](#beans-autowired-exceptions)Limitations and Disadvantages of Autowiring #####
+##### Limitations and Disadvantages of Autowiring
Autowiring works best when it is used consistently across a project. If autowiring is
not used in general, it might be confusing to developers to use it to wire only one or
@@ -2421,7 +1969,7 @@ In the latter scenario, you have several options:
* Implement the more fine-grained control available with annotation-based configuration,
as described in [Annotation-based Container Configuration](#beans-annotation-config).
-##### [](#beans-factory-autowire-candidate)Excluding a Bean from Autowiring #####
+##### Excluding a Bean from Autowiring
On a per-bean basis, you can exclude a bean from autowiring. In Spring’s XML format, set
the `autowire-candidate` attribute of the `` element to `false`. The container
@@ -2441,7 +1989,7 @@ These techniques are useful for beans that you never want to be injected into ot
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.
-#### [](#beans-factory-method-injection)1.4.6. Method Injection ####
+#### 1.4.6. Method Injection
In most application scenarios, most beans in the container are[singletons](#beans-factory-scopes-singleton). When a singleton bean needs to
collaborate with another singleton bean or a non-singleton bean needs to collaborate
@@ -2531,7 +2079,7 @@ container, lets you handle this use case cleanly.
You can read more about the motivation for Method Injection in[this blog entry](https://spring.io/blog/2004/08/06/method-injection/).
-##### [](#beans-factory-lookup-method-injection)Lookup Method Injection #####
+##### Lookup Method Injection
Lookup method injection is the ability of the container to override methods on
container-managed beans and return the lookup result for another named bean in the
@@ -2697,7 +2245,7 @@ apply to explicitly registered or explicitly imported bean classes.
| |Another way of accessing differently scoped target beans is an `ObjectFactory`/`Provider` injection point. See [Scoped Beans as Dependencies](#beans-factory-scopes-other-injection).
You may also find the `ServiceLocatorFactoryBean` (in the`org.springframework.beans.factory.config` package) to be useful.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-factory-arbitrary-method-replacement)Arbitrary Method Replacement #####
+##### Arbitrary Method Replacement
A less useful form of method injection than lookup method injection is the ability to
replace arbitrary methods in a managed bean with another method implementation. You
@@ -2800,7 +2348,7 @@ Because the number of arguments is often enough to distinguish between each poss
choice, this shortcut can save a lot of typing, by letting you type only the
shortest string that matches an argument type.
-### [](#beans-factory-scopes)1.5. Bean Scopes ###
+### 1.5. Bean Scopes
When you create a bean definition, you create a recipe for creating actual instances
of the class defined by that bean definition. The idea that a bean definition is a
@@ -2830,7 +2378,7 @@ The following table describes the supported scopes:
| |As of Spring 3.0, a thread scope is available but is not registered by default. For more information, see the documentation for[`SimpleThreadScope`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/support/SimpleThreadScope.html). For instructions on how to register this or any other custom scope, see[Using a Custom Scope](#beans-factory-scopes-custom-using).|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-factory-scopes-singleton)1.5.1. The Singleton Scope ####
+#### 1.5.1. The Singleton Scope
Only one shared instance of a singleton bean is managed, and all requests for beans
with an ID or IDs that match that bean definition result in that one specific bean
@@ -2861,7 +2409,7 @@ following example:
```
-#### [](#beans-factory-scopes-prototype)1.5.2. The Prototype Scope ####
+#### 1.5.2. The Prototype Scope
The non-singleton prototype scope of bean deployment results in the creation of a new
bean instance every time a request for that specific bean is made. That is, the bean
@@ -2900,7 +2448,7 @@ replacement for the Java `new` operator. All lifecycle management past that poin
be handled by the client. (For details on the lifecycle of a bean in the Spring
container, see [Lifecycle Callbacks](#beans-factory-lifecycle).)
-#### [](#beans-factory-scopes-sing-prot-interaction)1.5.3. Singleton Beans with Prototype-bean Dependencies ####
+#### 1.5.3. Singleton Beans with Prototype-bean Dependencies
When you use singleton-scoped beans with dependencies on prototype beans, be aware that
dependencies are resolved at instantiation time. Thus, if you dependency-inject a
@@ -2915,14 +2463,14 @@ 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](#beans-factory-method-injection).
-#### [](#beans-factory-scopes-other)1.5.4. Request, Session, Application, and WebSocket Scopes ####
+#### 1.5.4. Request, Session, Application, and WebSocket Scopes
The `request`, `session`, `application`, and `websocket` scopes are available only
if you use a web-aware Spring `ApplicationContext` implementation (such as`XmlWebApplicationContext`). If you use these scopes with regular Spring IoC containers,
such as the `ClassPathXmlApplicationContext`, an `IllegalStateException` that complains
about an unknown bean scope is thrown.
-##### [](#beans-factory-scopes-other-web-configuration)Initial Web Configuration #####
+##### Initial Web Configuration
To support the scoping of beans at the `request`, `session`, `application`, and`websocket` levels (web-scoped beans), some minor initial configuration is
required before you define your beans. (This initial setup is not required
@@ -2973,7 +2521,7 @@ the same thing, namely bind the HTTP request object to the `Thread` that is serv
that request. This makes beans that are request- and session-scoped available further
down the call chain.
-##### [](#beans-factory-scopes-request)Request scope #####
+##### Request scope
Consider the following XML configuration for a bean definition:
@@ -3011,7 +2559,7 @@ class LoginAction {
}
```
-##### [](#beans-factory-scopes-session)Session Scope #####
+##### Session Scope
Consider the following XML configuration for a bean definition:
@@ -3049,7 +2597,7 @@ class UserPreferences {
}
```
-##### [](#beans-factory-scopes-application)Application Scope #####
+##### Application Scope
Consider the following XML configuration for a bean definition:
@@ -3084,12 +2632,12 @@ class AppPreferences {
}
```
-##### [](#beans-factory-scopes-websocket)WebSocket Scope #####
+##### WebSocket Scope
WebSocket scope is associated with the lifecycle of a WebSocket session and applies to
STOMP over WebSocket applications, see[WebSocket scope](web.html#websocket-stomp-websocket-scope) for more details.
-##### [](#beans-factory-scopes-other-injection)Scoped Beans as Dependencies #####
+##### Scoped Beans as Dependencies
The Spring IoC container manages not only the instantiation of your objects (beans),
but also the wiring up of collaborators (or dependencies). If you want to inject (for
@@ -3176,7 +2724,7 @@ shows:
```
-###### [](#beans-factory-scopes-other-injection-proxies)Choosing the Type of Proxy to Create ######
+###### Choosing the Type of Proxy to Create
By default, when the Spring container creates a proxy for a bean that is marked up with
the `` element, a CGLIB-based class proxy is created.
@@ -3207,13 +2755,13 @@ interfaces. The following example shows a proxy based on an interface:
For more detailed information about choosing class-based or interface-based proxying,
see [Proxying Mechanisms](#aop-proxying).
-#### [](#beans-factory-scopes-custom)1.5.5. Custom Scopes ####
+#### 1.5.5. Custom Scopes
The bean scoping mechanism is extensible. You can define your own
scopes or even redefine existing scopes, although the latter is considered bad practice
and you cannot override the built-in `singleton` and `prototype` scopes.
-##### [](#beans-factory-scopes-custom-creating)Creating a Custom Scope #####
+##### Creating a Custom Scope
To integrate your custom scopes into the Spring container, you need to implement the`org.springframework.beans.factory.config.Scope` interface, which is described in this
section. For an idea of how to implement your own scopes, see the `Scope`implementations that are supplied with the Spring Framework itself and the[`Scope`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/beans/factory/config/Scope.html) javadoc,
@@ -3290,7 +2838,7 @@ fun getConversationId(): String
This identifier is different for each scope. For a session scoped implementation, this
identifier can be the session identifier.
-##### [](#beans-factory-scopes-custom-using)Using a Custom Scope #####
+##### Using a Custom Scope
After you write and test one or more custom `Scope` implementations, you need to make
the Spring container aware of your new scopes. The following method is the central
@@ -3379,7 +2927,7 @@ of the scope. You can also do the `Scope` registration declaratively, by using t
| |When you place `` within a `` declaration for a`FactoryBean` implementation, it is the factory bean itself that is scoped, not the object returned from `getObject()`.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#beans-factory-nature)1.6. Customizing the Nature of a Bean ###
+### 1.6. Customizing the Nature of a Bean
The Spring Framework provides a number of interfaces you can use to customize the nature
of a bean. This section groups them as follows:
@@ -3390,7 +2938,7 @@ of a bean. This section groups them as follows:
* [Other `Aware` Interfaces](#aware-list)
-#### [](#beans-factory-lifecycle)1.6.1. Lifecycle Callbacks ####
+#### 1.6.1. Lifecycle Callbacks
To interact with the container’s management of the bean lifecycle, you can implement
the Spring `InitializingBean` and `DisposableBean` interfaces. The container calls`afterPropertiesSet()` for the former and `destroy()` for the latter to let the bean
@@ -3410,7 +2958,7 @@ startup and shutdown process, as driven by the container’s own lifecycle.
The lifecycle callback interfaces are described in this section.
-##### [](#beans-factory-lifecycle-initializingbean)Initialization Callbacks #####
+##### 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
@@ -3485,7 +3033,7 @@ class AnotherExampleBean : InitializingBean {
However, the first of the two preceding examples does not couple the code to Spring.
-##### [](#beans-factory-lifecycle-disposablebean)Destruction Callbacks #####
+##### 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:
@@ -3561,7 +3109,7 @@ However, the first of the two preceding definitions does not couple the code to
| |You can assign the `destroy-method` attribute of a `` element a special`(inferred)` value, which instructs Spring to automatically detect a public `close` or`shutdown` method on the specific bean class. (Any class that implements`java.lang.AutoCloseable` or `java.io.Closeable` would therefore match.) You can also set this special `(inferred)` value on the `default-destroy-method` attribute of a`` element to apply this behavior to an entire set of beans (see[Default Initialization and Destroy Methods](#beans-factory-lifecycle-default-init-destroy-methods)). Note that this is the default behavior with Java configuration.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-factory-lifecycle-default-init-destroy-methods)Default Initialization and Destroy Methods #####
+##### Default Initialization and Destroy Methods
When you write initialization and destroy method callbacks that do not use the
Spring-specific `InitializingBean` and `DisposableBean` callback interfaces, you
@@ -3650,7 +3198,7 @@ interceptors to the `init` method, because doing so would couple the lifecycle o
target bean to its proxy or interceptors and leave strange semantics when your code
interacts directly with the raw target bean.
-##### [](#beans-factory-lifecycle-combined-effects)Combining Lifecycle Mechanisms #####
+##### Combining Lifecycle Mechanisms
As of Spring 2.5, you have three options for controlling bean lifecycle behavior:
@@ -3680,7 +3228,7 @@ Destroy methods are called in the same order:
3. A custom configured `destroy()` method
-##### [](#beans-factory-lifecycle-processor)Startup and Shutdown Callbacks #####
+##### Startup and Shutdown Callbacks
The `Lifecycle` interface defines the essential methods for any object that has its own
lifecycle requirements (such as starting and stopping some background process):
@@ -3776,7 +3324,7 @@ its own `start()` method (unlike the context refresh, the context start does not
automatically for a standard context implementation). The `phase` value and any
“depends-on” relationships determine the startup order as described earlier.
-##### [](#beans-factory-shutdown)Shutting Down the Spring IoC Container Gracefully in Non-Web Applications #####
+##### Shutting Down the Spring IoC Container Gracefully in Non-Web Applications
| |This section applies only to non-web applications. Spring’s web-based`ApplicationContext` implementations already have code in place to gracefully shut down the Spring IoC container when the relevant web application is shut down.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
@@ -3828,7 +3376,7 @@ fun main() {
}
```
-#### [](#beans-factory-aware)1.6.2. `ApplicationContextAware` and `BeanNameAware` ####
+#### 1.6.2. `ApplicationContextAware` and `BeanNameAware`
When an `ApplicationContext` creates an object instance that implements the`org.springframework.context.ApplicationContextAware` interface, the instance is provided
with a reference to that `ApplicationContext`. The following listing shows the definition
@@ -3873,7 +3421,7 @@ The callback is invoked after population of normal bean properties but before an
initialization callback such as `InitializingBean.afterPropertiesSet()` or a custom
init-method.
-#### [](#aware-list)1.6.3. Other `Aware` Interfaces ####
+#### 1.6.3. Other `Aware` Interfaces
Besides `ApplicationContextAware` and `BeanNameAware` (discussed [earlier](#beans-factory-aware)),
Spring offers a wide range of `Aware` callback interfaces that let beans indicate to the container
@@ -3898,7 +3446,7 @@ Note again that using these interfaces ties your code to the Spring API and does
follow the Inversion of Control style. As a result, we recommend them for infrastructure
beans that require programmatic access to the container.
-### [](#beans-child-bean-definitions)1.7. Bean Definition Inheritance ###
+### 1.7. Bean Definition Inheritance
A bean definition can contain a lot of configuration information, including constructor
arguments, property values, and container-specific information, such as the initialization
@@ -3974,13 +3522,13 @@ abstract.
| |`ApplicationContext` pre-instantiates all singletons by default. Therefore, it is important (at least for singleton beans) that if you have a (parent) bean definition which 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 will actually (attempt to) pre-instantiate the `abstract` bean.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#beans-factory-extension)1.8. Container Extension Points ###
+### 1.8. Container Extension Points
Typically, an application developer does not need to subclass `ApplicationContext`implementation classes. Instead, the Spring IoC container can be extended by plugging in
implementations of special integration interfaces. The next few sections describe these
integration interfaces.
-#### [](#beans-factory-extension-bpp)1.8.1. Customizing Beans by Using a `BeanPostProcessor` ####
+#### 1.8.1. Customizing Beans by Using a `BeanPostProcessor`
The `BeanPostProcessor` interface defines callback methods that you can implement to
provide your own (or override the container’s default) instantiation logic, dependency
@@ -4029,7 +3577,7 @@ initialization of other beans in the context, this early type detection is criti
The following examples show how to write, register, and use `BeanPostProcessor` instances
in an `ApplicationContext`.
-##### [](#beans-factory-extension-bpp-examples-hw)Example: Hello World, `BeanPostProcessor`-style #####
+##### Example: Hello World, `BeanPostProcessor`-style
This first example illustrates basic usage. The example shows a custom`BeanPostProcessor` implementation that invokes the `toString()` method of each bean as
it is created by the container and prints the resulting string to the system console.
@@ -4146,14 +3694,14 @@ Bean 'messenger' created : [email protected]
[email protected]
```
-##### [](#beans-factory-extension-bpp-examples-aabpp)Example: The `AutowiredAnnotationBeanPostProcessor` #####
+##### Example: The `AutowiredAnnotationBeanPostProcessor`
Using callback interfaces or annotations in conjunction with a custom `BeanPostProcessor`implementation is a common means of extending the Spring IoC container. An example is
Spring’s `AutowiredAnnotationBeanPostProcessor` — a `BeanPostProcessor` implementation
that ships with the Spring distribution and autowires annotated fields, setter methods,
and arbitrary config methods.
-#### [](#beans-factory-extension-factory-postprocessors)1.8.2. Customizing Configuration Metadata with a `BeanFactoryPostProcessor` ####
+#### 1.8.2. Customizing Configuration Metadata with a `BeanFactoryPostProcessor` ####
The next extension point that we look at is the`org.springframework.beans.factory.config.BeanFactoryPostProcessor`. The semantics of
this interface are similar to those of the `BeanPostProcessor`, with one major
@@ -4182,7 +3730,7 @@ you would any other bean.
| |As with `BeanPostProcessor`s , you typically do not want to configure`BeanFactoryPostProcessor`s for lazy initialization. If no other bean references a`Bean(Factory)PostProcessor`, that post-processor will not get instantiated at all. Thus, marking it for lazy initialization will be ignored, and the`Bean(Factory)PostProcessor` will be instantiated eagerly even if you set the`default-lazy-init` attribute to `true` on the declaration of your `` element.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-factory-placeholderconfigurer)Example: The Class Name Substitution `PropertySourcesPlaceholderConfigurer` #####
+##### Example: The Class Name Substitution `PropertySourcesPlaceholderConfigurer` #####
You can use the `PropertySourcesPlaceholderConfigurer` to externalize property values
from a bean definition in a separate file by using the standard Java `Properties` format.
@@ -4239,7 +3787,7 @@ it checks against Spring `Environment` properties and regular Java `System` prop
| |You can use the `PropertySourcesPlaceholderConfigurer` to substitute class names, which is sometimes useful when you have to pick a particular implementation class at runtime. The following example shows how to do so:
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.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-factory-overrideconfigurer)Example: The `PropertyOverrideConfigurer` #####
+##### Example: The `PropertyOverrideConfigurer`
The `PropertyOverrideConfigurer`, another bean factory post-processor, resembles the`PropertySourcesPlaceholderConfigurer`, but unlike the latter, the original definitions
can have default values or no values at all for bean properties. If an overriding`Properties` file does not have an entry for a certain bean property, the default
@@ -4284,7 +3832,7 @@ property overriding with a dedicated configuration element, as the following exa
```
-#### [](#beans-factory-extension-factorybean)1.8.3. Customizing Instantiation Logic with a `FactoryBean` ####
+#### 1.8.3. Customizing Instantiation Logic with a `FactoryBean`
You can implement the `org.springframework.beans.factory.FactoryBean` interface for objects that
are themselves factories.
@@ -4314,7 +3862,7 @@ the bean it produces, prefix the bean’s `id` with the ampersand symbol (`&`) w
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.
-### [](#beans-annotation-config)1.9. Annotation-based Container Configuration ###
+### 1.9. Annotation-based Container Configuration
Are annotations better than XML for configuring Spring?
@@ -4384,7 +3932,7 @@ The `` element implicitly registers the following po
| |`` only looks for annotations on beans in the same application context in which it is defined. This means that, if you put`` in a `WebApplicationContext` for a `DispatcherServlet`, it only checks for `@Autowired` beans in your controllers, and not your services. See[The DispatcherServlet](web.html#mvc-servlet) for more information.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-required-annotation)1.9.1. @Required ####
+#### 1.9.1. @Required
The `@Required` annotation applies to bean property setter methods, as in the following
example:
@@ -4430,7 +3978,7 @@ references and values even when you use the class outside of a container.
| |The `@Required` annotation and `RequiredAnnotationBeanPostProcessor` are formally deprecated as of Spring Framework 5.1, in favor of using constructor injection for required settings (or a custom implementation of `InitializingBean.afterPropertiesSet()`or a custom `@PostConstruct` method along with bean property setter methods).|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-autowired-annotation)1.9.2. Using `@Autowired` ####
+#### 1.9.2. Using `@Autowired`
| |JSR 330’s `@Inject` annotation can be used in place of Spring’s `@Autowired` annotation in the examples included in this section. See [here](#beans-standard-annotations) for more details.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
@@ -4798,7 +4346,7 @@ class MovieRecommender {
| |The `@Autowired`, `@Inject`, `@Value`, and `@Resource` annotations are handled by Spring`BeanPostProcessor` implementations. This means that you cannot apply these annotations within your own `BeanPostProcessor` or `BeanFactoryPostProcessor` types (if any). These types must be 'wired up' explicitly by using XML or a Spring `@Bean` method.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-autowired-annotation-primary)1.9.3. Fine-tuning Annotation-based Autowiring with `@Primary` ####
+#### 1.9.3. Fine-tuning Annotation-based Autowiring with `@Primary`
Because autowiring by type may lead to multiple candidates, it is often necessary to have
more control over the selection process. One way to accomplish this is with Spring’s`@Primary` annotation. `@Primary` indicates that a particular bean should be given
@@ -4896,7 +4444,7 @@ The corresponding bean definitions follow:
```
-#### [](#beans-autowired-annotation-qualifiers)1.9.4. Fine-tuning Annotation-based Autowiring with Qualifiers ####
+#### 1.9.4. Fine-tuning Annotation-based Autowiring with Qualifiers
`@Primary` is an effective way to use autowiring by type with several instances when one
primary candidate can be determined. When you need more control over the selection process,
@@ -5384,7 +4932,7 @@ the following example:
```
-#### [](#beans-generics-as-qualifiers)1.9.5. Using Generics as Autowiring Qualifiers ####
+#### 1.9.5. Using Generics as Autowiring Qualifiers
In addition to the `@Qualifier` annotation, you can use Java generic types
as an implicit form of qualification. For example, suppose you have the following
@@ -5466,7 +5014,7 @@ Kotlin
private lateinit var s: List>
```
-#### [](#beans-custom-autowire-configurer)1.9.6. Using `CustomAutowireConfigurer` ####
+#### 1.9.6. Using `CustomAutowireConfigurer`
[`CustomAutowireConfigurer`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/beans/factory/annotation/CustomAutowireConfigurer.html)is a `BeanFactoryPostProcessor` that lets you register your own custom qualifier
annotation types, even if they are not annotated with Spring’s `@Qualifier` annotation.
@@ -5495,7 +5043,7 @@ The `AutowireCandidateResolver` determines autowire candidates by:
When multiple beans qualify as autowire candidates, the determination of a “primary” is
as follows: If exactly one bean definition among the candidates has a `primary`attribute set to `true`, it is selected.
-#### [](#beans-resource-annotation)1.9.7. Injection with `@Resource` ####
+#### 1.9.7. Injection with `@Resource`
Spring also supports injection by using the JSR-250 `@Resource` annotation
(`javax.annotation.Resource`) on fields or bean property setter methods.
@@ -5615,7 +5163,7 @@ class MovieRecommender {
|**1**|The `context` field is injected based on the known resolvable dependency type:`ApplicationContext`.|
|-----|---------------------------------------------------------------------------------------------------|
-#### [](#beans-value-annotations)1.9.8. Using `@Value` ####
+#### 1.9.8. Using `@Value`
`@Value` is typically used to inject externalized properties:
@@ -5815,7 +5363,7 @@ class MovieRecommender(
@Value("#{{'Thriller': 100, 'Comedy': 300}}") private val countOfMoviesPerCatalog: Map)
```
-#### [](#beans-postconstruct-and-predestroy-annotations)1.9.9. Using `@PostConstruct` and `@PreDestroy` ####
+#### 1.9.9. Using `@PostConstruct` and `@PreDestroy`
The `CommonAnnotationBeanPostProcessor` not only recognizes the `@Resource` annotation
but also the JSR-250 lifecycle annotations: `javax.annotation.PostConstruct` and`javax.annotation.PreDestroy`. Introduced in Spring 2.5, the support for these
@@ -5864,7 +5412,7 @@ For details about the effects of combining various lifecycle mechanisms, see[Com
| |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 `javax.annotation-api` artifact needs to be obtained via Maven Central now, simply to be added to the application’s classpath like any other library.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#beans-classpath-scanning)1.10. Classpath Scanning and Managed Components ###
+### 1.10. Classpath Scanning and Managed Components
Most examples in this chapter use XML to specify the configuration metadata that produces
each `BeanDefinition` within the Spring container. The previous section
@@ -5882,7 +5430,7 @@ the container.
| |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.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-stereotype-annotations)1.10.1. `@Component` and Further Stereotype Annotations ####
+#### 1.10.1. `@Component` and Further Stereotype Annotations
The `@Repository` annotation is a marker for any class that fulfills the role or
stereotype of a repository (also known as Data Access Object or DAO). Among the uses
@@ -5898,7 +5446,7 @@ choosing between using `@Component` or `@Service` for your service layer, `@Serv
clearly the better choice. Similarly, as stated earlier, `@Repository` is already
supported as a marker for automatic exception translation in your persistence layer.
-#### [](#beans-meta-annotations)1.10.2. Using Meta-annotations and Composed Annotations ####
+#### 1.10.2. Using Meta-annotations and Composed Annotations
Many of the annotations provided by Spring can be used as meta-annotations in your
own code. A meta-annotation is an annotation that can be applied to another annotation.
@@ -6022,7 +5570,7 @@ class SessionScopedUserService : UserService {
For further details, see the[Spring Annotation Programming Model](https://github.com/spring-projects/spring-framework/wiki/Spring-Annotation-Programming-Model)wiki page.
-#### [](#beans-scanning-autodetection)1.10.3. Automatically Detecting Classes and Registering Bean Definitions ####
+#### 1.10.3. Automatically Detecting Classes and Registering Bean Definitions
Spring can automatically detect stereotyped classes and register corresponding`BeanDefinition` instances with the `ApplicationContext`. For example, the following two classes
are eligible for such autodetection:
@@ -6123,7 +5671,7 @@ wired together — all without any bean configuration metadata provided in X
| |You can disable the registration of `AutowiredAnnotationBeanPostProcessor` and`CommonAnnotationBeanPostProcessor` by including the `annotation-config` attribute with a value of `false`.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-scanning-filters)1.10.4. Using Filters to Customize Scanning ####
+#### 1.10.4. Using Filters to Customize Scanning
By default, classes annotated with `@Component`, `@Repository`, `@Service`, `@Controller`,`@Configuration`, or a custom annotation that itself is annotated with `@Component` are
the only detected candidate components. However, you can modify and extend this behavior
@@ -6183,7 +5731,7 @@ The following listing shows the equivalent XML:
| |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`` element. This effectively disables automatic detection of classes annotated or meta-annotated with `@Component`, `@Repository`, `@Service`, `@Controller`,`@RestController`, or `@Configuration`.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-factorybeans-annotations)1.10.5. Defining Bean Metadata within Components ####
+#### 1.10.5. Defining Bean Metadata within Components
Spring components can also contribute bean definition metadata to the container. You can do
this with the same `@Bean` annotation used to define bean metadata within `@Configuration`annotated classes. The following example shows how to do so:
@@ -6356,7 +5904,7 @@ constraints applying.
| |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 `@Bean` methods never get intercepted by the container, not even within`@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`.
`@Bean` methods are also discovered on base classes of a given component or configuration class, as well as on Java 8 default methods declared in interfaces implemented by the component or configuration class. This allows for a lot of flexibility in composing complex configuration arrangements, with even multiple inheritance being possible through Java 8 default methods as of Spring 4.2.
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.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-scanning-name-generator)1.10.6. Naming Autodetected Components ####
+#### 1.10.6. Naming Autodetected Components
When a component is autodetected as part of the scanning process, its bean name is
generated by the `BeanNameGenerator` strategy known to that scanner. By default, any
@@ -6443,7 +5991,7 @@ As a general rule, consider specifying the name with the annotation whenever oth
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.
-#### [](#beans-scanning-scope-resolver)1.10.7. Providing a Scope for Autodetected Components ####
+#### 1.10.7. Providing a Scope for Autodetected Components
As with Spring-managed components in general, the default and most common scope for
autodetected components is `singleton`. However, sometimes you need a different scope
@@ -6540,7 +6088,7 @@ class AppConfig {
```
-#### [](#beans-scanning-qualifiers)1.10.8. Providing Qualifier Metadata with Annotations ####
+#### 1.10.8. Providing Qualifier Metadata with Annotations
The `@Qualifier` annotation is discussed in [Fine-tuning Annotation-based Autowiring with Qualifiers](#beans-autowired-annotation-qualifiers).
The examples in that section demonstrate the use of the `@Qualifier` annotation and
@@ -6612,7 +6160,7 @@ class CachingMovieCatalog : MovieCatalog {
| |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.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-scanning-index)1.10.9. Generating an Index of Candidate Components ####
+#### 1.10.9. Generating an Index of Candidate Components
While classpath scanning is very fast, it is possible to improve the startup performance
of large applications by creating a static list of candidates at compilation time. In this
@@ -6661,7 +6209,7 @@ is included in the jar file.
| |The index is enabled automatically when a `META-INF/spring.components` file is found on the classpath. If an index is partially available for some libraries (or use cases) but could not be built for the whole application, you can fall back to a regular classpath arrangement (as though no index were present at all) by setting `spring.index.ignore` to`true`, either as a JVM system property or via the[`SpringProperties`](appendix.html#appendix-spring-properties) mechanism.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#beans-standard-annotations)1.11. Using JSR 330 Standard Annotations ###
+### 1.11. Using JSR 330 Standard Annotations
Starting with Spring 3.0, Spring offers support for JSR-330 standard annotations
(Dependency Injection). Those annotations are scanned in the same way as the Spring
@@ -6670,7 +6218,7 @@ annotations. To use them, you need to have the relevant jars in your classpath.
| |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/](https://repo1.maven.org/maven2/javax/inject/javax.inject/1/)). You can add the following dependency to your file pom.xml:
``` javax.inject javax.inject 1
```|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-inject-named)1.11.1. Dependency Injection with `@Inject` and `@Named` ####
+#### 1.11.1. Dependency Injection with `@Inject` and `@Named`
Instead of `@Autowired`, you can use `@javax.inject.Inject` as follows:
@@ -6832,7 +6380,7 @@ class SimpleMovieLister {
}
```
-#### [](#beans-named)1.11.2. `@Named` and `@ManagedBean`: Standard Equivalents to the `@Component` Annotation ####
+#### 1.11.2. `@Named` and `@ManagedBean`: Standard Equivalents to the `@Component` Annotation
Instead of `@Component`, you can use `@javax.inject.Named` or `javax.annotation.ManagedBean`,
as the following example shows:
@@ -6937,7 +6485,7 @@ class AppConfig {
| |In contrast to `@Component`, the JSR-330 `@Named` and the JSR-250 `@ManagedBean`annotations are not composable. You should use Spring’s stereotype model for building custom component annotations.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-standard-annotations-limitations)1.11.3. Limitations of JSR-330 Standard Annotations ####
+#### 1.11.3. Limitations of JSR-330 Standard Annotations
When you work with standard annotations, you should know that some significant
features are not available, as the following table shows:
@@ -6953,7 +6501,7 @@ features are not available, as the following table shows:
| @Lazy | \- | no equivalent |
| ObjectFactory | Provider | `javax.inject.Provider` is a direct alternative to Spring’s `ObjectFactory`, only with a shorter `get()` method name. It can also be used in combination with Spring’s `@Autowired` or with non-annotated constructors and setter methods. |
-### [](#beans-java)1.12. Java-based Container Configuration ###
+### 1.12. Java-based Container Configuration
This section covers how to use annotations in your Java code to configure the Spring
container. It includes the following topics:
@@ -6976,7 +6524,7 @@ container. It includes the following topics:
* [Placeholder Resolution in Statements](#beans-placeholder-resolution-in-statements)
-#### [](#beans-java-basic-concepts)1.12.1. Basic Concepts: `@Bean` and `@Configuration` ####
+#### 1.12.1. Basic Concepts: `@Bean` and `@Configuration`
The central artifacts in Spring’s new Java-configuration support are`@Configuration`-annotated classes and `@Bean`-annotated methods.
@@ -7049,7 +6597,7 @@ The `@Bean` and `@Configuration` annotations are discussed in depth in the follo
First, however, we cover the various ways of creating a spring container by using
Java-based configuration.
-#### [](#beans-java-instantiating-container)1.12.2. Instantiating the Spring Container by Using `AnnotationConfigApplicationContext` ####
+#### 1.12.2. Instantiating the Spring Container by Using `AnnotationConfigApplicationContext` ####
The following sections document Spring’s `AnnotationConfigApplicationContext`, introduced in Spring
3.0. This versatile `ApplicationContext` implementation is capable of accepting not only`@Configuration` classes as input but also plain `@Component` classes and classes
@@ -7063,7 +6611,7 @@ 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.
-##### [](#beans-java-instantiating-container-constructor)Simple Construction #####
+##### 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
@@ -7120,7 +6668,7 @@ fun main() {
The preceding example assumes that `MyServiceImpl`, `Dependency1`, and `Dependency2` use Spring
dependency injection annotations such as `@Autowired`.
-##### [](#beans-java-instantiating-container-register)Building the Container Programmatically by Using `register(Class>…)` #####
+##### Building the Container Programmatically by Using `register(Class>…)` #####
You can instantiate an `AnnotationConfigApplicationContext` by using a no-arg constructor
and then configure it by using the `register()` method. This approach is particularly useful
@@ -7155,7 +6703,7 @@ fun main() {
}
```
-##### [](#beans-java-instantiating-container-scan)Enabling Component Scanning with `scan(String…)` #####
+##### Enabling Component Scanning with `scan(String…)`
To enable component scanning, you can annotate your `@Configuration` class as follows:
@@ -7217,7 +6765,7 @@ fun main() {
| |Remember that `@Configuration` classes are [meta-annotated](#beans-meta-annotations)with `@Component`, so they are candidates for component-scanning. In the preceding example, assuming that `AppConfig` is declared within the `com.acme` package (or any package underneath), it is picked up during the call to `scan()`. Upon `refresh()`, all its `@Bean`methods are processed and registered as bean definitions within the container.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-java-instantiating-container-web)Support for Web Applications with `AnnotationConfigWebApplicationContext` #####
+##### Support for Web Applications with `AnnotationConfigWebApplicationContext` #####
A `WebApplicationContext` variant of `AnnotationConfigApplicationContext` is available
with `AnnotationConfigWebApplicationContext`. You can use this implementation when
@@ -7280,7 +6828,7 @@ init-param):
| |For programmatic use cases, a `GenericWebApplicationContext` can be used as an alternative to `AnnotationConfigWebApplicationContext`. See the[`GenericWebApplicationContext`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/context/support/GenericWebApplicationContext.html)javadoc for details.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-java-bean-annotation)1.12.3. Using the `@Bean` Annotation ####
+#### 1.12.3. Using the `@Bean` Annotation
`@Bean` is a method-level annotation and a direct analog of the XML `` element.
The annotation supports some of the attributes offered by ``, such as:
@@ -7295,7 +6843,7 @@ The annotation supports some of the attributes offered by ``, such as:
You can use the `@Bean` annotation in a `@Configuration`-annotated or in a`@Component`-annotated class.
-##### [](#beans-java-declaring-a-bean)Declaring a Bean #####
+##### 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
@@ -7401,7 +6949,7 @@ which resolves only once the `transferService` bean has been instantiated).
| |If you consistently refer to your types by a declared service interface, your`@Bean` return types may safely join that design decision. However, for components that implement several interfaces or for components potentially referred to by their implementation type, it is safer to declare the most specific return type possible (at least as specific as required by the injection points that refer to your bean).|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-java-dependencies)Bean Dependencies #####
+##### Bean Dependencies
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
@@ -7436,7 +6984,7 @@ class AppConfig {
The resolution mechanism is pretty much identical to constructor-based dependency
injection. See [the relevant section](#beans-constructor-injection) for more details.
-##### [](#beans-java-lifecycle-callbacks)Receiving Lifecycle Callbacks #####
+##### Receiving Lifecycle Callbacks
Any classes defined with the `@Bean` annotation support the regular lifecycle callbacks
and can use the `@PostConstruct` and `@PreDestroy` annotations from JSR-250. See[JSR-250 annotations](#beans-postconstruct-and-predestroy-annotations) for further
@@ -7552,11 +7100,11 @@ class AppConfig {
| |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.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-java-specifying-bean-scope)Specifying Bean Scope #####
+##### Specifying Bean Scope
Spring includes the `@Scope` annotation so that you can specify the scope of a bean.
-###### [](#beans-java-available-scopes)Using the `@Scope` Annotation ######
+###### Using the `@Scope` Annotation
You can specify that your beans defined with the `@Bean` annotation should have a
specific scope. You can use any of the standard scopes specified in the[Bean Scopes](#beans-factory-scopes) section.
@@ -7592,7 +7140,7 @@ class MyConfiguration {
}
```
-###### [](#beans-java-scoped-proxy)`@Scope` and `scoped-proxy` ######
+###### `@Scope` and `scoped-proxy`
Spring offers a convenient way of working with scoped dependencies through[scoped proxies](#beans-factory-scopes-other-injection). The easiest way to create
such a proxy when using the XML configuration is the `` element.
@@ -7640,7 +7188,7 @@ fun userService(): Service {
}
```
-##### [](#beans-java-customizing-bean-naming)Customizing Bean Naming #####
+##### Customizing Bean Naming
By default, configuration classes use a `@Bean` method’s name as the name of the
resulting bean. This functionality can be overridden, however, with the `name` attribute,
@@ -7670,7 +7218,7 @@ class AppConfig {
}
```
-##### [](#beans-java-bean-aliasing)Bean Aliasing #####
+##### Bean Aliasing
As discussed in [Naming Beans](#beans-beanname), 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
@@ -7702,7 +7250,7 @@ class AppConfig {
}
```
-##### [](#beans-java-bean-description)Bean Description #####
+##### 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.
@@ -7735,14 +7283,14 @@ class AppConfig {
}
```
-#### [](#beans-java-configuration-annotation)1.12.4. Using the `@Configuration` annotation ####
+#### 1.12.4. Using the `@Configuration` annotation
`@Configuration` is a class-level annotation indicating that an object is a source of
bean definitions. `@Configuration` classes declare beans through `@Bean`-annotated
methods. Calls to `@Bean` methods on `@Configuration` classes can also be used to define
inter-bean dependencies. See [Basic Concepts: `@Bean` and `@Configuration`](#beans-java-basic-concepts) for a general introduction.
-##### [](#beans-java-injecting-dependencies)Injecting Inter-bean Dependencies #####
+##### Injecting Inter-bean Dependencies
When beans have dependencies on one another, expressing that dependency is as simple
as having one bean method call another, as the following example shows:
@@ -7785,7 +7333,7 @@ injection.
| |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.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-java-method-injection)Lookup Method Injection #####
+##### Lookup Method Injection
As noted earlier, [lookup method injection](#beans-factory-method-injection) is an
advanced feature that you should use rarely. It is useful in cases where a
@@ -7877,7 +7425,7 @@ fun commandManager(): CommandManager {
}
```
-##### [](#beans-java-further-information-java-config)Further Information About How Java-based Configuration Works Internally #####
+##### Further Information About How Java-based Configuration Works Internally #####
Consider the following example, which shows a `@Bean` annotated method being called twice:
@@ -7952,12 +7500,12 @@ cached (scoped) beans before it calls the parent method and creates a new instan
| |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.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-java-composing-configuration-classes)1.12.5. Composing Java-based Configurations ####
+#### 1.12.5. Composing Java-based Configurations
Spring’s Java-based configuration feature lets you compose annotations, which can reduce
the complexity of your configuration.
-##### [](#beans-java-using-import)Using the `@Import` Annotation #####
+##### Using the `@Import` Annotation
Much as the `` element is used within Spring XML files to aid in modularizing
configurations, the `@Import` annotation allows for loading `@Bean` definitions from
@@ -8041,7 +7589,7 @@ with, rather than requiring you to remember a potentially large number of`@Confi
| |As of Spring Framework 4.2, `@Import` also supports references to regular component classes, analogous to the `AnnotationConfigApplicationContext.register` method. This is particularly useful if you want to avoid component scanning, by using a few configuration classes as entry points to explicitly define all your components.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-###### [](#beans-java-injecting-imported-beans)Injecting Dependencies on Imported `@Bean` Definitions ######
+###### Injecting Dependencies on Imported `@Bean` Definitions
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
@@ -8398,7 +7946,7 @@ than the usual process of navigating interface-based code.
| |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).|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-java-conditional)Conditionally Include `@Configuration` Classes or `@Bean` Methods #####
+##### Conditionally Include `@Configuration` Classes or `@Bean` Methods
It is often useful to conditionally enable or disable a complete `@Configuration` class
or even individual `@Bean` methods, based on some arbitrary system state. One common
@@ -8451,7 +7999,7 @@ override fun matches(context: ConditionContext, metadata: AnnotatedTypeMetadata)
See the [`@Conditional`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Conditional.html)javadoc for more detail.
-##### [](#beans-java-combining)Combining Java and XML Configuration #####
+##### Combining Java and XML Configuration
Spring’s `@Configuration` class support does not aim to be a 100% complete replacement
for Spring XML. Some facilities, such as Spring XML namespaces, remain an ideal way to
@@ -8459,7 +8007,7 @@ configure the container. In cases where XML is convenient or necessary, you have
choice: either instantiate the container in an “XML-centric” way by using, for example,`ClassPathXmlApplicationContext`, or instantiate it in a “Java-centric” way by using`AnnotationConfigApplicationContext` and the `@ImportResource` annotation to import XML
as needed.
-###### [](#beans-java-combining-xml-centric)XML-centric Use of `@Configuration` Classes ######
+###### XML-centric Use of `@Configuration` Classes
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
@@ -8587,7 +8135,7 @@ The following example shows the modified `system-test-config.xml` file:
```
-###### [](#beans-java-combining-java-centric)`@Configuration` Class-centric Use of XML with `@ImportResource` ######
+###### `@Configuration` Class-centric Use of XML with `@ImportResource` ######
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
@@ -8680,7 +8228,7 @@ fun main() {
}
```
-### [](#beans-environment)1.13. Environment Abstraction ###
+### 1.13. Environment Abstraction
The [`Environment`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/env/Environment.html) interface
is an abstraction integrated in the container that models two key
@@ -8699,7 +8247,7 @@ on. The role of the `Environment` object with relation to properties is to provi
user with a convenient service interface for configuring property sources and resolving
properties from them.
-#### [](#beans-definition-profiles)1.13.1. Bean Definition Profiles ####
+#### 1.13.1. Bean Definition Profiles
Bean definition profiles provide a mechanism in the core container that allows for
registration of different beans in different environments. The word, “environment,”
@@ -8782,7 +8330,7 @@ certain contexts but not in others. You could say that you want to register a
certain profile of bean definitions in situation A and a different profile in
situation B. We start by updating our configuration to reflect this need.
-##### [](#beans-definition-profiles-java)Using `@Profile` #####
+##### Using `@Profile`
The [`@Profile`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Profile.html)annotation lets you indicate that a component is eligible for registration
when one or more specified profiles are active. Using our preceding example, we
@@ -8959,7 +8507,7 @@ class AppConfig {
| |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.
If you want to define alternative beans with different profile conditions, use distinct Java method names that point to the same bean name by using the `@Bean` name attribute, as shown in the preceding example. If the argument signatures are all the same (for example, all of the variants have no-arg factory methods), this is the only way to represent such an arrangement in a valid Java class in the first place (since there can only be one method of a particular name and argument signature).|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-definition-profiles-xml)XML Bean Definition Profiles #####
+##### XML Bean Definition Profiles
The XML counterpart is the `profile` attribute of the `` element. Our preceding sample
configuration can be rewritten in two XML files, as follows:
@@ -9021,7 +8569,7 @@ 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:
In the preceding example, the `dataSource` bean is exposed if both the `production` and`us-east` profiles are active.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#beans-definition-profiles-enable)Activating a Profile #####
+##### 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
@@ -9078,7 +8626,7 @@ as the following example shows:
-Dspring.profiles.active="profile1,profile2"
```
-##### [](#beans-definition-profiles-default)Default Profile #####
+##### Default Profile
The default profile represents the profile that is enabled by default. Consider the
following example:
@@ -9124,7 +8672,7 @@ profile is enabled, the default profile does not apply.
You can change the name of the default profile by using `setDefaultProfiles()` on
the `Environment` or, declaratively, by using the `spring.profiles.default` property.
-#### [](#beans-property-source-abstraction)1.13.2. `PropertySource` Abstraction ####
+#### 1.13.2. `PropertySource` Abstraction
Spring’s `Environment` abstraction provides search operations over a configurable
hierarchy of property sources. Consider the following listing:
@@ -9189,7 +8737,7 @@ search. If it contains a `my-property` property, the property is detected and re
any `my-property` property in any other `PropertySource`. The[`MutablePropertySources`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/env/MutablePropertySources.html)API exposes a number of methods that allow for precise manipulation of the set of
property sources.
-#### [](#beans-using-propertysource)1.13.3. Using `@PropertySource` ####
+#### 1.13.3. Using `@PropertySource`
The [`@PropertySource`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/PropertySource.html)annotation provides a convenient and declarative mechanism for adding a `PropertySource`to Spring’s `Environment`.
@@ -9281,7 +8829,7 @@ as a default. If no default is specified and a property cannot be resolved, an`I
| |The `@PropertySource` annotation is repeatable, according to Java 8 conventions. However, all such `@PropertySource` annotations need to be declared at the same level, either directly on the configuration class or as meta-annotations within the same custom annotation. Mixing direct annotations and meta-annotations is not recommended, since direct annotations effectively override meta-annotations.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#beans-placeholder-resolution-in-statements)1.13.4. Placeholder Resolution in Statements ####
+#### 1.13.4. Placeholder Resolution in Statements
Historically, the value of placeholders in elements could be resolved only against
JVM system properties or environment variables. This is no longer the case. Because
@@ -9299,7 +8847,7 @@ Concretely, the following statement works regardless of where the `customer`prop
```
-### [](#context-load-time-weaver)1.14. Registering a `LoadTimeWeaver` ###
+### 1.14. Registering a `LoadTimeWeaver`
The `LoadTimeWeaver` is used by Spring to dynamically transform classes as they are
loaded into the Java virtual machine (JVM).
@@ -9336,7 +8884,7 @@ weaver instance. This is particularly useful in combination with[Spring’s JPA
necessary for JPA class transformation.
Consult the[`LocalContainerEntityManagerFactoryBean`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.html)javadoc for more detail. For more on AspectJ load-time weaving, see [Load-time Weaving with AspectJ in the Spring Framework](#aop-aj-ltw).
-### [](#context-introduction)1.15. Additional Capabilities of the `ApplicationContext` ###
+### 1.15. Additional Capabilities of the `ApplicationContext`
As discussed in the [chapter introduction](#beans), the `org.springframework.beans.factory`package provides basic functionality for managing and manipulating beans, including in a
programmatic way. The `org.springframework.context` package adds the[`ApplicationContext`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/ApplicationContext.html)interface, which extends the `BeanFactory` interface, in addition to extending other
@@ -9358,7 +8906,7 @@ package also provides the following functionality:
* Loading of multiple (hierarchical) contexts, letting each be focused on one
particular layer, such as the web layer of an application, through the`HierarchicalBeanFactory` interface.
-#### [](#context-functionality-messagesource)1.15.1. Internationalization using `MessageSource` ####
+#### 1.15.1. Internationalization using `MessageSource`
The `ApplicationContext` interface extends an interface called `MessageSource` and,
therefore, provides internationalization (“i18n”) functionality. Spring also provides the`HierarchicalMessageSource` interface, which can resolve messages hierarchically.
@@ -9562,7 +9110,7 @@ the application context’s `MessageSource` when the bean is created and configu
| |As an alternative to `ResourceBundleMessageSource`, Spring provides a`ReloadableResourceBundleMessageSource` class. This variant supports the same bundle file format but is more flexible than the standard JDK based`ResourceBundleMessageSource` implementation. In particular, it allows for reading files from any Spring resource location (not only from the classpath) and supports hot reloading of bundle property files (while efficiently caching them in between). See the [`ReloadableResourceBundleMessageSource`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/support/ReloadableResourceBundleMessageSource.html)javadoc for details.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#context-functionality-events)1.15.2. Standard and Custom Events ####
+#### 1.15.2. Standard and Custom Events
Event handling in the `ApplicationContext` is provided through the `ApplicationEvent`class and the `ApplicationListener` interface. If a bean that implements the`ApplicationListener` interface is deployed into the context, every time an`ApplicationEvent` gets published to the `ApplicationContext`, that bean is notified.
Essentially, this is the standard Observer design pattern.
@@ -9738,7 +9286,7 @@ notify appropriate parties.
| |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](https://projects.spring.io/spring-integration/) project provides complete support for building lightweight,[pattern-oriented](https://www.enterpriseintegrationpatterns.com), event-driven architectures that build upon the well-known Spring programming model.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#context-functionality-events-annotation)Annotation-based Event Listeners #####
+##### Annotation-based Event Listeners
You can register an event listener on any method of a managed bean by using the`@EventListener` annotation. The `BlockedListNotifier` can be rewritten as follows:
@@ -9866,7 +9414,7 @@ fun handleBlockedListEvent(event: BlockedListEvent): ListUpdateEvent {
The `handleBlockedListEvent()` method publishes a new `ListUpdateEvent` for every`BlockedListEvent` that it handles. If you need to publish several events, you can return
a `Collection` or an array of events instead.
-##### [](#context-functionality-events-async)Asynchronous Listeners #####
+##### Asynchronous Listeners
If you want a particular listener to process events asynchronously, you can reuse the[regular `@Async` support](integration.html#scheduling-annotation-support-async).
The following example shows how to do so:
@@ -9899,7 +9447,7 @@ Be aware of the following limitations when using asynchronous events:
* Asynchronous event listener methods cannot publish a subsequent event by returning a
value. If you need to publish another event as the result of the processing, inject an[`ApplicationEventPublisher`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/ApplicationEventPublisher.html)to publish the event manually.
-##### [](#context-functionality-events-order)Ordering Listeners #####
+##### 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:
@@ -9923,7 +9471,7 @@ fun processBlockedListEvent(event: BlockedListEvent) {
}
```
-##### [](#context-functionality-events-generics)Generic Events #####
+##### Generic Events
You can also use generics to further define the structure of your event. Consider using an`EntityCreatedEvent` 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`:
@@ -9984,7 +9532,7 @@ class EntityCreatedEvent(entity: T) : ApplicationEvent(entity), ResolvableTyp
| |This works not only for `ApplicationEvent` but any arbitrary object that you send as an event.|
|---|--------------------------------------------------------------------------------------------------|
-#### [](#context-functionality-resources)1.15.3. Convenient Access to Low-level Resources ####
+#### 1.15.3. Convenient Access to Low-level Resources
For optimal usage and understanding of application contexts, you should familiarize
yourself with Spring’s `Resource` abstraction, as described in [Resources](#resources).
@@ -10012,7 +9560,7 @@ location path as a classpath location. You can also use location paths (resource
with special prefixes to force loading of definitions from the classpath or a URL,
regardless of the actual context type.
-#### [](#context-functionality-startup)1.15.4. Application Startup Tracking ####
+#### 1.15.4. Application Startup Tracking
The `ApplicationContext` manages the lifecycle of Spring applications and provides a rich
programming model around components. As a result, complex applications can have equally
@@ -10078,7 +9626,7 @@ 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.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#context-create)1.15.5. Convenient ApplicationContext Instantiation for Web Applications ####
+#### 1.15.5. Convenient ApplicationContext Instantiation for Web Applications
You can create `ApplicationContext` instances declaratively by using, for example, a`ContextLoader`. Of course, you can also create `ApplicationContext` instances
programmatically by using one of the `ApplicationContext` implementations.
@@ -10104,7 +9652,7 @@ delimiters (comma, semicolon, and whitespace) and uses the values as locations w
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`).
-#### [](#context-deploy-rar)1.15.6. Deploying a Spring `ApplicationContext` as a Java EE RAR File ####
+#### 1.15.6. Deploying a Spring `ApplicationContext` as a Java EE RAR File
It is possible to deploy a Spring `ApplicationContext` as a RAR file, encapsulating the
context and all of its required bean classes and library JARs in a Java EE RAR deployment
@@ -10139,7 +9687,7 @@ For a simple deployment of a Spring ApplicationContext as a Java EE RAR file:
| |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.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#beans-beanfactory)1.16. The `BeanFactory` ###
+### 1.16. The `BeanFactory`
The `BeanFactory` API provides the underlying basis for Spring’s IoC functionality.
Its specific contracts are mostly used in integration with other parts of Spring and
@@ -10158,7 +9706,7 @@ component annotations to be used. All of these flavors come in through extension
operate on shared `BeanDefinition` objects as a core metadata representation.
This is the essence of what makes Spring’s container so flexible and extensible.
-#### [](#context-introduction-ctx-vs-beanfactory)1.16.1. `BeanFactory` or `ApplicationContext`? ####
+#### 1.16.1. `BeanFactory` or `ApplicationContext`?
This section explains the differences between the `BeanFactory` and`ApplicationContext` container levels and the implications on bootstrapping.
@@ -10261,8 +9809,7 @@ container functionality in a typical enterprise setup.
| |An `AnnotationConfigApplicationContext` has all common annotation post-processors registered and may bring in additional processors underneath the covers through configuration annotations, such as `@EnableTransactionManagement`. At the abstraction level of Spring’s annotation-based configuration model, the notion of bean post-processors becomes a mere internal container detail.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-[](#resources)2. Resources
-----------
+## 2. Resources
This chapter covers how Spring handles resources and how you can work with resources in
Spring. It includes the following topics:
@@ -10283,7 +9830,7 @@ Spring. It includes the following topics:
* [Application Contexts and Resource Paths](#resources-app-ctx)
-### [](#resources-introduction)2.1. Introduction ###
+### 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
@@ -10292,7 +9839,7 @@ resource that needs to be obtained from the classpath or relative to a`ServletCo
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.
-### [](#resources-resource)2.2. The `Resource` Interface ###
+### 2.2. The `Resource` Interface
Spring’s `Resource` interface located in the `org.springframework.core.io.` package is
meant to be a more capable interface for abstracting access to low-level resources. The
@@ -10378,7 +9925,7 @@ considered equivalent to any other library you would use for this purpose.
| |The `Resource` abstraction does not replace functionality. It wraps it where possible. For example, a `UrlResource` wraps a URL and uses the wrapped `URL` to do its work.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#resources-implementations)2.3. Built-in `Resource` Implementations ###
+### 2.3. Built-in `Resource` Implementations
Spring includes several built-in `Resource` implementations:
@@ -10399,7 +9946,7 @@ Spring includes several built-in `Resource` implementations:
For a complete list of `Resource` implementations available in Spring, consult the
"All Known Implementing Classes" section of the[`Resource`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/io/Resource.html) javadoc.
-#### [](#resources-implementations-urlresource)2.3.1. `UrlResource` ####
+#### 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
@@ -10413,7 +9960,7 @@ well-known (to property editor, that is) prefix (such as `classpath:`), it creat
appropriate specialized `Resource` for that prefix. However, if it does not recognize the
prefix, it assumes the string is a standard URL string and creates a `UrlResource`.
-#### [](#resources-implementations-classpathresource)2.3.2. `ClassPathResource` ####
+#### 2.3.2. `ClassPathResource`
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
@@ -10428,19 +9975,19 @@ resolution as a `java.net.URL`.
A `ClassPathResource` is created by Java code by explicitly using the `ClassPathResource`constructor but is often created implicitly when you call an API method that takes a`String` argument meant to represent a path. For the latter case, a JavaBeans`PropertyEditor` recognizes the special prefix, `classpath:`, on the string path and
creates a `ClassPathResource` in that case.
-#### [](#resources-implementations-filesystemresource)2.3.3. `FileSystemResource` ####
+#### 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`.
-#### [](#resources-implementations-pathresource)2.3.4. `PathResource` ####
+#### 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.
-#### [](#resources-implementations-servletcontextresource)2.3.5. `ServletContextResource` ####
+#### 2.3.5. `ServletContextResource`
This is a `Resource` implementation for `ServletContext` resources that interprets
relative paths within the relevant web application’s root directory.
@@ -10451,7 +9998,7 @@ 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.
-#### [](#resources-implementations-inputstreamresource)2.3.6. `InputStreamResource` ####
+#### 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
@@ -10462,14 +10009,14 @@ already-opened resource. Therefore, it returns `true` from `isOpen()`. Do not us
you need to keep the resource descriptor somewhere or if you need to read a stream
multiple times.
-#### [](#resources-implementations-bytearrayresource)2.3.7. `ByteArrayResource` ####
+#### 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`.
-### [](#resources-resourceloader)2.4. The `ResourceLoader` Interface ###
+### 2.4. The `ResourceLoader` Interface
The `ResourceLoader` interface is meant to be implemented by objects that can return
(that is, load) `Resource` instances. The following listing shows the `ResourceLoader`interface definition:
@@ -10561,7 +10108,7 @@ The following table summarizes the strategy for converting `String` objects to `
| https: | `https://myserver/logo.png` | Loaded as a `URL`. |
| (none) | `/data/config.xml` | Depends on the underlying `ApplicationContext`. |
-### [](#resources-resourcepatternresolver)2.5. The `ResourcePatternResolver` Interface ###
+### 2.5. The `ResourcePatternResolver` Interface
The `ResourcePatternResolver` interface is an extension to the `ResourceLoader` interface
which defines a strategy for resolving a location pattern (for example, an Ant-style path
@@ -10596,7 +10143,7 @@ wildcards.
| |The default `ResourceLoader` in any standard `ApplicationContext` is in fact an instance of `PathMatchingResourcePatternResolver` which implements the `ResourcePatternResolver`interface. The same is true for the `ApplicationContext` instance itself which also implements the `ResourcePatternResolver` interface and delegates to the default`PathMatchingResourcePatternResolver`.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#resources-resourceloaderaware)2.6. The `ResourceLoaderAware` Interface ###
+### 2.6. The `ResourceLoaderAware` Interface
The `ResourceLoaderAware` interface is a special callback interface which identifies
components that expect to be provided a `ResourceLoader` reference. The following listing
@@ -10632,7 +10179,7 @@ For more information, see [Using `@Autowired`](#beans-autowired-annotation).
| |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`](#resources-resourcepatternresolver) autowired into your application components instead of `ResourceLoader`.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#resources-as-dependencies)2.7. Resources as Dependencies ###
+### 2.7. Resources as Dependencies
If the bean itself is going to determine and supply the resource path through some sort
of dynamic process, it probably makes sense for the bean to use the `ResourceLoader` or`ResourcePatternResolver` interface to load resources. For example, consider the loading
@@ -10751,12 +10298,12 @@ Kotlin
class MyBean(@Value("\${templates.path}") private val templates: Resource[])
```
-### [](#resources-app-ctx)2.8. Application Contexts and Resource Paths ###
+### 2.8. Application Contexts and Resource Paths
This section covers how to create application contexts with resources, including shortcuts
that work with XML, how to use wildcards, and other details.
-#### [](#resources-app-ctx-construction)2.8.1. Constructing Application Contexts ####
+#### 2.8.1. Constructing Application Contexts
An application context constructor (for a specific application context type) generally
takes a string or array of strings as the location paths of the resources, such as
@@ -10817,7 +10364,7 @@ val ctx = FileSystemXmlApplicationContext("classpath:conf/appContext.xml")
Using `FileSystemXmlApplicationContext` loads the bean definitions from the classpath.
However, it is still a `FileSystemXmlApplicationContext`. If it is subsequently used as a`ResourceLoader`, any unprefixed paths are still treated as filesystem paths.
-##### [](#resources-app-ctx-classpathxml)Constructing `ClassPathXmlApplicationContext` Instances — Shortcuts #####
+##### Constructing `ClassPathXmlApplicationContext` Instances — Shortcuts
The `ClassPathXmlApplicationContext` exposes a number of constructors to enable
convenient instantiation. The basic idea is that you can supply merely a string array
@@ -10854,7 +10401,7 @@ val ctx = ClassPathXmlApplicationContext(arrayOf("services.xml", "repositories.x
See the [`ClassPathXmlApplicationContext`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/support/ClassPathXmlApplicationContext.html)javadoc for details on the various constructors.
-#### [](#resources-app-ctx-wildcards-in-resource-paths)2.8.2. Wildcards in Application Context Constructor Resource Paths ####
+#### 2.8.2. Wildcards in Application Context Constructor Resource Paths ####
The resource paths in application context constructor values may be simple paths (as
shown earlier), each of which has a one-to-one mapping to a target `Resource` or,
@@ -10872,7 +10419,7 @@ resolved at construction time. It has nothing to do with the `Resource` type its
You cannot use the `classpath*:` prefix to construct an actual `Resource`, as
a resource points to just one resource at a time.
-##### [](#resources-app-ctx-ant-patterns-in-paths)Ant-style Patterns #####
+##### Ant-style Patterns
Path locations can contain Ant-style patterns, as the following example shows:
@@ -10891,7 +10438,7 @@ a `java.io.File` is obtained from it and used to resolve the wildcard by travers
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.
-###### [](#resources-app-ctx-portability)Implications on Portability ######
+###### 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.
@@ -10909,7 +10456,7 @@ walk the contents of the jar and resolve the wildcard. This does work in most en
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.
-##### [](#resources-classpath-wildcards)The `classpath*:` Prefix #####
+##### The `classpath*:` Prefix
When constructing an XML-based application context, a location string may use the
special `classpath*:` prefix, as the following example shows:
@@ -10941,7 +10488,7 @@ used on the last non-wildcard path segment to get all the matching resources in
class loader hierarchy and then, off each resource, the same `PathMatcher` resolution
strategy described earlier is used for the wildcard subpath.
-##### [](#resources-wildcards-in-path-other-stuff)Other Notes Relating to Wildcards #####
+##### Other Notes Relating to Wildcards
Note that `classpath*:`, when combined with Ant-style patterns, only works
reliably with at least one root directory before the pattern starts, unless the actual
@@ -10976,7 +10523,7 @@ multiple `ClassLoader` locations, the desired resource may not exist in the firs
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`.
-#### [](#resources-filesystemresource-caveats)2.8.3. `FileSystemResource` Caveats ####
+#### 2.8.3. `FileSystemResource` Caveats
A `FileSystemResource` that is not attached to a `FileSystemApplicationContext` (that
is, when a `FileSystemApplicationContext` is not the actual `ResourceLoader`) treats
@@ -11079,8 +10626,7 @@ Kotlin
val ctx = FileSystemXmlApplicationContext("file:///conf/context.xml")
```
-[](#validation)3. Validation, Data Binding, and Type Conversion
-----------
+## 3. Validation, Data Binding, and Type Conversion#
There are pros and cons for considering validation as business logic, and Spring offers
a design for validation (and data binding) that does not exclude either one of them.
@@ -11110,7 +10656,7 @@ as described in [Java Bean Validation](#validation-beanvalidation), and use it e
needs. In the web layer, applications can further register controller-local Spring`Validator` instances per `DataBinder`, as described in [Configuring a `DataBinder`](#validation-binder), which can
be useful for plugging in custom validation logic.
-### [](#validator)3.1. Validation by Using Spring’s Validator Interface ###
+### 3.1. Validation by Using Spring’s Validator Interface
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.
@@ -11287,7 +10833,7 @@ of Spring Web MVC, you can use the `` tag to inspect the error mes
you can also inspect the `Errors` object yourself. More information about the
methods it offers can be found in the [javadoc](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/validation/Errors.html).
-### [](#validation-conversion)3.2. Resolving Codes to Error Messages ###
+### 3.2. Resolving Codes to Error Messages
We covered databinding and validation. This section covers outputting messages that correspond
to validation errors. In the example shown in the [preceding section](#validator),
@@ -11305,7 +10851,7 @@ More information on the `MessageCodesResolver` and the default strategy can be f
in the javadoc of[`MessageCodesResolver`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/validation/MessageCodesResolver.html) and[`DefaultMessageCodesResolver`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/validation/DefaultMessageCodesResolver.html),
respectively.
-### [](#beans-beans)3.3. Bean Manipulation and the `BeanWrapper` ###
+### 3.3. Bean Manipulation and the `BeanWrapper`
The `org.springframework.beans` package adheres to the JavaBeans standard.
A JavaBean is a class with a default no-argument constructor and that follows
@@ -11324,7 +10870,7 @@ The `BeanWrapper` usually is not used by application code directly but is used b
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.
-#### [](#beans-beans-conventions)3.3.1. Setting and Getting Basic and Nested Properties ####
+#### 3.3.1. Setting and Getting Basic and Nested Properties
Setting and getting properties is done through the `setPropertyValue` and`getPropertyValue` overloaded method variants of `BeanWrapper`. See their Javadoc for
details. The below table shows some examples of these conventions:
@@ -11454,7 +11000,7 @@ company.setPropertyValue("managingDirector", jim.wrappedInstance)
val salary = company.getPropertyValue("managingDirector.salary") as Float?
```
-#### [](#beans-beans-conversion)3.3.2. Built-in `PropertyEditor` Implementations ####
+#### 3.3.2. Built-in `PropertyEditor` Implementations
Spring uses the concept of a `PropertyEditor` to effect the conversion between an`Object` and a `String`. It can be handy
to represent properties in a different way than the object itself. For example, a `Date`can be represented in a human readable way (as the `String`: `'2007-14-09'`), while
@@ -11572,7 +11118,7 @@ class SomethingBeanInfo : SimpleBeanInfo() {
}
```
-##### [](#beans-beans-conversion-customeditor-registration)Registering Additional Custom `PropertyEditor` Implementations #####
+##### Registering Additional Custom `PropertyEditor` Implementations #####
When setting bean properties as string values, a Spring IoC container ultimately uses
standard JavaBeans `PropertyEditor` implementations to convert these strings to the complex type of the
@@ -11693,7 +11239,7 @@ Finally, the following example shows how to use `CustomEditorConfigurer` to regi
```
-###### [](#beans-beans-conversion-customeditor-registration-per)Using `PropertyEditorRegistrar` ######
+###### Using `PropertyEditorRegistrar`
Another mechanism for registering property editors with the Spring container is to
create and use a `PropertyEditorRegistrar`. This interface is particularly useful when
@@ -11805,7 +11351,7 @@ class RegisterUserController(
This style of `PropertyEditor` registration can lead to concise code (the implementation
of `initBinder(..)` is only one line long) and lets common `PropertyEditor`registration code be encapsulated in a class and then shared amongst as many`Controllers` as needed.
-### [](#core-convert)3.4. Spring Type Conversion ###
+### 3.4. Spring Type Conversion
Spring 3 introduced a `core.convert` package that provides a general type conversion
system. The system defines an SPI to implement type conversion logic and an API
@@ -11814,7 +11360,7 @@ as an alternative to `PropertyEditor` implementations to convert externalized be
strings to the required property types. You can also use the public API anywhere in your
application where type conversion is needed.
-#### [](#core-convert-Converter-API)3.4.1. Converter SPI ####
+#### 3.4.1. Converter SPI
The SPI to implement type conversion logic is simple and strongly typed, as the following
interface definition shows:
@@ -11851,7 +11397,7 @@ final class StringToInteger implements Converter {
}
```
-#### [](#core-convert-ConverterFactory-SPI)3.4.2. Using `ConverterFactory` ####
+#### 3.4.2. Using `ConverterFactory`
When you need to centralize the conversion logic for an entire class hierarchy
(for example, when converting from `String` to `Enum` objects), you can implement`ConverterFactory`, as the following example shows:
@@ -11895,7 +11441,7 @@ final class StringToEnumConverterFactory implements ConverterFactoryit only when you need it. Favor `Converter` or `ConverterFactory` for basic type conversion needs.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#core-convert-ConditionalGenericConverter-SPI)Using `ConditionalGenericConverter` #####
+##### 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
@@ -11949,7 +11495,7 @@ public interface ConditionalGenericConverter extends GenericConverter, Condition
A good example of a `ConditionalGenericConverter` is an `IdToEntityConverter` that converts
between a persistent entity identifier and an entity reference. Such an `IdToEntityConverter`might match only if the target entity type declares a static finder method (for example,`findAccount(Long)`). You might perform such a finder method check in the implementation of`matches(TypeDescriptor, TypeDescriptor)`.
-#### [](#core-convert-ConversionService-API)3.4.4. The `ConversionService` API ####
+#### 3.4.4. The `ConversionService` API
`ConversionService` defines a unified API for executing type conversion logic at
runtime. Converters are often run behind the following facade interface:
@@ -11976,7 +11522,7 @@ A robust `ConversionService` implementation is provided in the `core.convert.sup
use in most environments. `ConversionServiceFactory` provides a convenient factory for
creating common `ConversionService` configurations.
-#### [](#core-convert-Spring-config)3.4.5. Configuring a `ConversionService` ####
+#### 3.4.5. Configuring a `ConversionService`
A `ConversionService` is a stateless object designed to be instantiated at application
startup and then shared between multiple threads. In a Spring application, you typically
@@ -12015,7 +11561,7 @@ It is also common to use a `ConversionService` within a Spring MVC application.
In certain situations, you may wish to apply formatting during conversion. See[The `FormatterRegistry` SPI](#format-FormatterRegistry-SPI) for details on using `FormattingConversionServiceFactoryBean`.
-#### [](#core-convert-programmatic-usage)3.4.6. Using a `ConversionService` Programmatically ####
+#### 3.4.6. Using a `ConversionService` Programmatically
To work with a `ConversionService` instance programmatically, you can inject a reference to
it like you would for any other bean. The following example shows how to do so:
@@ -12086,7 +11632,7 @@ with any `ConverterRegistry` by using the static `addDefaultConverters`method on
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.
-### [](#format)3.5. Spring Field Formatting ###
+### 3.5. Spring Field Formatting
As discussed in the previous section, [`core.convert`](#core-convert) is a
general-purpose type conversion system. It provides a unified `ConversionService` API as
@@ -12108,7 +11654,7 @@ conversion logic — for example, for converting between a `java.util.Date`
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.
-#### [](#format-Formatter-SPI)3.5.1. The `Formatter` SPI ####
+#### 3.5.1. The `Formatter` SPI
The `Formatter` SPI to implement field formatting logic is simple and strongly typed. The
following listing shows the `Formatter` interface definition:
@@ -12208,7 +11754,7 @@ class DateFormatter(private val pattern: String) : Formatter {
The Spring team welcomes community-driven `Formatter` contributions. See[GitHub Issues](https://github.com/spring-projects/spring-framework/issues) to contribute.
-#### [](#format-CustomFormatAnnotations)3.5.2. Annotation-driven Formatting ####
+#### 3.5.2. Annotation-driven Formatting
Field formatting can be configured by field type or annotation. To bind
an annotation to a `Formatter`, implement `AnnotationFormatterFactory`. The following
@@ -12331,7 +11877,7 @@ class MyModel(
)
```
-##### [](#format-annotations-api)Format Annotation API #####
+##### Format Annotation API
A portable format annotation API exists in the `org.springframework.format.annotation`package. You can use `@NumberFormat` to format `Number` fields such as `Double` and`Long`, and `@DateTimeFormat` to format `java.util.Date`, `java.util.Calendar`, `Long`(for millisecond timestamps) as well as JSR-310 `java.time`.
@@ -12356,7 +11902,7 @@ class MyModel(
)
```
-#### [](#format-FormatterRegistry-SPI)3.5.3. The `FormatterRegistry` SPI ####
+#### 3.5.3. The `FormatterRegistry` SPI
The `FormatterRegistry` is an SPI for registering formatters and converters.`FormattingConversionService` is an implementation of `FormatterRegistry` suitable for
most environments. You can programmatically or declaratively configure this variant
@@ -12393,7 +11939,7 @@ enforce that all date fields are formatted a certain way or that fields with a s
annotation are formatted in a certain way. With a shared `FormatterRegistry`, you define
these rules once, and they are applied whenever formatting is needed.
-#### [](#format-FormatterRegistrar-SPI)3.5.4. The `FormatterRegistrar` SPI ####
+#### 3.5.4. The `FormatterRegistrar` SPI
`FormatterRegistrar` is an SPI for registering formatters and converters through the
FormatterRegistry. The following listing shows its interface definition:
@@ -12414,11 +11960,11 @@ needs to be indexed under a specific field type different from its own `` or
registering a `Printer`/`Parser` pair. The next section provides more information on
converter and formatter registration.
-#### [](#format-configuring-formatting-mvc)3.5.5. Configuring Formatting in Spring MVC ####
+#### 3.5.5. Configuring Formatting in Spring MVC
See [Conversion and Formatting](web.html#mvc-config-conversion) in the Spring MVC chapter.
-### [](#format-configuring-formatting-globaldatetimeformat)3.6. Configuring a Global Date and Time Format ###
+### 3.6. Configuring a Global Date and Time Format
By default, date and time fields not annotated with `@DateTimeFormat` are converted from
strings by using the `DateFormat.SHORT` style. If you prefer, you can change this by
@@ -12526,11 +12072,11 @@ If you prefer XML-based configuration, you can use a`FormattingConversionService
Note there are extra considerations when configuring date and time formats in web
applications. Please see[WebMVC Conversion and Formatting](web.html#mvc-config-conversion) or[WebFlux Conversion and Formatting](web-reactive.html#webflux-config-conversion).
-### [](#validation-beanvalidation)3.7. Java Bean Validation ###
+### 3.7. Java Bean Validation
The Spring Framework provides support for the[Java Bean Validation](https://beanvalidation.org/) API.
-#### [](#validation-beanvalidation-overview)3.7.1. Overview of Bean Validation ####
+#### 3.7.1. Overview of Bean Validation
Bean Validation provides a common way of validation through constraint declaration and
metadata for Java applications. To use it, you annotate domain model properties with
@@ -12590,7 +12136,7 @@ the API. See the [Hibernate Validator](https://hibernate.org/validator/) documen
specific constraints. To learn how to set up a bean validation provider as a Spring
bean, keep reading.
-#### [](#validation-beanvalidation-spring)3.7.2. Configuring a Bean Validation Provider ####
+#### 3.7.2. Configuring a Bean Validation Provider
Spring provides full support for the Bean Validation API including the bootstrapping of a
Bean Validation provider as a Spring bean. This lets you inject a`javax.validation.ValidatorFactory` or `javax.validation.Validator` wherever validation is
@@ -12625,7 +12171,7 @@ The basic configuration in the preceding example triggers bean validation to ini
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.
-##### [](#validation-beanvalidation-spring-inject)Injecting a Validator #####
+##### 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
@@ -12681,7 +12227,7 @@ import org.springframework.validation.Validator
class MyService(@Autowired private val validator: Validator)
```
-##### [](#validation-beanvalidation-spring-constraints)Configuring Custom Constraints #####
+##### Configuring Custom Constraints
Each bean validation constraint consists of two parts:
@@ -12744,7 +12290,7 @@ class MyConstraintValidator(private val aDependency: Foo) : ConstraintValidator
As the preceding example shows, a `ConstraintValidator` implementation can have its dependencies`@Autowired` as any other Spring bean.
-##### [](#validation-beanvalidation-spring-method)Spring-driven Method Validation #####
+##### Spring-driven Method Validation
You can integrate the method validation feature supported by Bean Validation 1.1 (and, as
a custom extension, also by Hibernate Validator 4.3) into a Spring context through a`MethodValidationPostProcessor` bean definition:
@@ -12777,13 +12323,13 @@ groups to use. See[`MethodValidationPostProcessor`](https://docs.spring.io/sprin
| |Method validation relies on [AOP Proxies](#aop-introduction-proxies) around the target classes, either JDK dynamic proxies for methods on interfaces or CGLIB proxies. There are certain limitations with the use of proxies, some of which are described in[Understanding AOP Proxies](#aop-understanding-aop-proxies). In addition remember to always use methods and accessors on proxied classes; direct field access will not work.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#validation-beanvalidation-spring-other)Additional Configuration Options #####
+##### Additional Configuration Options
The default `LocalValidatorFactoryBean` configuration suffices for most
cases. There are a number of configuration options for various Bean Validation
constructs, from message interpolation to traversal resolution. See the[`LocalValidatorFactoryBean`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/validation/beanvalidation/LocalValidatorFactoryBean.html)javadoc for more information on these options.
-#### [](#validation-binder)3.7.3. Configuring a `DataBinder` ####
+#### 3.7.3. Configuring a `DataBinder`
Since Spring 3, you can configure a `DataBinder` instance with a `Validator`. Once
configured, you can invoke the `Validator` by calling `binder.validate()`. Any validation`Errors` are automatically added to the binder’s `BindingResult`.
@@ -12829,12 +12375,11 @@ You can also configure a `DataBinder` with multiple `Validator` instances throug
combining globally configured bean validation with a Spring `Validator` configured
locally on a DataBinder instance. See[Spring MVC Validation Configuration](web.html#mvc-config-validation).
-#### [](#validation-mvc)3.7.4. Spring MVC 3 Validation ####
+#### 3.7.4. Spring MVC 3 Validation
See [Validation](web.html#mvc-config-validation) in the Spring MVC chapter.
-[](#expressions)4. Spring Expression Language (SpEL)
-----------
+## 4. Spring Expression Language (SpEL)
The Spring Expression Language (“SpEL” for short) is a powerful expression language that
supports querying and manipulating an object graph at runtime. The language syntax is
@@ -12904,7 +12449,7 @@ The expression language supports the following functionality:
* Templated expressions
-### [](#expressions-evaluation)4.1. Evaluation ###
+### 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](#expressions-language-ref).
@@ -13104,7 +12649,7 @@ val result = exp.getValue(tesla, Boolean::class.java)
// result == true
```
-#### [](#expressions-evaluation-context)4.1.1. Understanding `EvaluationContext` ####
+#### 4.1.1. Understanding `EvaluationContext`
The `EvaluationContext` interface is used when evaluating an expression to resolve
properties, methods, or fields and to help perform type conversion. Spring provides two
@@ -13132,7 +12677,7 @@ one or some combination of the following:
* Data binding properties for read and write
-##### [](#expressions-type-conversion)Type Conversion #####
+##### Type Conversion
By default, SpEL uses the conversion service available in Spring core
(`org.springframework.core.convert.ConversionService`). This conversion service comes
@@ -13187,7 +12732,7 @@ parser.parseExpression("booleanList[0]").setValue(context, simple, "false")
val b = simple.booleanList[0]
```
-#### [](#expressions-parser-configuration)4.1.2. Parser Configuration ####
+#### 4.1.2. Parser Configuration
It is possible to configure the SpEL expression parser by using a parser configuration
object (`org.springframework.expression.spel.SpelParserConfiguration`). The configuration
@@ -13252,7 +12797,7 @@ val o = expression.getValue(demo)
// Each entry is a new empty String
```
-#### [](#expressions-spel-compilation)4.1.3. SpEL Compilation ####
+#### 4.1.3. SpEL Compilation
Spring Framework 4.1 includes a basic expression compiler. Expressions are usually
interpreted, which provides a lot of dynamic flexibility during evaluation but
@@ -13282,7 +12827,7 @@ and numeric operations, the performance gain can be very noticeable. In an examp
micro benchmark run of 50000 iterations, it took 75ms to evaluate by using the
interpreter and only 3ms using the compiled version of the expression.
-##### [](#expressions-compiler-configuration)Compiler Configuration #####
+##### 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
@@ -13355,7 +12900,7 @@ The second way to configure the compiler is for use when SpEL is embedded inside
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`](appendix.html#appendix-spring-properties) mechanism) to one of the`SpelCompilerMode` enum values (`off`, `immediate`, or `mixed`).
-##### [](#expressions-compiler-limitations)Compiler Limitations #####
+##### 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
@@ -13372,13 +12917,13 @@ kinds of expression cannot be compiled at the moment:
More types of expressions will be compilable in the future.
-### [](#expressions-beandef)4.2. Expressions in Bean Definitions ###
+### 4.2. Expressions in Bean Definitions
You can use SpEL expressions with XML-based or annotation-based configuration metadata for
defining `BeanDefinition` instances. In both cases, the syntax to define the expression is of the
form `#{ }`.
-#### [](#expressions-beandef-xml-based)4.2.1. XML Configuration ####
+#### 4.2.1. XML Configuration
A property or constructor argument value can be set by using expressions, as the following
example shows:
@@ -13422,7 +12967,7 @@ You can also refer to other bean properties by name, as the following example sh
```
-#### [](#expressions-beandef-annotation-based)4.2.2. Annotation Configuration ####
+#### 4.2.2. Annotation Configuration
To specify a default value, you can place the `@Value` annotation on fields, methods,
and method or constructor parameters.
@@ -13556,7 +13101,7 @@ class MovieRecommender(private val customerPreferenceDao: CustomerPreferenceDao,
}
```
-### [](#expressions-language-ref)4.3. Language Reference ###
+### 4.3. Language Reference
This section describes how the Spring Expression Language works. It covers the following
topics:
@@ -13591,7 +13136,7 @@ topics:
* [Safe Navigation Operator](#expressions-operator-safe-navigation)
-#### [](#expressions-ref-literal)4.3.1. Literal Expressions ####
+#### 4.3.1. Literal Expressions
The types of literal expressions supported are strings, numeric values (int, real, hex),
boolean, and null. Strings are delimited by single quotation marks. To put a single quotation mark itself
@@ -13640,7 +13185,7 @@ val nullValue = parser.parseExpression("null").value
Numbers support the use of the negative sign, exponential notation, and decimal points.
By default, real numbers are parsed by using `Double.parseDouble()`.
-#### [](#expressions-properties-arrays)4.3.2. Properties, Arrays, Lists, Maps, and Indexers ####
+#### 4.3.2. Properties, Arrays, Lists, Maps, and Indexers
Navigating with property references is easy. To do so, use a period to indicate a nested
property value. The instances of the `Inventor` class, `pupin` and `tesla`, were
@@ -13758,7 +13303,7 @@ parser.parseExpression("officers['advisors'][0].placeOfBirth.country").setValue(
societyContext, "Croatia")
```
-#### [](#expressions-inline-lists)4.3.3. Inline Lists ####
+#### 4.3.3. Inline Lists
You can directly express lists in an expression by using `{}` notation.
@@ -13784,7 +13329,7 @@ val listOfLists = parser.parseExpression("{{'a','b'},{'x','y'}}").getValue(conte
entirely composed of fixed literals, a constant list is created to represent the
expression (rather than building a new list on each evaluation).
-#### [](#expressions-inline-maps)4.3.4. Inline Maps ####
+#### 4.3.4. Inline Maps
You can also directly express maps in an expression by using `{key:value}` notation. The
following example shows how to do so:
@@ -13813,7 +13358,7 @@ constant map is created to represent the expression (rather than building a new
each evaluation). Quoting of the map keys is optional (unless the key contains a period
(`.`)). The examples above do not use quoted keys.
-#### [](#expressions-array-construction)4.3.5. Array Construction ####
+#### 4.3.5. Array Construction
You can build arrays by using the familiar Java syntax, optionally supplying an initializer
to have the array populated at construction time. The following example shows how to do so:
@@ -13844,7 +13389,7 @@ val numbers3 = parser.parseExpression("new int[4][5]").getValue(context) as Arra
You cannot currently supply an initializer when you construct a multi-dimensional array.
-#### [](#expressions-methods)4.3.6. Methods ####
+#### 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
@@ -13872,7 +13417,7 @@ val isMember = parser.parseExpression("isMember('Mihajlo Pupin')").getValue(
societyContext, Boolean::class.java)
```
-#### [](#expressions-operators)4.3.7. Operators ####
+#### 4.3.7. Operators
The Spring Expression Language supports the following kinds of operators:
@@ -13884,7 +13429,7 @@ The Spring Expression Language supports the following kinds of operators:
* [The Assignment Operator](#expressions-assignment)
-##### [](#expressions-operators-relational)Relational Operators #####
+##### 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
@@ -13981,7 +13526,7 @@ which the expression is embedded (such as in an XML document). The textual equiv
All of the textual operators are case-insensitive.
-##### [](#expressions-operators-logical)Logical Operators #####
+##### Logical Operators
SpEL supports the following logical operators:
@@ -14055,7 +13600,7 @@ val expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')"
val falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean::class.java)
```
-##### [](#expressions-operators-mathematical)Mathematical Operators #####
+##### 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.
@@ -14129,7 +13674,7 @@ val one = parser.parseExpression("8 / 5 % 2").getValue(Int::class.java) // 1
val minusTwentyOne = parser.parseExpression("1+2-3*8").getValue(Int::class.java) // -21
```
-##### [](#expressions-assignment)The Assignment Operator #####
+##### The Assignment Operator
To set a property, use the assignment operator (`=`). This is typically done within a
call to `setValue` but can also be done inside a call to `getValue`. The following
@@ -14161,7 +13706,7 @@ val aleks = parser.parseExpression(
"name = 'Aleksandar Seovic'").getValue(context, inventor, String::class.java)
```
-#### [](#expressions-types)4.3.8. Types ####
+#### 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
@@ -14191,7 +13736,7 @@ val trueValue = parser.parseExpression(
.getValue(Boolean::class.java)
```
-#### [](#expressions-constructors)4.3.9. Constructors ####
+#### 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
@@ -14223,7 +13768,7 @@ p.parseExpression(
.getValue(societyContext)
```
-#### [](#expressions-ref-variables)4.3.10. Variables ####
+#### 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.
@@ -14257,7 +13802,7 @@ parser.parseExpression("name = #newName").getValue(context, tesla)
println(tesla.name) // "Mike Tesla"
```
-##### [](#expressions-this-root)The `#this` and `#root` Variables #####
+##### The `#this` and `#root` Variables
The `#this` variable is always defined and refers to the current evaluation object
(against which unqualified references are resolved). The `#root` variable is always
@@ -14301,7 +13846,7 @@ val primesGreaterThanTen = parser.parseExpression(
"#primes.?[#this>10]").getValue(context) as List
```
-#### [](#expressions-ref-functions)4.3.11. Functions ####
+#### 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
@@ -14381,7 +13926,7 @@ val helloWorldReversed = parser.parseExpression(
"#reverseString('hello')").getValue(context, String::class.java)
```
-#### [](#expressions-bean-references)4.3.12. Bean References ####
+#### 4.3.12. Bean References
If the evaluation context has been configured with a bean resolver, you can
look up beans from an expression by using the `@` symbol. The following example shows how
@@ -14434,7 +13979,7 @@ context.setBeanResolver(MyBeanResolver())
val bean = parser.parseExpression("&foo").getValue(context)
```
-#### [](#expressions-operator-ternary)4.3.13. Ternary Operator (If-Then-Else) ####
+#### 4.3.13. Ternary Operator (If-Then-Else)
You can use the ternary operator for performing if-then-else conditional logic inside
the expression. The following listing shows a minimal example:
@@ -14486,7 +14031,7 @@ val queryResultString = parser.parseExpression(expression)
See the next section on the Elvis operator for an even shorter syntax for the
ternary operator.
-#### [](#expressions-operator-elvis)4.3.14. The Elvis Operator ####
+#### 4.3.14. The Elvis Operator
The Elvis operator is a shortening of the ternary operator syntax and is used in the[Groovy](http://www.groovy-lang.org/operators.html#_elvis_operator) language.
With the ternary operator syntax, you usually have to repeat a variable twice, as the
@@ -14553,7 +14098,7 @@ println(name) // Elvis Presley
| |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:
This will inject a system property `pop3.port` if it is defined or 25 if not.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#expressions-operator-safe-navigation)4.3.15. Safe Navigation Operator ####
+#### 4.3.15. Safe Navigation Operator
The safe navigation operator is used to avoid a `NullPointerException` and comes from
the [Groovy](http://www.groovy-lang.org/operators.html#_safe_navigation_operator)language. Typically, when you have a reference to an object, you might need to verify that
@@ -14595,7 +14140,7 @@ city = parser.parseExpression("placeOfBirth?.city").getValue(context, tesla, Str
println(city) // null - does not throw NullPointerException!!!
```
-#### [](#expressions-collection-selection)4.3.16. Collection Selection ####
+#### 4.3.16. Collection Selection
Selection is a powerful expression language feature that lets you transform a
source collection into another collection by selecting from its entries.
@@ -14640,7 +14185,7 @@ val 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]`.
-#### [](#expressions-collection-projection)4.3.17. Collection Projection ####
+#### 4.3.17. Collection Projection
Projection lets a collection drive the evaluation of a sub-expression, and the result is
a new collection. The syntax for projection is `.![projectionExpression]`. For example,
@@ -14667,7 +14212,7 @@ evaluated against each entry in the map (represented as a Java `Map.Entry`). The
of a projection across a map is a list that consists of the evaluation of the projection
expression against each map entry.
-#### [](#expressions-templating)4.3.18. Expression templating ####
+#### 4.3.18. Expression templating
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
@@ -14739,7 +14284,7 @@ class TemplateParserContext : ParserContext {
}
```
-### [](#expressions-example-classes)4.4. Classes Used in the Examples ###
+### 4.4. Classes Used in the Examples
This section lists the classes used in the examples throughout this chapter.
@@ -14943,8 +14488,7 @@ class Society {
}
```
-[](#aop)5. Aspect Oriented Programming with Spring
-----------
+## 5. Aspect Oriented Programming with Spring
Aspect-oriented Programming (AOP) complements Object-oriented Programming (OOP) by
providing another way of thinking about program structure. The key unit of modularity
@@ -14975,7 +14519,7 @@ AOP is used in the Spring Framework to:
| |If you are interested only in generic declarative services or other pre-packaged declarative middleware services such as pooling, you do not need to work directly with Spring AOP, and can skip most of this chapter.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#aop-introduction-defn)5.1. AOP Concepts ###
+### 5.1. AOP Concepts
Let us begin by defining some central AOP concepts and terminology. These terms are not
Spring-specific. Unfortunately, AOP terminology is not particularly intuitive.
@@ -15058,7 +14602,7 @@ targeted independently of the object-oriented hierarchy. For example, you can ap
around advice providing declarative transaction management to a set of methods that span
multiple objects (such as all business operations in the service layer).
-### [](#aop-introduction-spring-defn)5.2. Spring AOP Capabilities and Goals ###
+### 5.2. Spring AOP Capabilities and Goals
Spring AOP is implemented in pure Java. There is no need for a special compilation
process. Spring AOP does not need to control the class loader hierarchy and is thus
@@ -15094,7 +14638,7 @@ API. Spring AOP remains backward-compatible. See [the following chapter](#aop-ap
| |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.
See [Choosing which AOP Declaration Style to Use](#aop-choosing) for a more complete discussion of the “whys and wherefores” of each style.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#aop-introduction-proxies)5.3. AOP Proxies ###
+### 5.3. AOP Proxies
Spring AOP defaults to using standard JDK dynamic proxies for AOP proxies. This
enables any interface (or set of interfaces) to be proxied.
@@ -15109,7 +14653,7 @@ pass a proxied object to a method as a concrete type.
It is important to grasp the fact that Spring AOP is proxy-based. See[Understanding AOP Proxies](#aop-understanding-aop-proxies) for a thorough examination of exactly what this
implementation detail actually means.
-### [](#aop-ataspectj)5.4. @AspectJ support ###
+### 5.4. @AspectJ support
@AspectJ refers to a style of declaring aspects as regular Java classes annotated with
annotations. The @AspectJ style was introduced by the[AspectJ project](https://www.eclipse.org/aspectj) as part of the AspectJ 5 release. Spring
@@ -15120,7 +14664,7 @@ there is no dependency on the AspectJ compiler or weaver.
| |Using the AspectJ compiler and weaver enables use of the full AspectJ language and is discussed in [Using AspectJ with Spring Applications](#aop-using-aspectj).|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#aop-aspectj-support)5.4.1. Enabling @AspectJ Support ####
+#### 5.4.1. Enabling @AspectJ Support
To use @AspectJ aspects in a Spring configuration, you need to enable Spring support for
configuring Spring AOP based on @AspectJ aspects and auto-proxying beans based on
@@ -15133,7 +14677,7 @@ The @AspectJ support can be enabled with XML- or Java-style configuration. In ei
case, you also need to ensure that AspectJ’s `aspectjweaver.jar` library is on the
classpath of your application (version 1.8 or later). This library is available in the`lib` directory of an AspectJ distribution or from the Maven Central repository.
-##### [](#aop-enable-aspectj-java)Enabling @AspectJ Support with Java Configuration #####
+##### Enabling @AspectJ Support with Java Configuration
To enable @AspectJ support with Java `@Configuration`, add the `@EnableAspectJAutoProxy`annotation, as the following example shows:
@@ -15155,7 +14699,7 @@ Kotlin
class AppConfig
```
-##### [](#aop-enable-aspectj-xml)Enabling @AspectJ Support with XML Configuration #####
+##### Enabling @AspectJ Support with XML Configuration
To enable @AspectJ support with XML-based configuration, use the `aop:aspectj-autoproxy`element, as the following example shows:
@@ -15167,7 +14711,7 @@ This assumes that you use schema support as described in[XML Schema-based config
See [the AOP schema](#xsd-schemas-aop) for how to
import the tags in the `aop` namespace.
-#### [](#aop-at-aspectj)5.4.2. Declaring an Aspect ####
+#### 5.4.2. Declaring an Aspect
With @AspectJ support enabled, any bean defined in your application context with a
class that is an @AspectJ aspect (has the `@Aspect` annotation) is automatically
@@ -15219,7 +14763,7 @@ declarations.
| |Advising aspects with other aspects?
In Spring AOP, aspects themselves cannot be the targets of advice from other aspects. The `@Aspect` annotation on a class marks it as an aspect and, hence, excludes it from auto-proxying.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#aop-pointcuts)5.4.3. Declaring a Pointcut ####
+#### 5.4.3. Declaring a Pointcut
Pointcuts determine join points of interest and thus enable us to control
when advice runs. Spring AOP only supports method execution join points for Spring
@@ -15256,7 +14800,7 @@ Programming Guide](https://www.eclipse.org/aspectj/doc/released/progguide/index.
Developer’s Notebook](https://www.eclipse.org/aspectj/doc/released/adk15notebook/index.html)) or one of the books on AspectJ (such as *Eclipse AspectJ*, by Colyer
et al., or *AspectJ in Action*, by Ramnivas Laddad).
-##### [](#aop-pointcuts-designators)Supported Pointcut Designators #####
+##### Supported Pointcut Designators
Spring AOP supports the following AspectJ pointcut designators (PCD) for use in pointcut
expressions:
@@ -15337,7 +14881,7 @@ be used with the `&&` (and), `||` (or), and `!` (negation) operators, too.
| |The `bean` PCD is supported only in Spring AOP and not in native AspectJ weaving. It is a Spring-specific extension to the standard PCDs that AspectJ defines and is, therefore, not available for aspects declared in the `@Aspect` model.
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.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#aop-pointcuts-combining)Combining Pointcut Expressions #####
+##### Combining Pointcut Expressions
You can combine pointcut expressions by using `&&,` `||` and `!`. You can also refer to
pointcut expressions by name. The following example shows three pointcut expressions:
@@ -15384,7 +14928,7 @@ rules apply (you can see private pointcuts in the same type, protected pointcuts
hierarchy, public pointcuts anywhere, and so on). Visibility does not affect pointcut
matching.
-##### [](#aop-common-pointcuts)Sharing Common Pointcut Definitions #####
+##### Sharing Common Pointcut Definitions
When working with enterprise applications, developers often want to refer to modules of
the application and particular sets of operations from within several aspects. We
@@ -15543,7 +15087,7 @@ write the following:
The `` and `` elements are discussed in [Schema-based AOP Support](#aop-schema). The
transaction elements are discussed in [Transaction Management](data-access.html#transaction).
-##### [](#aop-pointcuts-examples)Examples #####
+##### Examples
Spring AOP users are likely to use the `execution` pointcut designator the most often.
The format of an execution expression follows:
@@ -15695,7 +15239,7 @@ The following examples show some common pointcut expressions:
bean(*Service)
```
-##### [](#writing-good-pointcuts)Writing Good Pointcuts #####
+##### Writing Good Pointcuts
During compilation, AspectJ processes pointcuts in order to optimize matching
performance. Examining code and determining if each join point matches (statically or
@@ -15730,13 +15274,13 @@ designators are very fast to match, and using them means AspectJ can very quickl
dismiss groups of join points that should not be further processed. A good
pointcut should always include one if possible.
-#### [](#aop-advice)5.4.4. Declaring Advice ####
+#### 5.4.4. Declaring Advice
Advice is associated with a pointcut expression and runs before, after, or around
method executions matched by the pointcut. The pointcut expression may be either a
simple reference to a named pointcut or a pointcut expression declared in place.
-##### [](#aop-advice-before)Before Advice #####
+##### Before Advice
You can declare before advice in an aspect by using the `@Before` annotation:
@@ -15807,7 +15351,7 @@ class BeforeExample {
}
```
-##### [](#aop-advice-after-returning)After Returning Advice #####
+##### After Returning Advice
After returning advice runs when a matched method execution returns normally.
You can declare it by using the `@AfterReturning` annotation:
@@ -15896,7 +15440,7 @@ 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.
-##### [](#aop-advice-after-throwing)After Throwing Advice #####
+##### After Throwing Advice
After throwing advice runs when a matched method execution exits by throwing an
exception. You can declare it by using the `@AfterThrowing` annotation, as the
@@ -15984,7 +15528,7 @@ specified type (`DataAccessException`, in this case).
| |Note that `@AfterThrowing` does not indicate a general exception handling callback. Specifically, an `@AfterThrowing` advice method is only supposed to receive exceptions from the join point (user-declared target method) itself but not from an accompanying`@After`/`@AfterReturning` method.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#aop-advice-after-finally)After (Finally) Advice #####
+##### Advice
After (finally) advice runs when a matched method execution exits. It is declared by
using the `@After` annotation. After advice must be prepared to handle both normal and
@@ -16026,7 +15570,7 @@ class AfterFinallyExample {
| |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.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#aop-ataspectj-around-advice)Around Advice #####
+##### 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
@@ -16100,7 +15644,7 @@ class AroundExample {
}
```
-##### [](#aop-ataspectj-advice-params)Advice Parameters #####
+##### 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
@@ -16108,7 +15652,7 @@ work with `Object[]` arrays all the time. We see how to make argument and other
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.
-###### [](#aop-ataspectj-advice-params-the-joinpoint)Access to the Current `JoinPoint` ######
+###### Access to the Current `JoinPoint`
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`.
@@ -16127,7 +15671,7 @@ The `JoinPoint` interface provides a number of useful methods:
See the [javadoc](https://www.eclipse.org/aspectj/doc/released/runtime-api/org/aspectj/lang/JoinPoint.html) for more detail.
-###### [](#aop-ataspectj-advice-params-passing)Passing Parameters to Advice ######
+###### Passing Parameters to Advice
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
@@ -16235,7 +15779,7 @@ fun audit(auditable: Auditable) {
}
```
-###### [](#aop-ataspectj-advice-params-generics)Advice Parameters and Generics ######
+###### Advice Parameters and Generics
Spring AOP can handle generics used in class declarations and method parameters. Suppose
you have a generic type like the following:
@@ -16305,7 +15849,7 @@ reasonable, as we also cannot decide how to treat `null` values in general. To a
something similar to this, you have to type the parameter to `Collection>` and manually
check the type of the elements.
-###### [](#aop-ataspectj-advice-params-names)Determining Argument Names ######
+###### Determining Argument Names
The parameter binding in advice invocations relies on matching names used in pointcut
expressions to declared parameter names in advice and pointcut method signatures.
@@ -16409,7 +15953,7 @@ fun audit(jp: JoinPoint) {
* If all of the above strategies fail, an `IllegalArgumentException` is thrown.
-###### [](#aop-ataspectj-advice-proceeding-with-the-call)Proceeding with Arguments ######
+###### Proceeding with Arguments
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
@@ -16444,7 +15988,7 @@ fun preProcessQueryPattern(pjp: ProceedingJoinPoint,
In many cases, you do this binding anyway (as in the preceding example).
-##### [](#aop-ataspectj-advice-ordering)Advice Ordering #####
+##### 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
@@ -16464,7 +16008,7 @@ 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`.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#aop-introductions)5.4.5. Introductions ####
+#### 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
@@ -16528,7 +16072,7 @@ Kotlin
val usageTracked = context.getBean("myService") as UsageTracked
```
-#### [](#aop-instantiation-models)5.4.6. Aspect Instantiation Models ####
+#### 5.4.6. Aspect Instantiation Models
| |This is an advanced topic. If you are just starting out with AOP, you can safely skip it until later.|
|---|---------------------------------------------------------------------------------------------------------|
@@ -16583,7 +16127,7 @@ 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.
-#### [](#aop-ataspectj-example)5.4.7. An AOP Example ####
+#### 5.4.7. An AOP Example
Now that you have seen how all the constituent parts work, we can put them together to do
something useful.
@@ -16741,7 +16285,7 @@ fun doConcurrentOperation(pjp: ProceedingJoinPoint): Any {
}
```
-### [](#aop-schema)5.5. Schema-based AOP Support ###
+### 5.5. Schema-based AOP Support
If you prefer an XML-based format, Spring also offers support for defining aspects
using the `aop` namespace tags. The exact same pointcut expressions and advice kinds
@@ -16760,7 +16304,7 @@ advisor, and aspect elements (note that these must be declared in that order).
| |The `` style of configuration makes heavy use of Spring’s[auto-proxying](#aop-autoproxy) mechanism. This can cause issues (such as advice not being woven) if you already use explicit auto-proxying through the use of`BeanNameAutoProxyCreator` or something similar. The recommended usage pattern is to use either only the `` style or only the `AutoProxyCreator` style and never mix them.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#aop-schema-declaring-an-aspect)5.5.1. Declaring an Aspect ####
+#### 5.5.1. Declaring an Aspect
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
@@ -16784,7 +16328,7 @@ by using the `ref` attribute, as the following example shows:
The bean that backs the aspect (`aBean` in this case) can of course be configured and
dependency injected just like any other Spring bean.
-#### [](#aop-schema-pointcuts)5.5.2. Declaring a Pointcut ####
+#### 5.5.2. Declaring a Pointcut
You can declare a named pointcut inside an `` element, letting the pointcut
definition be shared across several aspects and advisors.
@@ -16897,12 +16441,12 @@ used as named pointcuts to form composite pointcuts. The named pointcut support
schema-based definition style is thus more limited than that offered by the @AspectJ
style.
-#### [](#aop-schema-advice)5.5.3. Declaring Advice ####
+#### 5.5.3. Declaring Advice
The schema-based AOP support uses the same five kinds of advice as the @AspectJ style, and they have
exactly the same semantics.
-##### [](#aop-schema-advice-before)Before Advice #####
+##### Before Advice
Before advice runs before a matched method execution. It is declared inside an`` by using the `` element, as the following example shows:
@@ -16942,7 +16486,7 @@ that contains the advice. Before a data access operation is performed (a method
join point matched by the pointcut expression), the `doAccessCheck` method on the aspect
bean is invoked.
-##### [](#aop-schema-advice-after-returning)After Returning Advice #####
+##### After Returning Advice
After returning advice runs when a matched method execution completes normally. It is
declared inside an `` in the same way as before advice. The following example
@@ -16991,7 +16535,7 @@ Kotlin
fun doAccessCheck(retVal: Any) {...
```
-##### [](#aop-schema-advice-after-throwing)After Throwing Advice #####
+##### After Throwing Advice
After throwing advice runs when a matched method execution exits by throwing an
exception. It is declared inside an `` by using the `after-throwing` element,
@@ -17039,7 +16583,7 @@ Kotlin
fun doRecoveryActions(dataAccessEx: DataAccessException) {...
```
-##### [](#aop-schema-advice-after-finally)After (Finally) Advice #####
+##### After (Finally) Advice
After (finally) advice runs no matter how a matched method execution exits.
You can declare it by using the `after` element, as the following example shows:
@@ -17055,7 +16599,7 @@ You can declare it by using the `after` element, as the following example shows:
```
-##### [](#aop-schema-advice-around)Around Advice #####
+##### 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
@@ -17113,7 +16657,7 @@ fun doBasicProfiling(pjp: ProceedingJoinPoint): Any {
}
```
-##### [](#aop-schema-params)Advice Parameters #####
+##### 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
@@ -17290,7 +16834,7 @@ ms % Task name
00000 ? execution(getFoo)
```
-##### [](#aop-ordering)Advice Ordering #####
+##### 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](#aop-ataspectj-advice-ordering). The precedence
@@ -17301,7 +16845,7 @@ 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 `` 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 `` element, from highest to lowest precedence.
For example, given an `around` advice and a `before` advice defined in the same`` element that apply to the same join point, to ensure that the `around`advice has higher precedence than the `before` advice, the `` element must be declared before the `` element.
As a general rule of thumb, if you find that you have multiple pieces of advice defined in the same `` element that apply to the same join point, consider collapsing such advice methods into one advice method per join point in each `` element or refactor the pieces of advice into separate `` elements that you can order at the aspect level.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#aop-schema-introductions)5.5.4. Introductions ####
+#### 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
@@ -17366,12 +16910,12 @@ Kotlin
val usageTracked = context.getBean("myService") as UsageTracked
```
-#### [](#aop-schema-instatiation-models)5.5.5. Aspect Instantiation Models ####
+#### 5.5.5. Aspect Instantiation Models
The only supported instantiation model for schema-defined aspects is the singleton
model. Other instantiation models may be supported in future releases.
-#### [](#aop-schema-advisors)5.5.6. Advisors ####
+#### 5.5.6. Advisors
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
@@ -17406,7 +16950,7 @@ As well as the `pointcut-ref` attribute used in the preceding example, you can a
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.
-#### [](#aop-schema-example)5.5.7. An AOP Schema Example ####
+#### 5.5.7. An AOP Schema Example
This section shows how the concurrent locking failure retry example from[An AOP Example](#aop-ataspectj-example) looks when rewritten with the schema support.
@@ -17568,7 +17112,7 @@ pointcut expression so that only `@Idempotent` operations match, as follows:
@annotation(com.xyz.myapp.service.Idempotent)"/>
```
-### [](#aop-choosing)5.6. Choosing which AOP Declaration Style to Use ###
+### 5.6. Choosing which AOP Declaration Style to Use
Once you have decided that an aspect is the best approach for implementing a given
requirement, how do you decide between using Spring AOP or AspectJ and between the
@@ -17576,7 +17120,7 @@ Aspect language (code) style, the @AspectJ annotation style, or the Spring XML s
decisions are influenced by a number of factors including application requirements,
development tools, and team familiarity with AOP.
-#### [](#aop-spring-or-aspectj)5.6.1. Spring AOP or Full AspectJ? ####
+#### 5.6.1. Spring AOP or Full AspectJ?
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
@@ -17597,7 +17141,7 @@ that do not play a major role in your application, you may want to consider usin
the @AspectJ style, sticking with regular Java compilation in your IDE, and adding
an aspect weaving phase to your build script.
-#### [](#aop-ataspectj-or-xml)5.6.2. @AspectJ or XML for Spring AOP? ####
+#### 5.6.2. @AspectJ or XML for Spring AOP?
If you have chosen to use Spring AOP, you have a choice of @AspectJ or XML style.
There are various tradeoffs to consider.
@@ -17665,14 +17209,14 @@ to implement additional requirements, you can easily migrate to a classic Aspect
On balance, the Spring team prefers the @AspectJ style for custom aspects beyond simple
configuration of enterprise services.
-### [](#aop-mixing-styles)5.7. Mixing Aspect Types ###
+### 5.7. Mixing Aspect Types
It is perfectly possible to mix @AspectJ style aspects by using the auto-proxying support,
schema-defined `` aspects, `` declared advisors, and even proxies
and interceptors in other styles in the same configuration. All of these are implemented
by using the same underlying support mechanism and can co-exist without any difficulty.
-### [](#aop-proxying)5.8. Proxying Mechanisms ###
+### 5.8. Proxying Mechanisms
Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given
target object. JDK dynamic proxies are built into the JDK, whereas CGLIB is a common
@@ -17713,7 +17257,7 @@ as follows:
| |Multiple `` sections are collapsed into a single unified auto-proxy creator at runtime, which applies the *strongest* proxy settings that any of the`` sections (typically from different XML bean definition files) specified. This also applies to the `` and ``elements.
To be clear, using `proxy-target-class="true"` on ``,``, or `` elements forces the use of CGLIB proxies *for all three of them*.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#aop-understanding-aop-proxies)5.8.1. Understanding AOP Proxies ####
+#### 5.8.1. Understanding AOP Proxies
Spring AOP is proxy-based. It is vitally important that you grasp the semantics of
what that last statement actually means before you write your own aspects or use any of
@@ -17908,7 +17452,7 @@ fun main() {
Finally, it must be noted that AspectJ does not have this self-invocation issue because
it is not a proxy-based AOP framework.
-### [](#aop-aspectj-programmatic)5.9. Programmatic Creation of @AspectJ Proxies ###
+### 5.9. Programmatic Creation of @AspectJ Proxies
In addition to declaring aspects in your configuration by using either ``or ``, it is also possible to programmatically create proxies
that advise target objects. For the full details of Spring’s AOP API, see the[next chapter](#aop-api). Here, we want to focus on the ability to automatically
@@ -17954,7 +17498,7 @@ val proxy = factory.getProxy()
See the [javadoc](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.html) for more information.
-### [](#aop-using-aspectj)5.10. Using AspectJ with Spring Applications ###
+### 5.10. Using AspectJ with Spring Applications
Everything we have covered so far in this chapter is pure Spring AOP. In this section,
we look at how you can use the AspectJ compiler or weaver instead of or in
@@ -17968,7 +17512,7 @@ content of this library and how you can use it. [Configuring AspectJ Aspects by
dependency inject AspectJ aspects that are woven using the AspectJ compiler. Finally,[Load-time Weaving with AspectJ in the Spring Framework](#aop-aj-ltw) provides an introduction to load-time weaving for Spring applications
that use AspectJ.
-#### [](#aop-atconfigurable)5.10.1. Using AspectJ to Dependency Inject Domain Objects with Spring ####
+#### 5.10.1. Using AspectJ to Dependency Inject Domain Objects with Spring
The Spring container instantiates and configures beans defined in your application
context. It is also possible to ask a bean factory to configure a pre-existing
@@ -18122,7 +17666,7 @@ configuration aspect. The following example shows how to use the `depends-on` at
| |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 `@Configurable` on bean classes that are registered as regular Spring beans with the container. Doing so results in double initialization, once through the container and once through the aspect.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#aop-configurable-testing)Unit Testing `@Configurable` Objects #####
+##### Unit Testing `@Configurable` Objects
One of the goals of the `@Configurable` support is to enable independent unit testing
of domain objects without the difficulties associated with hard-coded lookups.
@@ -18133,7 +17677,7 @@ you can still unit test outside of the container as normal, but you see a warnin
message each time that you construct a `@Configurable` object indicating that it has
not been configured by Spring.
-##### [](#aop-configurable-container)Working with Multiple Application Contexts #####
+##### Working with Multiple Application Contexts
The `AnnotationBeanConfigurerAspect` that is used to implement the `@Configurable` support
is an AspectJ singleton aspect. The scope of a singleton aspect is the same as the scope
@@ -18159,7 +17703,7 @@ web application loads the types in `spring-aspects.jar` by using its own classlo
classloader), all web applications share the same aspect instance (which is probably
not what you want).
-#### [](#aop-ajlib-other)5.10.2. Other Spring aspects for AspectJ ####
+#### 5.10.2. Other Spring aspects for AspectJ
In addition to the `@Configurable` aspect, `spring-aspects.jar` contains an AspectJ
aspect that you can use to drive Spring’s transaction management for types and methods
@@ -18204,7 +17748,7 @@ public aspect DomainObjectConfiguration extends AbstractBeanConfigurerAspect {
}
```
-#### [](#aop-aj-configure)5.10.3. Configuring AspectJ Aspects by Using Spring IoC ####
+#### 5.10.3. Configuring AspectJ Aspects by Using Spring IoC
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
@@ -18252,7 +17796,7 @@ configuration. The following example shows how to use `` elements:
| |Do not be misled by the name of the `` element. Using it results in the creation of Spring AOP proxies. The @AspectJ style of aspect declaration is being used here, but the AspectJ runtime is not involved.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#aop-aj-ltw)5.10.4. Load-time Weaving with AspectJ in the Spring Framework ####
+#### 5.10.4. Load-time Weaving with AspectJ in the Spring Framework
Load-time weaving (LTW) refers to the process of weaving AspectJ aspects into an
application’s class files as they are being loaded into the Java virtual machine (JVM).
@@ -18282,7 +17826,7 @@ Now that the sales pitch is over, let us first walk through a quick example of A
LTW that uses Spring, followed by detailed specifics about elements introduced in the
example. For a complete example, see the[Petclinic sample application](https://github.com/spring-projects/spring-petclinic).
-##### [](#aop-aj-ltw-first-example)A First Example #####
+##### 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
@@ -18534,21 +18078,21 @@ the “why” behind each bit of configuration and usage in detail.
| |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.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#aop-aj-ltw-the-aspects)Aspects #####
+##### 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.
-##### [](#aop-aj-ltw-aop_dot_xml)'META-INF/aop.xml' #####
+##### '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](https://www.eclipse.org/aspectj/doc/released/devguide/ltw-configuration.html). Because the `aop.xml` file is 100% AspectJ, we do not describe it further here.
-##### [](#aop-aj-ltw-libraries)Required libraries (JARS) #####
+##### Required libraries (JARS)
At minimum, you need the following libraries to use the Spring Framework’s support
for AspectJ LTW:
@@ -18562,7 +18106,7 @@ instrumentation](#aop-aj-ltw-environments-generic), you also need:
* `spring-instrument.jar`
-##### [](#aop-aj-ltw-spring)Spring Configuration #####
+##### 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
@@ -18702,13 +18246,13 @@ possible values:
| `DISABLED` | `off` | LTW is off. No aspect is woven at load-time. |
| `AUTODETECT` |`autodetect`|If the Spring LTW infrastructure can find at least one `META-INF/aop.xml` file, then AspectJ weaving is on. Otherwise, it is off. This is the default value.|
-##### [](#aop-aj-ltw-environments)Environment-specific Configuration #####
+##### Environment-specific Configuration
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.
-###### [](#aop-aj-ltw-environments-tomcat-jboss-etc)Tomcat, JBoss, WebSphere, WebLogic ######
+###### Tomcat, JBoss, WebSphere, WebLogic
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
@@ -18724,7 +18268,7 @@ to your artifact a file named `WEB-INF/jboss-scanning.xml` with the following co
```
-###### [](#aop-aj-ltw-environments-generic)Generic Java Applications ######
+###### Generic Java Applications
When class instrumentation is required in environments that are not supported by
specific `LoadTimeWeaver` implementations, a JVM agent is the general solution.
@@ -18744,7 +18288,7 @@ from using this in application server environments (depending on your server and
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.
-### [](#aop-resources)5.11. Further Resources ###
+### 5.11. Further Resources
More information on AspectJ can be found on the [AspectJ website](https://www.eclipse.org/aspectj).
@@ -18755,19 +18299,18 @@ comprehensive introduction and reference for the AspectJ language.
recommended. The focus of the book is on AspectJ, but a lot of general AOP themes are
explored (in some depth).
-[](#aop-api)6. Spring AOP APIs
-----------
+## 6. Spring AOP APIs
The previous chapter described the Spring’s support for AOP with @AspectJ and schema-based
aspect definitions. In this chapter, we discuss the lower-level Spring AOP APIs. For common
applications, we recommend the use of Spring AOP with AspectJ pointcuts as described in the
previous chapter.
-### [](#aop-api-pointcuts)6.1. Pointcut API in Spring ###
+### 6.1. Pointcut API in Spring
This section describes how Spring handles the crucial pointcut concept.
-#### [](#aop-api-concepts)6.1.1. Concepts ####
+#### 6.1.1. Concepts
Spring’s pointcut model enables pointcut reuse independent of advice types. You can
target different advice with the same pointcut.
@@ -18825,7 +18368,7 @@ returns `false`. In this case, the three-argument `matches` method is never invo
| |If possible, try to make pointcuts static, allowing the AOP framework to cache the results of pointcut evaluation when an AOP proxy is created.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#aop-api-pointcut-ops)6.1.2. Operations on Pointcuts ####
+#### 6.1.2. Operations on Pointcuts
Spring supports operations (notably, union and intersection) on pointcuts.
@@ -18835,19 +18378,19 @@ Union is usually more useful.
You can compose pointcuts by using the static methods in the`org.springframework.aop.support.Pointcuts` class or by using the`ComposablePointcut` class in the same package. However, using AspectJ pointcut
expressions is usually a simpler approach.
-#### [](#aop-api-pointcuts-aspectj)6.1.3. AspectJ Expression Pointcuts ####
+#### 6.1.3. AspectJ Expression Pointcuts
Since 2.0, the most important type of pointcut used by Spring is`org.springframework.aop.aspectj.AspectJExpressionPointcut`. This is a pointcut that
uses an AspectJ-supplied library to parse an AspectJ pointcut expression string.
See the [previous chapter](#aop) for a discussion of supported AspectJ pointcut primitives.
-#### [](#aop-api-pointcuts-impls)6.1.4. Convenience Pointcut Implementations ####
+#### 6.1.4. Convenience Pointcut Implementations
Spring provides several convenient pointcut implementations. You can use some of them
directly; others are intended to be subclassed in application-specific pointcuts.
-##### [](#aop-api-pointcuts-static)Static 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.
@@ -18857,7 +18400,7 @@ After that, there is no need to evaluate the pointcut again with each method inv
The rest of this section describes some of the static pointcut implementations that are
included with Spring.
-###### [](#aop-api-pointcuts-regex)Regular Expression Pointcuts ######
+###### Regular Expression Pointcuts
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
@@ -18904,12 +18447,12 @@ pointcut and advice, as the following example shows:
You can use `RegexpMethodPointcutAdvisor` with any `Advice` type.
-###### [](#aop-api-pointcuts-attribute-driven)Attribute-driven Pointcuts ######
+###### Attribute-driven Pointcuts
An important type of static pointcut is a metadata-driven pointcut. This uses the
values of metadata attributes (typically, source-level metadata).
-##### [](#aop-api-pointcuts-dynamic)Dynamic 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
@@ -18918,7 +18461,7 @@ vary.
The main example is the `control flow` pointcut.
-###### [](#aop-api-pointcuts-cflow)Control Flow Pointcuts ######
+###### Control Flow Pointcuts
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
@@ -18930,7 +18473,7 @@ are specified by using the `org.springframework.aop.support.ControlFlowPointcut`
| |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.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#aop-api-pointcuts-superclasses)6.1.5. Pointcut Superclasses ####
+#### 6.1.5. Pointcut Superclasses
Spring provides useful pointcut superclasses to help you to implement your own pointcuts.
@@ -18963,7 +18506,7 @@ class TestStaticPointcut : StaticMethodMatcherPointcut() {
There are also superclasses for dynamic pointcuts.
You can use custom pointcuts with any advice type.
-#### [](#aop-api-pointcuts-custom)6.1.6. Custom Pointcuts ####
+#### 6.1.6. Custom Pointcuts
Because pointcuts in Spring AOP are Java classes rather than language features (as in
AspectJ), you can declare custom pointcuts, whether static or dynamic. Custom
@@ -18973,11 +18516,11 @@ expression language, if you can.
| |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.”|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#aop-api-advice)6.2. Advice API in Spring ###
+### 6.2. Advice API in Spring
Now we can examine how Spring AOP handles advice.
-#### [](#aop-api-advice-lifecycle)6.2.1. Advice Lifecycles ####
+#### 6.2.1. Advice Lifecycles
Each advice is a Spring bean. An advice instance can be shared across all advised
objects or be unique to each advised object. This corresponds to per-class or
@@ -18992,12 +18535,12 @@ the advice adds state to the proxied object.
You can use a mix of shared and per-instance advice in the same AOP proxy.
-#### [](#aop-api-advice-types)6.2.2. Advice Types in Spring ####
+#### 6.2.2. Advice Types in Spring
Spring provides several advice types and is extensible to support
arbitrary advice types. This section describes the basic concepts and standard advice types.
-##### [](#aop-api-advice-around)Interception Around Advice #####
+##### Interception Around Advice
The most fundamental advice type in Spring is interception around advice.
@@ -19055,7 +18598,7 @@ However, you do not want to do this without good reason.
| |`MethodInterceptor` implementations offer interoperability with other AOP Alliance-compliant AOP implementations. The other advice types discussed in the remainder of this section implement common AOP concepts but in a Spring-specific way. While there is an advantage in using the most specific advice type, stick with `MethodInterceptor` around advice if you are likely to want to run the aspect in another AOP framework. Note that pointcuts are not currently interoperable between frameworks, and the AOP Alliance does not currently define pointcut interfaces.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#aop-api-advice-before)Before Advice #####
+##### 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.
@@ -19117,7 +18660,7 @@ class CountingBeforeAdvice : MethodBeforeAdvice {
| |Before advice can be used with any pointcut.|
|---|--------------------------------------------|
-##### [](#aop-api-advice-throws)Throws Advice #####
+##### Throws Advice
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
@@ -19222,7 +18765,7 @@ class CombinedThrowsAdvice : ThrowsAdvice {
| |Throws advice can be used with any pointcut.|
|---|--------------------------------------------|
-##### [](#aop-api-advice-after-returning)After Returning Advice #####
+##### After Returning Advice
An after returning advice in Spring must implement the`org.springframework.aop.AfterReturningAdvice` interface, which the following listing shows:
@@ -19278,7 +18821,7 @@ thrown up the interceptor chain instead of the return value.
| |After returning advice can be used with any pointcut.|
|---|-----------------------------------------------------|
-##### [](#aop-api-advice-introduction)Introduction Advice #####
+##### Introduction Advice
Spring treats introduction advice as a special kind of interception advice.
@@ -19469,7 +19012,7 @@ We can apply this advisor programmatically by using the `Advised.addAdvisor()` m
choices discussed below, including “auto proxy creators,” correctly handle introductions
and stateful mixins.
-### [](#aop-api-advisor)6.3. The Advisor API in Spring ###
+### 6.3. The Advisor API in Spring
In Spring, an Advisor is an aspect that contains only a single advice object associated
with a pointcut expression.
@@ -19482,7 +19025,7 @@ example, you could use an interception around advice, throws advice, and before
one proxy configuration. Spring automatically creates the necessary interceptor
chain.
-### [](#aop-pfb)6.4. Using the `ProxyFactoryBean` to Create AOP Proxies ###
+### 6.4. Using the `ProxyFactoryBean` to Create AOP Proxies
If you use the Spring IoC container (an `ApplicationContext` or `BeanFactory`) for your
business objects (and you should be!), you want to use one of Spring’s AOP`FactoryBean` implementations. (Remember that a factory bean introduces a layer of indirection, letting
@@ -19495,7 +19038,7 @@ The basic way to create an AOP proxy in Spring is to use the`org.springframework
the pointcuts, any advice that applies, and their ordering. However, there are simpler
options that are preferable if you do not need such control.
-#### [](#aop-pfb-1)6.4.1. Basics ####
+#### 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
@@ -19510,7 +19053,7 @@ achieve with other AOP frameworks. For example, an advice may itself reference
application objects (besides the target, which should be available in any AOP
framework), benefiting from all the pluggability provided by Dependency Injection.
-#### [](#aop-pfb-2)6.4.2. JavaBean Properties ####
+#### 6.4.2. JavaBean Properties
In common with most `FactoryBean` implementations provided with Spring, the`ProxyFactoryBean` class is itself a JavaBean. Its properties are used to:
@@ -19559,7 +19102,7 @@ Other properties specific to `ProxyFactoryBean` include the following:
such a method. The default value is `true`. If you want to use stateful advice - for
example, for stateful mixins - use prototype advices along with a singleton value of`false`.
-#### [](#aop-pfb-proxy-types)6.4.3. JDK- and CGLIB-based proxies ####
+#### 6.4.3. JDK- and CGLIB-based proxies
This section serves as the definitive documentation on how the `ProxyFactoryBean`chooses to create either a JDK-based proxy or a CGLIB-based proxy for a particular target
object (which is to be proxied).
@@ -19599,7 +19142,7 @@ 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.
-#### [](#aop-api-proxying-intf)6.4.4. Proxying Interfaces ####
+#### 6.4.4. Proxying Interfaces
Consider a simple example of `ProxyFactoryBean` in action. This example involves:
@@ -19713,7 +19256,7 @@ arguably, an advantage in that the `ProxyFactoryBean` definition is self-contain
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).
-#### [](#aop-api-proxying-class)6.4.5. Proxying Classes ####
+#### 6.4.5. Proxying Classes
What if you need to proxy a class, rather than one or more interfaces?
@@ -19744,7 +19287,7 @@ to consider:
There is little performance difference between CGLIB proxying and dynamic proxies.
Performance should not be a decisive consideration in this case.
-#### [](#aop-global-advisors)6.4.6. Using “Global” Advisors ####
+#### 6.4.6. Using “Global” Advisors
By appending an asterisk to an interceptor name, all advisors with bean names that match
the part before the asterisk are added to the advisor chain. This can come in handy
@@ -19765,7 +19308,7 @@ two global advisors:
```
-### [](#aop-concise-proxy)6.5. Concise Proxy Definitions ###
+### 6.5. Concise Proxy Definitions
Especially when defining transactional proxies, you may end up with many similar proxy
definitions. The use of parent and child bean definitions, along with inner bean
@@ -19827,7 +19370,7 @@ that, if you have a (parent) bean definition that you intend to use only as a te
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.
-### [](#aop-prog)6.6. Creating AOP Proxies Programmatically with the `ProxyFactory` ###
+### 6.6. Creating AOP Proxies Programmatically with the `ProxyFactory`
It is easy to create AOP proxies programmatically with Spring. This lets you use
Spring AOP without dependency on Spring IoC.
@@ -19868,7 +19411,7 @@ that let you add other advice types, such as before and throws advice.`AdvisedSu
| |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.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#aop-api-advised)6.7. Manipulating Advised Objects ###
+### 6.7. Manipulating Advised Objects
However you create AOP proxies, you can manipulate them BY using the`org.springframework.aop.framework.Advised` interface. Any AOP proxy can be cast to this
interface, no matter which other interfaces it implements. This interface includes the
@@ -19995,7 +19538,7 @@ advice through addition or removal results in an `AopConfigException`. The abili
to freeze the state of an advised object is useful in some cases (for example, to
prevent calling code removing a security interceptor).
-### [](#aop-autoproxy)6.8. Using the "auto-proxy" facility ###
+### 6.8. Using the "auto-proxy" facility
So far, we have considered explicit creation of AOP proxies by using a `ProxyFactoryBean` or
similar factory bean.
@@ -20015,11 +19558,11 @@ There are two ways to do this:
* A special case of auto-proxy creation that deserves to be considered separately:
auto-proxy creation driven by source-level metadata attributes.
-#### [](#aop-autoproxy-choices)6.8.1. Auto-proxy Bean Definitions ####
+#### 6.8.1. Auto-proxy Bean Definitions
This section covers the auto-proxy creators provided by the`org.springframework.aop.framework.autoproxy` package.
-##### [](#aop-api-autoproxy)`BeanNameAutoProxyCreator` #####
+##### `BeanNameAutoProxyCreator`
The `BeanNameAutoProxyCreator` class is a `BeanPostProcessor` that automatically creates
AOP proxies for beans with names that match literal values or wildcards. The following
@@ -20051,7 +19594,7 @@ automatically created by the `BeanNameAutoProxyCreator`. The same advice is appl
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.
-##### [](#aop-api-autoproxy-default)`DefaultAdvisorAutoProxyCreator` #####
+##### `DefaultAdvisorAutoProxyCreator`
A more general and extremely powerful auto-proxy creator is`DefaultAdvisorAutoProxyCreator`. This automagically applies eligible advisors in the
current context, without the need to include specific bean names in the auto-proxy
@@ -20112,7 +19655,7 @@ Advisors can implement the `org.springframework.core.Ordered` interface to ensur
correct ordering if this is an issue. The `TransactionAttributeSourceAdvisor` used in the
preceding example has a configurable order value. The default setting is unordered.
-### [](#aop-targetsource)6.9. Using `TargetSource` Implementations ###
+### 6.9. Using `TargetSource` Implementations
Spring offers the concept of a `TargetSource`, expressed in the`org.springframework.aop.TargetSource` interface. This interface is responsible for
returning the “target object” that implements the join point. The `TargetSource`implementation is asked for a target instance each time the AOP proxy handles a method
@@ -20131,7 +19674,7 @@ The rest of this section describes the standard target sources provided with Spr
| |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.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#aop-ts-swap)6.9.1. Hot-swappable Target Sources ####
+#### 6.9.1. Hot-swappable Target Sources
The `org.springframework.aop.target.HotSwappableTargetSource` exists to let the target
of an AOP proxy be switched while letting callers keep their references to it.
@@ -20176,7 +19719,7 @@ Although this example does not add any advice (it is not necessary to add advice
use a `TargetSource`), any `TargetSource` can be used in conjunction with
arbitrary advice.
-#### [](#aop-ts-pool)6.9.2. Pooling Target Sources ####
+#### 6.9.2. Pooling Target Sources
Using a pooling target source provides a similar programming model to stateless session
EJBs, in which a pool of identical instances is maintained, with method invocations
@@ -20259,7 +19802,7 @@ println("Max pool size is " + conf.maxSize)
Simpler pooling is available by using auto-proxying. You can set the `TargetSource` implementations
used by any auto-proxy creator.
-#### [](#aop-ts-prototype)6.9.3. Prototype Target Sources ####
+#### 6.9.3. Prototype Target Sources
Setting up a “prototype” target source is similar to setting up a pooling `TargetSource`. In this
case, a new instance of the target is created on every method invocation. Although
@@ -20279,7 +19822,7 @@ To do this, you could modify the `poolTargetSource` definition shown earlier as
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.
-#### [](#aop-ts-threadlocal)6.9.4. `ThreadLocal` Target Sources ####
+#### 6.9.4. `ThreadLocal` Target Sources
`ThreadLocal` target sources are useful if you need an object to be created for each
incoming request (per thread that is). The concept of a `ThreadLocal` provides a JDK-wide
@@ -20295,7 +19838,7 @@ of target source, as the following example shows:
| |`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.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#aop-extensibility)6.10. Defining New Advice Types ###
+### 6.10. Defining New Advice Types
Spring AOP is designed to be extensible. While the interception implementation strategy
is presently used internally, it is possible to support arbitrary advice types in
@@ -20308,8 +19851,7 @@ The only constraint on a custom `Advice` type is that it must implement the`org.
See the [`org.springframework.aop.framework.adapter`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/aop/framework/adapter/package-frame.html)javadoc for further information.
-[](#null-safety)7. Null-safety
-----------
+## 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
@@ -20338,7 +19880,7 @@ 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.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#use-cases)7.1. Use cases ###
+### 7.1. Use cases
In addition to providing an explicit declaration for Spring Framework API nullability,
these annotations can be used by an IDE (such as IDEA or Eclipse) to provide useful
@@ -20348,7 +19890,7 @@ They are also used to make Spring API null-safe in Kotlin projects, since Kotlin
supports [null-safety](https://kotlinlang.org/docs/reference/null-safety.html). More details
are available in the [Kotlin support documentation](languages.html#kotlin-null-safety).
-### [](#jsr-305-meta-annotations)7.2. JSR-305 meta-annotations ###
+### 7.2. JSR-305 meta-annotations
Spring annotations are meta-annotated with [JSR 305](https://jcp.org/en/jsr/detail?id=305)annotations (a dormant but wide-spread JSR). JSR-305 meta-annotations let tooling vendors
like IDEA or Kotlin provide null-safety support in a generic way, without having to
@@ -20358,8 +19900,7 @@ It is not necessary nor recommended to add a JSR-305 dependency to the project c
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.
-[](#databuffers)8. Data Buffers and Codecs
-----------
+## 8. Data Buffers and Codecs
Java NIO provides `ByteBuffer` but many libraries build their own byte buffer API on top,
especially for network operations where reusing buffers and/or using direct buffers is
@@ -20376,7 +19917,7 @@ APIs as follows:
* [Codecs](#codecs) decode or encode data buffer streams into higher level objects.
-### [](#databuffers-factory)8.1. `DataBufferFactory` ###
+### 8.1. `DataBufferFactory`
`DataBufferFactory` is used to create data buffers in one of two ways:
@@ -20390,7 +19931,7 @@ Note that WebFlux applications do not create a `DataBufferFactory` directly but
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.
-### [](#databuffers-buffer)8.2. `DataBuffer` ###
+### 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`.
@@ -20407,7 +19948,7 @@ Below is a partial list of benefits:
* Determine the index, or the last index, for a given byte.
-### [](#databuffers-buffer-pooled)8.3. `PooledDataBuffer` ###
+### 8.3. `PooledDataBuffer`
As explained in the Javadoc for[ByteBuffer](https://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html),
byte buffers can be direct or non-direct. Direct buffers may reside outside the Java heap
@@ -20426,7 +19967,7 @@ the memory pool.
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`.
-### [](#databuffers-utils)8.4. `DataBufferUtils` ###
+### 8.4. `DataBufferUtils`
`DataBufferUtils` offers a number of utility methods to operate on data buffers:
@@ -20439,7 +19980,7 @@ to use the convenience methods in `DataBufferUtils` that apply release or retain
* Skip or take from a stream of bytes until a specific byte count.
-### [](#codecs)8.5. Codecs ###
+### 8.5. Codecs
The `org.springframework.core.codec` package provides the following strategy interfaces:
@@ -20450,7 +19991,7 @@ The `org.springframework.core.codec` package provides the following strategy int
The `spring-core` module provides `byte[]`, `ByteBuffer`, `DataBuffer`, `Resource`, and`String` encoder and decoder implementations. The `spring-web` module adds Jackson JSON,
Jackson Smile, JAXB2, Protocol Buffers and other encoders and decoders. See[Codecs](web-reactive.html#webflux-codecs) in the WebFlux section.
-### [](#databuffers-using)8.6. Using `DataBuffer` ###
+### 8.6. Using `DataBuffer`
When working with data buffers, special care must be taken to ensure buffers are released
since they may be [pooled](#databuffers-buffer-pooled). We’ll use codecs to illustrate
@@ -20518,8 +20059,7 @@ responsibility of the code writing to the server response, or to the client requ
Note that when running on Netty, there are debugging options for[troubleshooting buffer leaks](https://github.com/netty/netty/wiki/Reference-counted-objects#troubleshooting-buffer-leaks).
-[](#spring-jcl)9. Logging
-----------
+## 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
@@ -20555,14 +20095,13 @@ class MyBean {
}
```
-[](#appendix)10. Appendix
-----------
+## 10. Appendix
-### [](#xsd-schemas)10.1. XML Schemas ###
+### 10.1. XML Schemas
This part of the appendix lists XML schemas related to the core container.
-#### [](#xsd-schemas-util)10.1.1. The `util` Schema ####
+#### 10.1.1. The `util` Schema
As the name implies, the `util` tags deal with common, utility configuration
issues, such as configuring collections, referencing constants, and so forth.
@@ -20584,7 +20123,7 @@ correct schema so that the tags in the `util` namespace are available to you):
```
-##### [](#xsd-schemas-util-constant)Using `` #####
+##### Using ``
Consider the following bean definition:
@@ -20613,7 +20152,7 @@ developer’s intent (“inject this constant value”), and it reads better:
```
-###### [](#xsd-schemas-util-frfb)Setting a Bean Property or Constructor Argument from a Field Value ######
+###### Setting a Bean Property or Constructor Argument from a Field Value
[`FieldRetrievingFactoryBean`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/beans/factory/config/FieldRetrievingFactoryBean.html)is a `FactoryBean` that retrieves a `static` or non-static field value. It is typically
used for retrieving `public` `static` `final` constants, which may then be used to set a
@@ -20716,7 +20255,7 @@ class Client {
```
-##### [](#xsd-schemas-util-property-path)Using `` #####
+##### Using ``
Consider the following example:
@@ -20757,7 +20296,7 @@ Now consider the following example, which adds a `` element
The value of the `path` attribute of the `` element follows the form of`beanName.beanProperty`. In this case, it picks up the `age` property of the bean named`testBean`. The value of that `age` property is `10`.
-###### [](#xsd-schemas-util-property-path-dependency)Using `` to Set a Bean Property or Constructor Argument ######
+###### Using `` to Set a Bean Property or Constructor Argument ######
`PropertyPathFactoryBean` is a `FactoryBean` that evaluates a property path on a given
target object. The target object can be specified directly or by a bean name. You can then use this
@@ -20826,7 +20365,7 @@ You can specifically set the result type in the actual definition. This is not n
for most use cases, but it can sometimes be useful. See the javadoc for more info on
this feature.
-##### [](#xsd-schemas-util-properties)Using `` #####
+##### Using ``
Consider the following example:
@@ -20847,7 +20386,7 @@ The following example uses a `util:properties` element to make a more concise re
```
-##### [](#xsd-schemas-util-list)Using `` #####
+##### Using ``
Consider the following example:
@@ -20896,7 +20435,7 @@ following configuration:
If no `list-class` attribute is supplied, the container chooses a `List` implementation.
-##### [](#xsd-schemas-util-map)Using `` #####
+##### Using ``
Consider the following example:
@@ -20945,7 +20484,7 @@ following configuration:
If no `'map-class'` attribute is supplied, the container chooses a `Map` implementation.
-##### [](#xsd-schemas-util-set)Using `` #####
+##### Using ``
Consider the following example:
@@ -20994,7 +20533,7 @@ following configuration:
If no `set-class` attribute is supplied, the container chooses a `Set` implementation.
-#### [](#xsd-schemas-aop)10.1.2. The `aop` Schema ####
+#### 10.1.2. The `aop` Schema
The `aop` tags deal with configuring all things AOP in Spring, including Spring’s
own proxy-based AOP framework and Spring’s integration with the AspectJ AOP framework.
@@ -21019,7 +20558,7 @@ are available to you):
```
-#### [](#xsd-schemas-context)10.1.3. The `context` Schema ####
+#### 10.1.3. The `context` Schema
The `context` tags deal with `ApplicationContext` configuration that relates to plumbing — that is, not usually beans that are important to an end-user but rather beans that do
a lot of the “grunt” work in Spring, such as `BeanfactoryPostProcessors`. The following
@@ -21040,13 +20579,13 @@ available to you:
```
-##### [](#xsd-schemas-context-pphc)Using `` #####
+##### Using ``
This element activates the replacement of `${…}` placeholders, which are resolved against a
specified properties file (as a [Spring resource location](#resources)). This element
is a convenience mechanism that sets up a [`PropertySourcesPlaceholderConfigurer`](#beans-factory-placeholderconfigurer) for you. If you need more control over the specific`PropertySourcesPlaceholderConfigurer` setup, you can explicitly define it as a bean yourself.
-##### [](#xsd-schemas-context-ac)Using `` #####
+##### Using ``
This element activates the Spring infrastructure to detect annotations in bean classes:
@@ -21067,23 +20606,23 @@ Alternatively, you can choose to explicitly activate the individual `BeanPostPro
| |This element does not activate processing of Spring’s[`@Transactional`](data-access.html#transaction-declarative-annotations) annotation; you can use the [``](data-access.html#tx-decl-explained)element for that purpose. Similarly, Spring’s[caching annotations](integration.html#cache-annotations) need to be explicitly[enabled](integration.html#cache-annotation-enable) as well.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-##### [](#xsd-schemas-context-component-scan)Using `` #####
+##### Using ``
This element is detailed in the section on [annotation-based container configuration](#beans-annotation-config).
-##### [](#xsd-schemas-context-ltw)Using `` #####
+##### Using ``
This element is detailed in the section on [load-time weaving with AspectJ in the Spring Framework](#aop-aj-ltw).
-##### [](#xsd-schemas-context-sc)Using `` #####
+##### Using ``
This element is detailed in the section on [using AspectJ to dependency inject domain objects with Spring](#aop-atconfigurable).
-##### [](#xsd-schemas-context-mbe)Using `` #####
+##### Using ``
This element is detailed in the section on [configuring annotation-based MBean export](integration.html#jmx-context-mbeanexport).
-#### [](#xsd-schemas-beans)10.1.4. The Beans Schema ####
+#### 10.1.4. The Beans Schema
Last but not least, we have the elements in the `beans` schema. These elements
have been in Spring since the very dawn of the framework. Examples of the various elements
@@ -21119,7 +20658,7 @@ as it stands).
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-custom)10.2. XML Schema Authoring ###
+### 10.2. XML Schema Authoring
Since version 2.0, Spring has featured a mechanism for adding schema-based extensions to the
basic Spring XML format for defining and configuring beans. This section covers
@@ -21156,7 +20695,7 @@ we will be able to define bean definitions of type `SimpleDateFormat` as follows
examples follow later in this appendix. The intent of this first simple example is to walk you
through the basic steps of making a custom extension.)
-#### [](#xsd-custom-schema)10.2.1. Authoring the Schema ####
+#### 10.2.1. Authoring the Schema
Creating an XML configuration extension for use with Spring’s IoC container starts with
authoring an XML Schema to describe the extension. For our example, we use the following schema
@@ -21217,7 +20756,7 @@ creates a bean in the container (identified by the name `dateFormat` of type`Sim
| |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.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-#### [](#xsd-custom-namespacehandler)10.2.2. Coding a `NamespaceHandler` ####
+#### 10.2.2. Coding a `NamespaceHandler`
In addition to the schema, we need a `NamespaceHandler` to parse all elements of
this specific namespace that Spring encounters while parsing configuration files. For this example, the`NamespaceHandler` should take care of the parsing of the `myns:dateformat`element.
@@ -21283,7 +20822,7 @@ delegating to `BeanDefinitionParsers` to do the grunt work of the XML parsing. T
means that each `BeanDefinitionParser` contains only the logic for parsing a single
custom element, as we can see in the next step.
-#### [](#xsd-custom-parser)10.2.3. Using `BeanDefinitionParser` ####
+#### 10.2.3. Using `BeanDefinitionParser`
A `BeanDefinitionParser` is used if the `NamespaceHandler` encounters an XML
element of the type that has been mapped to the specific bean definition parser
@@ -21368,7 +20907,7 @@ class SimpleDateFormatBeanDefinitionParser : AbstractSingleBeanDefinitionParser(
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.
-#### [](#xsd-custom-registration)10.2.4. Registering the Handler and the Schema ####
+#### 10.2.4. Registering the Handler and the Schema
The coding is finished. All that remains to be done is to make the Spring XML
parsing infrastructure aware of our custom element. We do so by registering our custom`namespaceHandler` and custom XSD file in two special-purpose properties files. These
@@ -21377,7 +20916,7 @@ can, for example, be distributed alongside your binary classes in a JAR file. Th
XML parsing infrastructure automatically picks up your new extension by consuming
these special properties files, the formats of which are detailed in the next two sections.
-##### [](#xsd-custom-registration-spring-handlers)Writing `META-INF/spring.handlers` #####
+##### 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:
@@ -21391,7 +20930,7 @@ http\://www.mycompany.example/schema/myns=org.springframework.samples.xml.MyName
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.
-##### [](#xsd-custom-registration-spring-schemas)Writing 'META-INF/spring.schemas' #####
+##### 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
@@ -21410,7 +20949,7 @@ http\://www.mycompany.example/schema/myns/myns.xsd=org/springframework/samples/x
You are encouraged to deploy your XSD file (or files) right alongside
the `NamespaceHandler` and `BeanDefinitionParser` classes on the classpath.
-#### [](#xsd-custom-using)10.2.5. Using a Custom Extension in Your Spring XML Configuration ####
+#### 10.2.5. Using a Custom Extension in Your Spring XML Configuration
Using a custom extension that you yourself have implemented is no different from using
one of the “custom” extensions that Spring provides. The following
@@ -21442,11 +20981,11 @@ in a Spring XML configuration file:
|**1**|Our custom bean.|
|-----|----------------|
-#### [](#xsd-custom-meat)10.2.6. More Detailed Examples ####
+#### 10.2.6. More Detailed Examples
This section presents some more detailed examples of custom XML extensions.
-##### [](#xsd-custom-custom-nested)Nesting Custom Elements within Custom Elements #####
+##### Nesting Custom Elements within Custom Elements
The example presented in this section shows how you to write the various artifacts required
to satisfy a target of the following configuration:
@@ -21794,7 +21333,7 @@ http\://www.foo.example/schema/component=com.foo.ComponentNamespaceHandler
http\://www.foo.example/schema/component/component.xsd=com/foo/component.xsd
```
-##### [](#xsd-custom-custom-just-attributes)Custom Attributes on “Normal” Elements #####
+##### Custom Attributes on “Normal” Elements
Writing your own custom parser and the associated artifacts is not hard. However,
it is sometimes not the right thing to do. Consider a scenario where you need to
@@ -22025,7 +21564,7 @@ http\://www.foo.example/schema/jcache=com.foo.JCacheNamespaceHandler
http\://www.foo.example/schema/jcache/jcache.xsd=com/foo/jcache.xsd
```
-### [](#application-startup-steps)10.3. Application Startup Steps ###
+### 10.3. Application Startup Steps
This part of the appendix lists the existing `StartupSteps` that the core container is instrumented with.
diff --git a/docs/en/spring-framework/data-access.md b/docs/en/spring-framework/data-access.md
index 9942d6ed44979e9a61731d31ecc165bb8878f094..9b3b5f92b2aac57796fceaa8ee19efbd82032ec1 100644
--- a/docs/en/spring-framework/data-access.md
+++ b/docs/en/spring-framework/data-access.md
@@ -1,218 +1,4 @@
-Data Access
-==========
-
-version 5.3.16
-
-Table of Contents
-
-* [1. Transaction Management](#transaction)
- * [1.1. Advantages of the Spring Framework’s Transaction Support Model](#transaction-motivation)
- * [1.1.1. Global Transactions](#transaction-global)
- * [1.1.2. Local Transactions](#transaction-local)
- * [1.1.3. Spring Framework’s Consistent Programming Model](#transaction-programming-model)
-
- * [1.2. Understanding the Spring Framework Transaction Abstraction](#transaction-strategies)
- * [1.2.1. Hibernate Transaction Setup](#transaction-strategies-hibernate)
-
- * [1.3. Synchronizing Resources with Transactions](#tx-resource-synchronization)
- * [1.3.1. High-level Synchronization Approach](#tx-resource-synchronization-high)
- * [1.3.2. Low-level Synchronization Approach](#tx-resource-synchronization-low)
- * [1.3.3. `TransactionAwareDataSourceProxy`](#tx-resource-synchronization-tadsp)
-
- * [1.4. Declarative Transaction Management](#transaction-declarative)
- * [1.4.1. Understanding the Spring Framework’s Declarative Transaction Implementation](#tx-decl-explained)
- * [1.4.2. Example of Declarative Transaction Implementation](#transaction-declarative-first-example)
- * [1.4.3. Rolling Back a Declarative Transaction](#transaction-declarative-rolling-back)
- * [1.4.4. Configuring Different Transactional Semantics for Different Beans](#transaction-declarative-diff-tx)
- * [1.4.5. \ Settings](#transaction-declarative-txadvice-settings)
- * [1.4.6. Using `@Transactional`](#transaction-declarative-annotations)
- * [`@Transactional` Settings](#transaction-declarative-attransactional-settings)
- * [Multiple Transaction Managers with `@Transactional`](#tx-multiple-tx-mgrs-with-attransactional)
- * [Custom Composed Annotations](#tx-custom-attributes)
-
- * [1.4.7. Transaction Propagation](#tx-propagation)
- * [Understanding `PROPAGATION_REQUIRED`](#tx-propagation-required)
- * [Understanding `PROPAGATION_REQUIRES_NEW`](#tx-propagation-requires_new)
- * [Understanding `PROPAGATION_NESTED`](#tx-propagation-nested)
-
- * [1.4.8. Advising Transactional Operations](#transaction-declarative-applying-more-than-just-tx-advice)
- * [1.4.9. Using `@Transactional` with AspectJ](#transaction-declarative-aspectj)
-
- * [1.5. Programmatic Transaction Management](#transaction-programmatic)
- * [1.5.1. Using the `TransactionTemplate`](#tx-prog-template)
- * [Specifying Transaction Settings](#tx-prog-template-settings)
-
- * [1.5.2. Using the `TransactionOperator`](#tx-prog-operator)
- * [Cancel Signals](#tx-prog-operator-cancel)
- * [Specifying Transaction Settings](#tx-prog-operator-settings)
-
- * [1.5.3. Using the `TransactionManager`](#transaction-programmatic-tm)
- * [Using the `PlatformTransactionManager`](#transaction-programmatic-ptm)
- * [Using the `ReactiveTransactionManager`](#transaction-programmatic-rtm)
-
- * [1.6. Choosing Between Programmatic and Declarative Transaction Management](#tx-decl-vs-prog)
- * [1.7. Transaction-bound Events](#transaction-event)
- * [1.8. Application server-specific integration](#transaction-application-server-integration)
- * [1.8.1. IBM WebSphere](#transaction-application-server-integration-websphere)
- * [1.8.2. Oracle WebLogic Server](#transaction-application-server-integration-weblogic)
-
- * [1.9. Solutions to Common Problems](#transaction-solutions-to-common-problems)
- * [1.9.1. Using the Wrong Transaction Manager for a Specific `DataSource`](#transaction-solutions-to-common-problems-wrong-ptm)
-
- * [1.10. Further Resources](#transaction-resources)
-
-* [2. DAO Support](#dao)
- * [2.1. Consistent Exception Hierarchy](#dao-exceptions)
- * [2.2. Annotations Used to Configure DAO or Repository Classes](#dao-annotations)
-
-* [3. Data Access with JDBC](#jdbc)
- * [3.1. Choosing an Approach for JDBC Database Access](#jdbc-choose-style)
- * [3.2. Package Hierarchy](#jdbc-packages)
- * [3.3. Using the JDBC Core Classes to Control Basic JDBC Processing and Error Handling](#jdbc-core)
- * [3.3.1. Using `JdbcTemplate`](#jdbc-JdbcTemplate)
- * [Querying (`SELECT`)](#jdbc-JdbcTemplate-examples-query)
- * [Updating (`INSERT`, `UPDATE`, and `DELETE`) with `JdbcTemplate`](#jdbc-JdbcTemplate-examples-update)
- * [Other `JdbcTemplate` Operations](#jdbc-JdbcTemplate-examples-other)
- * [`JdbcTemplate` Best Practices](#jdbc-JdbcTemplate-idioms)
-
- * [3.3.2. Using `NamedParameterJdbcTemplate`](#jdbc-NamedParameterJdbcTemplate)
- * [3.3.3. Using `SQLExceptionTranslator`](#jdbc-SQLExceptionTranslator)
- * [3.3.4. Running Statements](#jdbc-statements-executing)
- * [3.3.5. Running Queries](#jdbc-statements-querying)
- * [3.3.6. Updating the Database](#jdbc-updates)
- * [3.3.7. Retrieving Auto-generated Keys](#jdbc-auto-generated-keys)
-
- * [3.4. Controlling Database Connections](#jdbc-connections)
- * [3.4.1. Using `DataSource`](#jdbc-datasource)
- * [3.4.2. Using `DataSourceUtils`](#jdbc-DataSourceUtils)
- * [3.4.3. Implementing `SmartDataSource`](#jdbc-SmartDataSource)
- * [3.4.4. Extending `AbstractDataSource`](#jdbc-AbstractDataSource)
- * [3.4.5. Using `SingleConnectionDataSource`](#jdbc-SingleConnectionDataSource)
- * [3.4.6. Using `DriverManagerDataSource`](#jdbc-DriverManagerDataSource)
- * [3.4.7. Using `TransactionAwareDataSourceProxy`](#jdbc-TransactionAwareDataSourceProxy)
- * [3.4.8. Using `DataSourceTransactionManager`](#jdbc-DataSourceTransactionManager)
-
- * [3.5. JDBC Batch Operations](#jdbc-advanced-jdbc)
- * [3.5.1. Basic Batch Operations with `JdbcTemplate`](#jdbc-batch-classic)
- * [3.5.2. Batch Operations with a List of Objects](#jdbc-batch-list)
- * [3.5.3. Batch Operations with Multiple Batches](#jdbc-batch-multi)
-
- * [3.6. Simplifying JDBC Operations with the `SimpleJdbc` Classes](#jdbc-simple-jdbc)
- * [3.6.1. Inserting Data by Using `SimpleJdbcInsert`](#jdbc-simple-jdbc-insert-1)
- * [3.6.2. Retrieving Auto-generated Keys by Using `SimpleJdbcInsert`](#jdbc-simple-jdbc-insert-2)
- * [3.6.3. Specifying Columns for a `SimpleJdbcInsert`](#jdbc-simple-jdbc-insert-3)
- * [3.6.4. Using `SqlParameterSource` to Provide Parameter Values](#jdbc-simple-jdbc-parameters)
- * [3.6.5. Calling a Stored Procedure with `SimpleJdbcCall`](#jdbc-simple-jdbc-call-1)
- * [3.6.6. Explicitly Declaring Parameters to Use for a `SimpleJdbcCall`](#jdbc-simple-jdbc-call-2)
- * [3.6.7. How to Define `SqlParameters`](#jdbc-params)
- * [3.6.8. Calling a Stored Function by Using `SimpleJdbcCall`](#jdbc-simple-jdbc-call-3)
- * [3.6.9. Returning a `ResultSet` or REF Cursor from a `SimpleJdbcCall`](#jdbc-simple-jdbc-call-4)
-
- * [3.7. Modeling JDBC Operations as Java Objects](#jdbc-object)
- * [3.7.1. Understanding `SqlQuery`](#jdbc-SqlQuery)
- * [3.7.2. Using `MappingSqlQuery`](#jdbc-MappingSqlQuery)
- * [3.7.3. Using `SqlUpdate`](#jdbc-SqlUpdate)
- * [3.7.4. Using `StoredProcedure`](#jdbc-StoredProcedure)
-
- * [3.8. Common Problems with Parameter and Data Value Handling](#jdbc-parameter-handling)
- * [3.8.1. Providing SQL Type Information for Parameters](#jdbc-type-information)
- * [3.8.2. Handling BLOB and CLOB objects](#jdbc-lob)
- * [3.8.3. Passing in Lists of Values for IN Clause](#jdbc-in-clause)
- * [3.8.4. Handling Complex Types for Stored Procedure Calls](#jdbc-complex-types)
-
- * [3.9. Embedded Database Support](#jdbc-embedded-database-support)
- * [3.9.1. Why Use an Embedded Database?](#jdbc-why-embedded-database)
- * [3.9.2. Creating an Embedded Database by Using Spring XML](#jdbc-embedded-database-xml)
- * [3.9.3. Creating an Embedded Database Programmatically](#jdbc-embedded-database-java)
- * [3.9.4. Selecting the Embedded Database Type](#jdbc-embedded-database-types)
- * [Using HSQL](#jdbc-embedded-database-using-HSQL)
- * [Using H2](#jdbc-embedded-database-using-H2)
- * [Using Derby](#jdbc-embedded-database-using-Derby)
-
- * [3.9.5. Testing Data Access Logic with an Embedded Database](#jdbc-embedded-database-dao-testing)
- * [3.9.6. Generating Unique Names for Embedded Databases](#jdbc-embedded-database-unique-names)
- * [3.9.7. Extending the Embedded Database Support](#jdbc-embedded-database-extension)
-
- * [3.10. Initializing a `DataSource`](#jdbc-initializing-datasource)
- * [3.10.1. Initializing a Database by Using Spring XML](#jdbc-initializing-datasource-xml)
- * [Initialization of Other Components that Depend on the Database](#jdbc-client-component-initialization)
-
-* [4. Data Access with R2DBC](#r2dbc)
- * [4.1. Package Hierarchy](#r2dbc-packages)
- * [4.2. Using the R2DBC Core Classes to Control Basic R2DBC Processing and Error Handling](#r2dbc-core)
- * [4.2.1. Using `DatabaseClient`](#r2dbc-DatabaseClient)
- * [Executing Statements](#r2dbc-DatabaseClient-examples-statement)
- * [Querying (`SELECT`)](#r2dbc-DatabaseClient-examples-query)
- * [Updating (`INSERT`, `UPDATE`, and `DELETE`) with `DatabaseClient`](#r2dbc-DatabaseClient-examples-update)
- * [Binding Values to Queries](#r2dbc-DatabaseClient-named-parameters)
- * [Statement Filters](#r2dbc-DatabaseClient-filter)
- * [`DatabaseClient` Best Practices](#r2dbc-DatabaseClient-idioms)
-
- * [4.3. Retrieving Auto-generated Keys](#r2dbc-auto-generated-keys)
- * [4.4. Controlling Database Connections](#r2dbc-connections)
- * [4.4.1. Using `ConnectionFactory`](#r2dbc-ConnectionFactory)
- * [4.4.2. Using `ConnectionFactoryUtils`](#r2dbc-ConnectionFactoryUtils)
- * [4.4.3. Using `SingleConnectionFactory`](#r2dbc-SingleConnectionFactory)
- * [4.4.4. Using `TransactionAwareConnectionFactoryProxy`](#r2dbc-TransactionAwareConnectionFactoryProxy)
- * [4.4.5. Using `R2dbcTransactionManager`](#r2dbc-R2dbcTransactionManager)
-
-* [5. Object Relational Mapping (ORM) Data Access](#orm)
- * [5.1. Introduction to ORM with Spring](#orm-introduction)
- * [5.2. General ORM Integration Considerations](#orm-general)
- * [5.2.1. Resource and Transaction Management](#orm-resource-mngmnt)
- * [5.2.2. Exception Translation](#orm-exception-translation)
-
- * [5.3. Hibernate](#orm-hibernate)
- * [5.3.1. `SessionFactory` Setup in a Spring Container](#orm-session-factory-setup)
- * [5.3.2. Implementing DAOs Based on the Plain Hibernate API](#orm-hibernate-straight)
- * [5.3.3. Declarative Transaction Demarcation](#orm-hibernate-tx-declarative)
- * [5.3.4. Programmatic Transaction Demarcation](#orm-hibernate-tx-programmatic)
- * [5.3.5. Transaction Management Strategies](#orm-hibernate-tx-strategies)
- * [5.3.6. Comparing Container-managed and Locally Defined Resources](#orm-hibernate-resources)
- * [5.3.7. Spurious Application Server Warnings with Hibernate](#orm-hibernate-invalid-jdbc-access-error)
-
- * [5.4. JPA](#orm-jpa)
- * [5.4.1. Three Options for JPA Setup in a Spring Environment](#orm-jpa-setup)
- * [Using `LocalEntityManagerFactoryBean`](#orm-jpa-setup-lemfb)
- * [Obtaining an EntityManagerFactory from JNDI](#orm-jpa-setup-jndi)
- * [Using `LocalContainerEntityManagerFactoryBean`](#orm-jpa-setup-lcemfb)
- * [Dealing with Multiple Persistence Units](#orm-jpa-setup-multiple)
- * [Background Bootstrapping](#orm-jpa-setup-background)
-
- * [5.4.2. Implementing DAOs Based on JPA: `EntityManagerFactory` and `EntityManager`](#orm-jpa-dao)
- * [5.4.3. Spring-driven JPA transactions](#orm-jpa-tx)
- * [5.4.4. Understanding `JpaDialect` and `JpaVendorAdapter`](#orm-jpa-dialect)
- * [5.4.5. Setting up JPA with JTA Transaction Management](#orm-jpa-jta)
- * [5.4.6. Native Hibernate Setup and Native Hibernate Transactions for JPA Interaction](#orm-jpa-hibernate)
-
-* [6. Marshalling XML by Using Object-XML Mappers](#oxm)
- * [6.1. Introduction](#oxm-introduction)
- * [6.1.1. Ease of configuration](#oxm-ease-of-configuration)
- * [6.1.2. Consistent Interfaces](#oxm-consistent-interfaces)
- * [6.1.3. Consistent Exception Hierarchy](#oxm-consistent-exception-hierarchy)
-
- * [6.2. `Marshaller` and `Unmarshaller`](#oxm-marshaller-unmarshaller)
- * [6.2.1. Understanding `Marshaller`](#oxm-marshaller)
- * [6.2.2. Understanding `Unmarshaller`](#oxm-unmarshaller)
- * [6.2.3. Understanding `XmlMappingException`](#oxm-xmlmappingexception)
-
- * [6.3. Using `Marshaller` and `Unmarshaller`](#oxm-usage)
- * [6.4. XML Configuration Namespace](#oxm-schema-based-config)
- * [6.5. JAXB](#oxm-jaxb)
- * [6.5.1. Using `Jaxb2Marshaller`](#oxm-jaxb2)
- * [XML Configuration Namespace](#oxm-jaxb2-xsd)
-
- * [6.6. JiBX](#oxm-jibx)
- * [6.6.1. Using `JibxMarshaller`](#oxm-jibx-marshaller)
- * [XML Configuration Namespace](#oxm-jibx-xsd)
-
- * [6.7. XStream](#oxm-xstream)
- * [6.7.1. Using `XStreamMarshaller`](#oxm-xstream-marshaller)
-
-* [7. Appendix](#appendix)
- * [7.1. XML Schemas](#xsd-schemas)
- * [7.1.1. The `tx` Schema](#xsd-schemas-tx)
- * [7.1.2. The `jdbc` Schema](#xsd-schemas-jdbc)
+# Data Access
This part of the reference documentation is concerned with data access and the
interaction between the data access layer and the business or service layer.
@@ -221,8 +7,7 @@ Spring’s comprehensive transaction management support is covered in some detai
followed by thorough coverage of the various data access frameworks and technologies
with which the Spring Framework integrates.
-[](#transaction)1. Transaction Management
-----------
+## 1. Transaction Management
Comprehensive transaction support is among the most compelling reasons to use the Spring
Framework. The Spring Framework provides a consistent abstraction for transaction
@@ -264,7 +49,7 @@ technologies:
The chapter also includes discussions of best practices,[application server integration](#transaction-application-server-integration),
and [solutions to common problems](#transaction-solutions-to-common-problems).
-### [](#transaction-motivation)1.1. Advantages of the Spring Framework’s Transaction Support Model ###
+### 1.1. Advantages of the Spring Framework’s Transaction Support Model
Traditionally, Java EE developers have had two choices for transaction management:
global or local transactions, both of which have profound limitations. Global
@@ -272,7 +57,7 @@ and local transaction management is reviewed in the next two sections, followed
discussion of how the Spring Framework’s transaction management support addresses the
limitations of the global and local transaction models.
-#### [](#transaction-global)1.1.1. Global Transactions ####
+#### 1.1.1. Global Transactions
Global transactions let you work with multiple transactional resources, typically
relational databases and message queues. The application server manages global
@@ -293,7 +78,7 @@ implement business logic in EJBs (or at least behind a transactional EJB facade)
negatives of EJB in general are so great that this is not an attractive proposition,
especially in the face of compelling alternatives for declarative transaction management.
-#### [](#transaction-local)1.1.2. Local Transactions ####
+#### 1.1.2. Local Transactions
Local transactions are resource-specific, such as a transaction associated with a JDBC
connection. Local transactions may be easier to use but have a significant disadvantage:
@@ -304,7 +89,7 @@ correctness across multiple resources. (It is worth noting that most application
single transaction resource.) Another downside is that local transactions are invasive
to the programming model.
-#### [](#transaction-programming-model)1.1.3. Spring Framework’s Consistent Programming Model ####
+#### 1.1.3. Spring Framework’s Consistent Programming Model
Spring resolves the disadvantages of global and local transactions. It lets
application developers use a consistent programming model in any environment.
@@ -343,7 +128,7 @@ and face a hefty rework if you need that code to run within global, container-ma
transactions. With the Spring Framework, only some of the bean definitions in your
configuration file need to change (rather than your code).
-### [](#transaction-strategies)1.2. Understanding the Spring Framework Transaction Abstraction ###
+### 1.2. Understanding the Spring Framework Transaction Abstraction
The key to the Spring transaction abstraction is the notion of a transaction strategy. A
transaction strategy is defined by a `TransactionManager`, specifically the`org.springframework.transaction.PlatformTransactionManager` interface for imperative
@@ -517,7 +302,7 @@ In all Spring transaction setups, application code does not need to change. You
how transactions are managed merely by changing configuration, even if that change means
moving from local to global transactions or vice versa.
-#### [](#transaction-strategies-hibernate)1.2.1. Hibernate Transaction Setup ####
+#### 1.2.1. Hibernate Transaction Setup
You can also easily use Hibernate local transactions, as shown in the following examples.
In this case, you need to define a Hibernate `LocalSessionFactoryBean`, which your
@@ -599,7 +384,7 @@ Or alternatively, you may pass the `JtaTransactionManager` into your `LocalSessi
```
-### [](#tx-resource-synchronization)1.3. Synchronizing Resources with Transactions ###
+### 1.3. Synchronizing Resources with Transactions
How to create different transaction managers and how they are linked to related resources
that need to be synchronized to transactions (for example `DataSourceTransactionManager`to a JDBC `DataSource`, `HibernateTransactionManager` to a Hibernate `SessionFactory`,
@@ -609,7 +394,7 @@ ensures that these resources are created, reused, and cleaned up properly. The s
also discusses how transaction synchronization is (optionally) triggered through the
relevant `TransactionManager`.
-#### [](#tx-resource-synchronization-high)1.3.1. High-level Synchronization Approach ####
+#### 1.3.1. High-level Synchronization Approach
The preferred approach is to use Spring’s highest-level template-based persistence
integration APIs or to use native ORM APIs with transaction-aware factory beans or
@@ -621,7 +406,7 @@ persistence logic. Generally, you use the native ORM API or take a template appr
for JDBC access by using the `JdbcTemplate`. These solutions are detailed in subsequent
sections of this reference documentation.
-#### [](#tx-resource-synchronization-low)1.3.2. Low-level Synchronization Approach ####
+#### 1.3.2. Low-level Synchronization Approach
Classes such as `DataSourceUtils` (for JDBC), `EntityManagerFactoryUtils` (for JPA),`SessionFactoryUtils` (for Hibernate), and so on exist at a lower level. When you want the
application code to deal directly with the resource types of the native persistence APIs,
@@ -654,7 +439,7 @@ because you are much happier working through the Spring abstraction than directl
with the relevant APIs. For example, if you use the Spring `JdbcTemplate` or`jdbc.object` package to simplify your use of JDBC, correct connection retrieval occurs
behind the scenes and you need not write any special code.
-#### [](#tx-resource-synchronization-tadsp)1.3.3. `TransactionAwareDataSourceProxy` ####
+#### 1.3.3. `TransactionAwareDataSourceProxy`
At the very lowest level exists the `TransactionAwareDataSourceProxy` class. This is a
proxy for a target `DataSource`, which wraps the target `DataSource` to add awareness of
@@ -666,7 +451,7 @@ that case, it is possible that this code is usable but is participating in Sprin
transactions. You can write your new code by using the higher-level
abstractions mentioned earlier.
-### [](#transaction-declarative)1.4. Declarative Transaction Management ###
+### 1.4. Declarative Transaction Management
| |Most Spring Framework users choose declarative transaction management. This option has the least impact on application code and, hence, is most consistent with the ideals of a non-invasive lightweight container.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
@@ -718,7 +503,7 @@ other than `java.rmi.RemoteException`). While the Spring default behavior for
declarative transaction management follows EJB convention (roll back is automatic only
on unchecked exceptions), it is often useful to customize this behavior.
-#### [](#tx-decl-explained)1.4.1. Understanding the Spring Framework’s Declarative Transaction Implementation ####
+#### 1.4.1. Understanding the Spring Framework’s Declarative Transaction Implementation
It is not sufficient merely to tell you to annotate your classes with the`@Transactional` annotation, add `@EnableTransactionManagement` to your configuration,
and expect you to understand how it all works. To provide a deeper understanding, this
@@ -752,7 +537,7 @@ The following image shows a conceptual view of calling a method on a transaction
![tx](images/tx.png)
-#### [](#transaction-declarative-first-example)1.4.2. Example of Declarative Transaction Implementation ####
+#### 1.4.2. Example of Declarative Transaction Implementation
Consider the following interface and its attendant implementation. This example uses`Foo` and `Bar` classes as placeholders so that you can concentrate on the transaction
usage without focusing on a particular domain model. For the purposes of this example,
@@ -1137,7 +922,7 @@ A `Publisher` can emit data while a transaction is ongoing but not necessarily c
Therefore, methods that depend upon successful completion of an entire transaction need
to ensure completion and buffer results in the calling code.
-#### [](#transaction-declarative-rolling-back)1.4.3. Rolling Back a Declarative Transaction ####
+#### 1.4.3. Rolling Back a Declarative Transaction
The previous section outlined the basics of how to specify transactional settings for
classes, typically service layer classes, declaratively in your application. This
@@ -1232,7 +1017,7 @@ You are strongly encouraged to use the declarative approach to rollback, if at a
possible. Programmatic rollback is available should you absolutely need it, but its
usage flies in the face of achieving a clean POJO-based architecture.
-#### [](#transaction-declarative-diff-tx)1.4.4. Configuring Different Transactional Semantics for Different Beans ####
+#### 1.4.4. Configuring Different Transactional Semantics for Different Beans ####
Consider the scenario where you have a number of service layer objects, and you want to
apply a totally different transactional configuration to each of them. You can do so
@@ -1341,7 +1126,7 @@ transactional settings:
```
-#### [](#transaction-declarative-txadvice-settings)1.4.5. \ Settings ####
+#### 1.4.5. \ Settings
This section summarizes the various transactional settings that you can specify by using
the `` tag. The default `` settings are:
@@ -1370,7 +1155,7 @@ that are nested within `` and `` tags:
| `rollback-for` | No | | Comma-delimited list of `Exception` instances that trigger rollback. For example,`com.foo.MyBusinessException,ServletException`. |
|`no-rollback-for`| No | | Comma-delimited list of `Exception` instances that do not trigger rollback. For example,`com.foo.MyBusinessException,ServletException`. |
-#### [](#transaction-declarative-annotations)1.4.6. Using `@Transactional` ####
+#### 1.4.6. Using `@Transactional`
In addition to the XML-based declarative approach to transaction configuration, you can
use an annotation-based approach. Declaring transaction semantics directly in the Java
@@ -1631,7 +1416,7 @@ class DefaultFooService : FooService {
}
```
-##### [](#transaction-declarative-attransactional-settings)`@Transactional` Settings #####
+##### `@Transactional` Settings
The `@Transactional` annotation is metadata that specifies that an interface, class,
or method must have transactional semantics (for example, "start a brand new read-only
@@ -1671,7 +1456,7 @@ means the transaction name that appears in a transaction monitor, if applicable
transactions, the transaction name is always the fully-qualified class name + `.`+ the method name of the transactionally advised class. For example, if the`handlePayment(..)` method of the `BusinessService` class started a transaction, the
name of the transaction would be: `com.example.BusinessService.handlePayment`.
-##### [](#tx-multiple-tx-mgrs-with-attransactional)Multiple Transaction Managers with `@Transactional` #####
+##### Multiple Transaction Managers with `@Transactional`
Most Spring applications need only a single transaction manager, but there may be
situations where you want multiple independent transaction managers in a single
@@ -1743,7 +1528,7 @@ In this case, the individual methods on `TransactionalService` run under separat
transaction managers, differentiated by the `order`, `account`, and `reactive-account`qualifiers. The default `` target bean name, `transactionManager`,
is still used if no specifically qualified `TransactionManager` bean is found.
-##### [](#tx-custom-attributes)Custom Composed Annotations #####
+##### Custom Composed Annotations
If you find you repeatedly use the same attributes with `@Transactional` on many different
methods, [Spring’s meta-annotation support](core.html#beans-meta-annotations) lets you
@@ -1820,7 +1605,7 @@ In the preceding example, we used the syntax to define the transaction manager q
and transactional labels, but we could also have included propagation behavior,
rollback rules, timeouts, and other features.
-#### [](#tx-propagation)1.4.7. Transaction Propagation ####
+#### 1.4.7. Transaction Propagation
This section describes some semantics of transaction propagation in Spring. Note
that this section is not a proper introduction to transaction propagation. Rather, it
@@ -1829,7 +1614,7 @@ details some of the semantics regarding transaction propagation in Spring.
In Spring-managed transactions, be aware of the difference between physical and
logical transactions, and how the propagation setting applies to this difference.
-##### [](#tx-propagation-required)Understanding `PROPAGATION_REQUIRED` #####
+##### Understanding `PROPAGATION_REQUIRED`
![tx prop required](images/tx_prop_required.png)
@@ -1859,7 +1644,7 @@ is not aware) silently marks a transaction as rollback-only, the outer caller st
calls commit. The outer caller needs to receive an `UnexpectedRollbackException` to
indicate clearly that a rollback was performed instead.
-##### [](#tx-propagation-requires_new)Understanding `PROPAGATION_REQUIRES_NEW` #####
+##### Understanding `PROPAGATION_REQUIRES_NEW`
![tx prop requires new](images/tx_prop_requires_new.png)
@@ -1872,7 +1657,7 @@ status and with an inner transaction’s locks released immediately after its co
Such an independent inner transaction can also declare its own isolation level, timeout,
and read-only settings and not inherit an outer transaction’s characteristics.
-##### [](#tx-propagation-nested)Understanding `PROPAGATION_NESTED` #####
+##### Understanding `PROPAGATION_NESTED`
`PROPAGATION_NESTED` uses a single physical transaction with multiple savepoints
that it can roll back to. Such partial rollbacks let an inner transaction scope
@@ -1881,7 +1666,7 @@ the physical transaction despite some operations having been rolled back. This s
is typically mapped onto JDBC savepoints, so it works only with JDBC resource
transactions. See Spring’s [`DataSourceTransactionManager`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jdbc/datasource/DataSourceTransactionManager.html).
-#### [](#transaction-declarative-applying-more-than-just-tx-advice)1.4.8. Advising Transactional Operations ####
+#### 1.4.8. Advising Transactional Operations
Suppose you want to run both transactional operations and some basic profiling advice.
How do you effect this in the context of ``?
@@ -2090,7 +1875,7 @@ order value.
You can configure additional aspects in similar fashion.
-#### [](#transaction-declarative-aspectj)1.4.9. Using `@Transactional` with AspectJ ####
+#### 1.4.9. Using `@Transactional` with AspectJ
You can also use the Spring Framework’s `@Transactional` support outside of a Spring
container by means of an AspectJ aspect. To do so, first annotate your classes
@@ -2142,7 +1927,7 @@ your application with AspectJ (see the[AspectJ Development
Guide](https://www.eclipse.org/aspectj/doc/released/devguide/index.html)) or use load-time weaving. See [Load-time weaving with
AspectJ in the Spring Framework](core.html#aop-aj-ltw) for a discussion of load-time weaving with AspectJ.
-### [](#transaction-programmatic)1.5. Programmatic Transaction Management ###
+### 1.5. Programmatic Transaction Management
The Spring Framework provides two means of programmatic transaction management, by using:
@@ -2155,7 +1940,7 @@ transaction management in imperative flows and `TransactionalOperator` for react
The second approach is similar to using the JTA `UserTransaction` API, although exception
handling is less cumbersome.
-#### [](#tx-prog-template)1.5.1. Using the `TransactionTemplate` ####
+#### 1.5.1. Using the `TransactionTemplate`
The `TransactionTemplate` adopts the same approach as other Spring templates, such as
the `JdbcTemplate`. It uses a callback approach (to free application code from having to
@@ -2271,7 +2056,7 @@ transactionTemplate.execute(object : TransactionCallbackWithoutResult() {
})
```
-##### [](#tx-prog-template-settings)Specifying Transaction Settings #####
+##### Specifying Transaction Settings
You can specify transaction settings (such as the propagation mode, the isolation level,
the timeout, and so forth) on the `TransactionTemplate` either programmatically or in
@@ -2331,7 +2116,7 @@ of a `TransactionTemplate`, if a class needs to use a `TransactionTemplate` with
different settings (for example, a different isolation level), you need to create
two distinct `TransactionTemplate` instances.
-#### [](#tx-prog-operator)1.5.2. Using the `TransactionOperator` ####
+#### 1.5.2. Using the `TransactionOperator`
The `TransactionOperator` follows an operator design that is similar to other reactive
operators. It uses a callback approach (to free application code from having to do the
@@ -2417,7 +2202,7 @@ transactionalOperator.execute(object : TransactionCallback() {
})
```
-##### [](#tx-prog-operator-cancel)Cancel Signals #####
+##### Cancel Signals
In Reactive Streams, a `Subscriber` can cancel its `Subscription` and stop its`Publisher`. Operators in Project Reactor, as well as in other libraries, such as `next()`,`take(long)`, `timeout(Duration)`, and others can issue cancellations. There is no way to
know the reason for the cancellation, whether it is due to an error or a simply lack of
@@ -2425,7 +2210,7 @@ interest to consume further. Since version 5.3 cancel signals lead to a roll bac
As a result it is important to consider the operators used downstream from a transaction`Publisher`. In particular in the case of a `Flux` or other multi-value `Publisher`,
the full output must be consumed to allow the transaction to complete.
-##### [](#tx-prog-operator-settings)Specifying Transaction Settings #####
+##### Specifying Transaction Settings
You can specify transaction settings (such as the propagation mode, the isolation level,
the timeout, and so forth) for the `TransactionalOperator`. By default,`TransactionalOperator` instances have[default transactional settings](#transaction-declarative-txadvice-settings). The
@@ -2466,12 +2251,12 @@ class SimpleService(transactionManager: ReactiveTransactionManager) : Service {
}
```
-#### [](#transaction-programmatic-tm)1.5.3. Using the `TransactionManager` ####
+#### 1.5.3. Using the `TransactionManager`
The following sections explain programmatic usage of imperative and reactive transaction
managers.
-##### [](#transaction-programmatic-ptm)Using the `PlatformTransactionManager` #####
+##### Using the `PlatformTransactionManager`
For imperative transactions, you can use a`org.springframework.transaction.PlatformTransactionManager` directly to manage your
transaction. To do so, pass the implementation of the `PlatformTransactionManager` you
@@ -2515,7 +2300,7 @@ try {
txManager.commit(status)
```
-##### [](#transaction-programmatic-rtm)Using the `ReactiveTransactionManager` #####
+##### Using the `ReactiveTransactionManager`
When working with reactive transactions, you can use a`org.springframework.transaction.ReactiveTransactionManager` directly to manage your
transaction. To do so, pass the implementation of the `ReactiveTransactionManager` you
@@ -2559,7 +2344,7 @@ reactiveTx.flatMap { status ->
}
```
-### [](#tx-decl-vs-prog)1.6. Choosing Between Programmatic and Declarative Transaction Management ###
+### 1.6. Choosing Between Programmatic and Declarative Transaction Management
Programmatic transaction management is usually a good idea only if you have a small
number of transactional operations. For example, if you have a web application that
@@ -2574,7 +2359,7 @@ management out of business logic and is not difficult to configure. When using t
Spring Framework, rather than EJB CMT, the configuration cost of declarative transaction
management is greatly reduced.
-### [](#transaction-event)1.7. Transaction-bound Events ###
+### 1.7. Transaction-bound Events
As of Spring 4.2, the listener of an event can be bound to a phase of the transaction.
The typical example is to handle the event when the transaction has completed successfully.
@@ -2626,7 +2411,7 @@ required semantics. You can, however, override that behavior by setting the `fal
| |`@TransactionalEventListener` only works with thread-bound transactions managed by`PlatformTransactionManager`. A reactive transaction managed by `ReactiveTransactionManager`uses the Reactor context instead of thread-local attributes, so from the perspective of an event listener, there is no compatible active transaction that it can participate in.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-### [](#transaction-application-server-integration)1.8. Application server-specific integration ###
+### 1.8. Application server-specific integration
Spring’s transaction abstraction is generally application server-agnostic. Additionally,
Spring’s `JtaTransactionManager` class (which can optionally perform a JNDI lookup for
@@ -2649,13 +2434,13 @@ transaction manager available for the platform. This means that you need not exp
configure server-specific adapter classes (as discussed in the following sections).
Rather, they are chosen automatically, with the standard`JtaTransactionManager` as the default fallback.
-#### [](#transaction-application-server-integration-websphere)1.8.1. IBM WebSphere ####
+#### 1.8.1. IBM WebSphere
On WebSphere 6.1.0.9 and above, the recommended Spring JTA transaction manager to use is`WebSphereUowTransactionManager`. This special adapter uses IBM’s `UOWManager` API,
which is available in WebSphere Application Server 6.1.0.9 and later. With this adapter,
Spring-driven transaction suspension (suspend and resume as initiated by`PROPAGATION_REQUIRES_NEW`) is officially supported by IBM.
-#### [](#transaction-application-server-integration-weblogic)1.8.2. Oracle WebLogic Server ####
+#### 1.8.2. Oracle WebLogic Server
On WebLogic Server 9.0 or above, you would typically use the`WebLogicJtaTransactionManager` instead of the stock `JtaTransactionManager` class. This
special WebLogic-specific subclass of the normal `JtaTransactionManager` supports the
@@ -2663,11 +2448,11 @@ full power of Spring’s transaction definitions in a WebLogic-managed transacti
environment, beyond standard JTA semantics. Features include transaction names,
per-transaction isolation levels, and proper resuming of transactions in all cases.
-### [](#transaction-solutions-to-common-problems)1.9. Solutions to Common Problems ###
+### 1.9. Solutions to Common Problems
This section describes solutions to some common problems.
-#### [](#transaction-solutions-to-common-problems-wrong-ptm)1.9.1. Using the Wrong Transaction Manager for a Specific `DataSource` ####
+#### 1.9.1. Using the Wrong Transaction Manager for a Specific `DataSource` ####
Use the correct `PlatformTransactionManager` implementation based on your choice of
transactional technologies and requirements. Used properly, the Spring Framework merely
@@ -2677,7 +2462,7 @@ it) for all your transactional operations. Otherwise, the transaction infrastruc
tries to perform local transactions on such resources as container `DataSource`instances. Such local transactions do not make sense, and a good application server
treats them as errors.
-### [](#transaction-resources)1.10. Further Resources ###
+### 1.10. Further Resources
For more information about the Spring Framework’s transaction support, see:
@@ -2691,8 +2476,7 @@ For more information about the Spring Framework’s transaction support, see:
to transactions in Java. It also includes side-by-side examples of how to configure
and use transactions with both the Spring Framework and EJB3.
-[](#dao)2. DAO Support
-----------
+## 2. DAO Support
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with
data access technologies (such as JDBC, Hibernate, or JPA) in a consistent way. This
@@ -2700,7 +2484,7 @@ lets you switch between the aforementioned persistence technologies fairly easil
and it also lets you code without worrying about catching exceptions that are
specific to each technology.
-### [](#dao-exceptions)2.1. Consistent Exception Hierarchy ###
+### 2.1. Consistent Exception Hierarchy
Spring provides a convenient translation from technology-specific exceptions, such as`SQLException` to its own exception class hierarchy, which has `DataAccessException` as
the root exception. These exceptions wrap the original exception so that there is never
@@ -2727,7 +2511,7 @@ The following image shows the exception hierarchy that Spring provides.
![DataAccessException](images/DataAccessException.png)
-### [](#dao-annotations)2.2. Annotations Used to Configure DAO or Repository Classes ###
+### 2.2. Annotations Used to Configure DAO or Repository Classes
The best way to guarantee that your Data Access Objects (DAOs) or repositories provide
exception translation is to use the `@Repository` annotation. This annotation also
@@ -2854,8 +2638,7 @@ class JdbcMovieFinder(dataSource: DataSource) : MovieFinder {
| |See the specific coverage of each persistence technology for details on how to configure the application context to take advantage of these annotations.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------|
-[](#jdbc)3. Data Access with JDBC
-----------
+## 3. Data Access with JDBC
The value provided by the Spring Framework JDBC abstraction is perhaps best shown by
the sequence of actions outlined in the following table below. The table shows which actions Spring
@@ -2877,7 +2660,7 @@ takes care of and which actions are your responsibility.
The Spring Framework takes care of all the low-level details that can make JDBC such a
tedious API.
-### [](#jdbc-choose-style)3.1. Choosing an Approach for JDBC Database Access ###
+### 3.1. Choosing an Approach for JDBC Database Access
You can choose among several approaches to form the basis for your JDBC database access.
In addition to three flavors of `JdbcTemplate`, a new `SimpleJdbcInsert` and`SimpleJdbcCall` approach optimizes database metadata, and the RDBMS Object style takes a
@@ -2906,7 +2689,7 @@ advanced features require a JDBC 3.0 driver.
query string, declare parameters, and compile the query. Once you do that,`execute(…)`, `update(…)`, and `findObject(…)` methods can be called multiple
times with various parameter values.
-### [](#jdbc-packages)3.2. Package Hierarchy ###
+### 3.2. Package Hierarchy
The Spring Framework’s JDBC abstraction framework consists of four different packages:
@@ -2931,7 +2714,7 @@ The Spring Framework’s JDBC abstraction framework consists of four different p
the option of catching the exceptions from which you can recover while letting other
exceptions be propagated to the caller. See [Using `SQLExceptionTranslator`](#jdbc-SQLExceptionTranslator).
-### [](#jdbc-core)3.3. Using the JDBC Core Classes to Control Basic JDBC Processing and Error Handling ###
+### 3.3. Using the JDBC Core Classes to Control Basic JDBC Processing and Error Handling
This section covers how to use the JDBC core classes to control basic JDBC processing,
including error handling. It includes the following topics:
@@ -2950,7 +2733,7 @@ including error handling. It includes the following topics:
* [Retrieving Auto-generated Keys](#jdbc-auto-generated-keys)
-#### [](#jdbc-JdbcTemplate)3.3.1. Using `JdbcTemplate` ####
+#### 3.3.1. Using `JdbcTemplate`
`JdbcTemplate` is the central class in the JDBC core package. It handles the
creation and release of resources, which helps you avoid common errors, such as
@@ -2985,7 +2768,7 @@ The following sections provide some examples of `JdbcTemplate` usage. These exam
are not an exhaustive list of all of the functionality exposed by the `JdbcTemplate`.
See the attendant [javadoc](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html) for that.
-##### [](#jdbc-JdbcTemplate-examples-query)Querying (`SELECT`) #####
+##### Querying (`SELECT`)
The following query gets the number of rows in a relation:
@@ -3115,7 +2898,7 @@ fun findAllActors(): List {
}
```
-##### [](#jdbc-JdbcTemplate-examples-update)Updating (`INSERT`, `UPDATE`, and `DELETE`) with `JdbcTemplate` #####
+##### Updating (`INSERT`, `UPDATE`, and `DELETE`) with `JdbcTemplate`
You can use the `update(..)` method to perform insert, update, and delete operations.
Parameter values are usually provided as variable arguments or, alternatively, as an object array.
@@ -3172,7 +2955,7 @@ Kotlin
jdbcTemplate.update("delete from t_actor where id = ?", actorId.toLong())
```
-##### [](#jdbc-JdbcTemplate-examples-other)Other `JdbcTemplate` Operations #####
+##### Other `JdbcTemplate` Operations
You can use the `execute(..)` method to run any arbitrary SQL. Consequently, the
method is often used for DDL statements. It is heavily overloaded with variants that take
@@ -3211,7 +2994,7 @@ jdbcTemplate.update(
More sophisticated stored procedure support is [covered later](#jdbc-StoredProcedure).
-##### [](#jdbc-JdbcTemplate-idioms)`JdbcTemplate` Best Practices #####
+##### `JdbcTemplate` Best Practices
Instances of the `JdbcTemplate` class are thread-safe, once configured. This is
important because it means that you can configure a single instance of a `JdbcTemplate`and then safely inject this shared reference into multiple DAOs (or repositories).
@@ -3359,7 +3142,7 @@ If your application accesses multiple
databases, you may want multiple `JdbcTemplate` instances, which requires multiple `DataSources` and, subsequently, multiple differently
configured `JdbcTemplate` instances.
-#### [](#jdbc-NamedParameterJdbcTemplate)3.3.2. Using `NamedParameterJdbcTemplate` ####
+#### 3.3.2. Using `NamedParameterJdbcTemplate`
The `NamedParameterJdbcTemplate` class adds support for programming JDBC statements
by using named parameters, as opposed to programming JDBC statements using only classic
@@ -3531,7 +3314,7 @@ functionality that is present only in the `JdbcTemplate` class, you can use the`
See also [`JdbcTemplate` Best Practices](#jdbc-JdbcTemplate-idioms) for guidelines on using the`NamedParameterJdbcTemplate` class in the context of an application.
-#### [](#jdbc-SQLExceptionTranslator)3.3.3. Using `SQLExceptionTranslator` ####
+#### 3.3.3. Using `SQLExceptionTranslator`
`SQLExceptionTranslator` is an interface to be implemented by classes that can translate
between `SQLException`s and Spring’s own `org.springframework.dao.DataAccessException`,
@@ -3648,7 +3431,7 @@ fun updateShippingCharge(orderId: Long, pct: Long) {
The custom translator is passed a data source in order to look up the error codes in`sql-error-codes.xml`.
-#### [](#jdbc-statements-executing)3.3.4. Running Statements ####
+#### 3.3.4. Running Statements
Running an SQL statement requires very little code. You need a `DataSource` and a`JdbcTemplate`, including the convenience methods that are provided with the`JdbcTemplate`. The following example shows what you need to include for a minimal but
fully functional class that creates a new table:
@@ -3689,7 +3472,7 @@ class ExecuteAStatement(dataSource: DataSource) {
}
```
-#### [](#jdbc-statements-querying)3.3.5. Running Queries ####
+#### 3.3.5. Running Queries
Some query methods return a single value. To retrieve a count or a specific value from
one row, use `queryForObject(..)`. The latter converts the returned JDBC `Type` to the
@@ -3774,7 +3557,7 @@ The returned list would resemble the following:
[{name=Bob, id=1}, {name=Mary, id=2}]
```
-#### [](#jdbc-updates)3.3.6. Updating the Database ####
+#### 3.3.6. Updating the Database
The following example updates a column for a certain primary key:
@@ -3819,7 +3602,7 @@ an SQL statement has placeholders for row parameters. You can pass the parameter
in as varargs or, alternatively, as an array of objects. Thus, you should explicitly wrap primitives
in the primitive wrapper classes, or you should use auto-boxing.
-#### [](#jdbc-auto-generated-keys)3.3.7. Retrieving Auto-generated Keys ####
+#### 3.3.7. Retrieving Auto-generated Keys
An `update()` convenience method supports the retrieval of primary keys generated by the
database. This support is part of the JDBC 3.0 standard. See Chapter 13.6 of the
@@ -3859,7 +3642,7 @@ jdbcTemplate.update({
// keyHolder.getKey() now contains the generated key
```
-### [](#jdbc-connections)3.4. Controlling Database Connections ###
+### 3.4. Controlling Database Connections
This section covers:
@@ -3879,7 +3662,7 @@ This section covers:
* [Using `DataSourceTransactionManager`](#jdbc-DataSourceTransactionManager)
-#### [](#jdbc-datasource)3.4.1. Using `DataSource` ####
+#### 3.4.1. Using `DataSource`
Spring obtains a connection to the database through a `DataSource`. A `DataSource` is
part of the JDBC specification and is a generalized connection factory. It lets a
@@ -3978,24 +3761,24 @@ The following example shows C3P0 configuration:
```
-#### [](#jdbc-DataSourceUtils)3.4.2. Using `DataSourceUtils` ####
+#### 3.4.2. Using `DataSourceUtils`
The `DataSourceUtils` class is a convenient and powerful helper class that provides`static` methods to obtain connections from JNDI and close connections if necessary. It
supports thread-bound connections with, for example, `DataSourceTransactionManager`.
-#### [](#jdbc-SmartDataSource)3.4.3. Implementing `SmartDataSource` ####
+#### 3.4.3. Implementing `SmartDataSource`
The `SmartDataSource` interface should be implemented by classes that can provide a
connection to a relational database. It extends the `DataSource` interface to let
classes that use it query whether the connection should be closed after a given
operation. This usage is efficient when you know that you need to reuse a connection.
-#### [](#jdbc-AbstractDataSource)3.4.4. Extending `AbstractDataSource` ####
+#### 3.4.4. Extending `AbstractDataSource`
`AbstractDataSource` is an `abstract` base class for Spring’s `DataSource`implementations. It implements code that is common to all `DataSource` implementations.
You should extend the `AbstractDataSource` class if you write your own `DataSource`implementation.
-#### [](#jdbc-SingleConnectionDataSource)3.4.5. Using `SingleConnectionDataSource` ####
+#### 3.4.5. Using `SingleConnectionDataSource`
The `SingleConnectionDataSource` class is an implementation of the `SmartDataSource`interface that wraps a single `Connection` that is not closed after each use.
This is not multi-threading capable.
@@ -4010,7 +3793,7 @@ of code outside an application server, in conjunction with a simple JNDI environ
In contrast to `DriverManagerDataSource`, it reuses the same connection all the time,
avoiding excessive creation of physical connections.
-#### [](#jdbc-DriverManagerDataSource)3.4.6. Using `DriverManagerDataSource` ####
+#### 3.4.6. Using `DriverManagerDataSource`
The `DriverManagerDataSource` class is an implementation of the standard `DataSource`interface that configures a plain JDBC driver through bean properties and returns a new`Connection` every time.
@@ -4021,7 +3804,7 @@ close the connection, so any `DataSource`-aware persistence code should work. Ho
using JavaBean-style connection pools (such as `commons-dbcp`) is so easy, even in a test
environment, that it is almost always preferable to use such a connection pool over`DriverManagerDataSource`.
-#### [](#jdbc-TransactionAwareDataSourceProxy)3.4.7. Using `TransactionAwareDataSourceProxy` ####
+#### 3.4.7. Using `TransactionAwareDataSourceProxy`
`TransactionAwareDataSourceProxy` is a proxy for a target `DataSource`. The proxy wraps that
target `DataSource` to add awareness of Spring-managed transactions. In this respect, it
@@ -4032,7 +3815,7 @@ is similar to a transactional JNDI `DataSource`, as provided by a Java EE server
See the [`TransactionAwareDataSourceProxy`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.html)javadoc for more details.
-#### [](#jdbc-DataSourceTransactionManager)3.4.8. Using `DataSourceTransactionManager` ####
+#### 3.4.8. Using `DataSourceTransactionManager`
The `DataSourceTransactionManager` class is a `PlatformTransactionManager`implementation for single JDBC datasources. It binds a JDBC connection from the
specified data source to the currently executing thread, potentially allowing for one
@@ -4052,13 +3835,13 @@ case, as it does not require the container to support JTA. Switching between
both is just a matter of configuration, provided you stick to the required connection lookup
pattern. JTA does not support custom isolation levels.
-### [](#jdbc-advanced-jdbc)3.5. JDBC Batch Operations ###
+### 3.5. JDBC Batch Operations
Most JDBC drivers provide improved performance if you batch multiple calls to the same
prepared statement. By grouping updates into batches, you limit the number of round trips
to the database.
-#### [](#jdbc-batch-classic)3.5.1. Basic Batch Operations with `JdbcTemplate` ####
+#### 3.5.1. Basic Batch Operations with `JdbcTemplate`
You accomplish `JdbcTemplate` batch processing by implementing two methods of a special
interface, `BatchPreparedStatementSetter`, and passing that implementation in as the second parameter
@@ -4130,7 +3913,7 @@ case, you can use the `InterruptibleBatchPreparedStatementSetter` interface, whi
you interrupt a batch once the input source is exhausted. The `isBatchExhausted` method
lets you signal the end of the batch.
-#### [](#jdbc-batch-list)3.5.2. Batch Operations with a List of Objects ####
+#### 3.5.2. Batch Operations with a List of Objects
Both the `JdbcTemplate` and the `NamedParameterJdbcTemplate` provides an alternate way
of providing the batch update. Instead of implementing a special batch interface, you
@@ -4241,7 +4024,7 @@ the JDBC driver. If the count is not available, the JDBC driver returns a value
| |In such a scenario, with automatic setting of values on an underlying `PreparedStatement`, the corresponding JDBC type for each value needs to be derived from the given Java type. While this usually works well, there is a potential for issues (for example, with Map-contained`null` values). Spring, by default, calls `ParameterMetaData.getParameterType` in such a case, which can be expensive with your JDBC driver. You should use a recent driver version and consider setting the `spring.jdbc.getParameterType.ignore` property to `true`(as a JVM system property or via the[`SpringProperties`](appendix.html#appendix-spring-properties) mechanism) if you encounter a performance issue (as reported on Oracle 12c, JBoss, and PostgreSQL).
Alternatively, you might consider specifying the corresponding JDBC types explicitly, either through a `BatchPreparedStatementSetter` (as shown earlier), through an explicit type array given to a `List