mirror of
https://github.com/spring-projects/spring-framework
synced 2026-06-08 17:33:33 +00:00
Compare commits
205 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0fbc94fae0 | |||
| 6e08c56076 | |||
| fb6d3f5b5c | |||
| 6fe5652783 | |||
| ca68bbc9ff | |||
| e7bcb48e57 | |||
| 433b1c480c | |||
| 0b08246760 | |||
| c7bdfbea4f | |||
| 618989d317 | |||
| 7fe78b745f | |||
| 98f152e8d5 | |||
| d74191427e | |||
| 4c69892f39 | |||
| c79ae0c842 | |||
| 46fc28fd1a | |||
| f8a1dac593 | |||
| 9712bb62fd | |||
| e85f6342a2 | |||
| 7199782d45 | |||
| 5ed4a14e2b | |||
| b27735d4a6 | |||
| dc5a773b2b | |||
| 2b6f3caff4 | |||
| 83eb8ac0ea | |||
| 9b38e43c17 | |||
| 284cb12f8f | |||
| 67644a28b6 | |||
| 1b57f2bda5 | |||
| a1a140f7d5 | |||
| 4caf3c8ce0 | |||
| 485c80fcf3 | |||
| aae46263cc | |||
| 39d4d2041a | |||
| 5ac97b16a8 | |||
| f457c17c78 | |||
| b0b2bbc857 | |||
| 69f47e7700 | |||
| 52af5c2b38 | |||
| 404661d5cb | |||
| f07a4587bb | |||
| 114d6a9256 | |||
| 73a18046c3 | |||
| c899af0e03 | |||
| 098c924e32 | |||
| 4289a64e24 | |||
| 7615762039 | |||
| d601f3196a | |||
| 92a6e7ddcd | |||
| c79474d269 | |||
| f4bc9ffb98 | |||
| e124e802a3 | |||
| 348cc01284 | |||
| 9f7a510f90 | |||
| f64397d822 | |||
| 918edaba2e | |||
| 5214bd3093 | |||
| 752ef6f456 | |||
| bea1980e22 | |||
| f3360e4ee2 | |||
| 8330bd424b | |||
| 507c9697fb | |||
| 52c073724d | |||
| de07ad47f1 | |||
| 93ea2e1df9 | |||
| a7bf14b364 | |||
| 7899fa3b0a | |||
| c1da2a4e73 | |||
| db53b618c1 | |||
| 913163884a | |||
| 4a555aaef1 | |||
| e9ada8d15c | |||
| 63d841664c | |||
| 9779d25d98 | |||
| 89d0c6b962 | |||
| 20da0835b3 | |||
| 4f232a9003 | |||
| c24a51323d | |||
| 69d022712b | |||
| aa1f3d1681 | |||
| b366cd352e | |||
| ac667a1e2b | |||
| a09f93768a | |||
| 0ccd2f8b87 | |||
| b1fdb148d0 | |||
| 955ca4d146 | |||
| d5732fed45 | |||
| 4c7b04e32a | |||
| 74ec10bf3a | |||
| dd6cb1b728 | |||
| 1e4c10cef1 | |||
| e47978e168 | |||
| 52e967a525 | |||
| 1de9d123a5 | |||
| ad60164911 | |||
| c49b0825f9 | |||
| fdec9f0adc | |||
| a88dbbec98 | |||
| 61d8774da0 | |||
| c2b16f1ffb | |||
| 6af94dffe5 | |||
| 2147175898 | |||
| 052542254a | |||
| 1bb723b9e0 | |||
| db02c96c55 | |||
| 164141a63e | |||
| 0a731413de | |||
| 6e5dd64025 | |||
| 650875468c | |||
| 6d2a25b877 | |||
| 2847621928 | |||
| 3afc6a5079 | |||
| 6c8fb6c204 | |||
| 8e9a553517 | |||
| 537d539b1d | |||
| 476b9cfc99 | |||
| 352087a637 | |||
| 33d33802a8 | |||
| 9ec937c843 | |||
| 8e5eb84da1 | |||
| 902f8dd1d8 | |||
| 22f8ea61fb | |||
| 8ce1f14554 | |||
| 9a3cb628af | |||
| b0a4c5d72c | |||
| 8b110c9971 | |||
| 21d3a7529c | |||
| 9c7b471634 | |||
| 45d45c2989 | |||
| 4ff18741fd | |||
| b7e99fbe30 | |||
| a27f2e994b | |||
| 284cf3ecf2 | |||
| cbf25b704d | |||
| 8391897a94 | |||
| a3c89092e1 | |||
| e77c426eeb | |||
| fe5bd6751f | |||
| ed5ab77397 | |||
| 98c514ecbe | |||
| beb9fa2b8b | |||
| 459e8a1ea5 | |||
| 7e52b803be | |||
| 7fcd1de8e3 | |||
| d5b0b2b1a1 | |||
| 36f7597f25 | |||
| f9f8f2d89e | |||
| 43f8d9e084 | |||
| 7816c9e411 | |||
| d32027df92 | |||
| a832c98ced | |||
| c12d93c5d1 | |||
| ca6acfee30 | |||
| b130ff36d9 | |||
| 0b8000eeaa | |||
| 8350738929 | |||
| b695687e13 | |||
| 2ba7a553b3 | |||
| 1e98fb607a | |||
| c1dfde5ba4 | |||
| 917c41fd52 | |||
| 0c878d2d06 | |||
| 50109dd86d | |||
| 99ae209c25 | |||
| 64c6a97130 | |||
| 2112e86795 | |||
| f4e23fe204 | |||
| 04366f4129 | |||
| 2a2c679f66 | |||
| 32a5830543 | |||
| 9378493d83 | |||
| da12481ef1 | |||
| c45f8b7072 | |||
| 60243dbbac | |||
| fb1f0eccfb | |||
| c0602fd071 | |||
| 870e856554 | |||
| b9656ac6c0 | |||
| de441b4751 | |||
| 9c3efdec32 | |||
| af40a124bb | |||
| 44c583392e | |||
| 9249dc3d37 | |||
| 3458f293d4 | |||
| 796b8c1278 | |||
| cefd74555a | |||
| e9555d4825 | |||
| 1960666765 | |||
| 45dc1d2602 | |||
| ef5796c3a9 | |||
| b52300eab8 | |||
| 031adfb8ec | |||
| 792371ac1f | |||
| 62bbebd4f4 | |||
| ac7d428a62 | |||
| f6eaa8e63c | |||
| cd27fbe550 | |||
| bbfc39efc9 | |||
| 1a8a69d289 | |||
| e16cdfede0 | |||
| 26df6fbada | |||
| 508d2c7a77 | |||
| 428539f30d | |||
| d0d5730f7f | |||
| befa4b14cd |
@@ -3,6 +3,8 @@ name: Backport Bot
|
||||
on:
|
||||
issues:
|
||||
types: [labeled]
|
||||
pull_request:
|
||||
types: [labeled]
|
||||
push:
|
||||
branches:
|
||||
- '*.x'
|
||||
@@ -13,6 +15,7 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ plugins {
|
||||
id 'com.github.ben-manes.versions' version '0.42.0'
|
||||
id 'com.github.johnrengelman.shadow' version '7.1.2' apply false
|
||||
id 'de.undercouch.download' version '5.1.0'
|
||||
id 'me.champeau.jmh' version '0.6.6' apply false
|
||||
id 'me.champeau.jmh' version '0.6.8' apply false
|
||||
}
|
||||
|
||||
ext {
|
||||
@@ -78,7 +78,7 @@ configure([rootProject] + javaProjects) { project ->
|
||||
}
|
||||
|
||||
checkstyle {
|
||||
toolVersion = "10.4"
|
||||
toolVersion = "10.5.0"
|
||||
configDirectory.set(rootProject.file("src/checkstyle"))
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ public class KotlinConventions {
|
||||
kotlinOptions.setApiVersion("1.7");
|
||||
kotlinOptions.setLanguageVersion("1.7");
|
||||
kotlinOptions.setJvmTarget("17");
|
||||
kotlinOptions.setJavaParameters(true);
|
||||
kotlinOptions.setAllWarningsAsErrors(true);
|
||||
List<String> freeCompilerArgs = new ArrayList<>(compile.getKotlinOptions().getFreeCompilerArgs());
|
||||
freeCompilerArgs.addAll(List.of("-Xsuppress-version-warnings", "-Xjsr305=strict", "-opt-in=kotlin.RequiresOptIn"));
|
||||
|
||||
@@ -10,6 +10,15 @@ configurations {
|
||||
asciidoctorExtensions
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api(project(":spring-context"))
|
||||
api(project(":spring-web"))
|
||||
api("jakarta.servlet:jakarta.servlet-api")
|
||||
|
||||
implementation(project(":spring-core-test"))
|
||||
implementation("org.assertj:assertj-core")
|
||||
}
|
||||
|
||||
jar {
|
||||
enabled = false
|
||||
}
|
||||
@@ -80,8 +89,6 @@ rootProject.tasks.dokkaHtmlMultiModule.configure {
|
||||
}
|
||||
|
||||
asciidoctorj {
|
||||
def docRoot = 'https://docs.spring.io'
|
||||
def docsSpringFramework = "${docRoot}/spring-framework/docs/${project.version}"
|
||||
version = '2.4.3'
|
||||
fatalWarnings ".*"
|
||||
options doctype: 'book', eruby: 'erubis'
|
||||
@@ -92,11 +99,7 @@ asciidoctorj {
|
||||
revnumber: project.version,
|
||||
sectanchors: '',
|
||||
sectnums: '',
|
||||
'spring-version': project.version,
|
||||
'spring-framework-main-code': 'https://github.com/spring-projects/spring-framework/tree/main',
|
||||
'doc-root': docRoot,
|
||||
'docs-spring-framework': docsSpringFramework,
|
||||
'api-spring-framework': "${docsSpringFramework}/javadoc-api/org/springframework"
|
||||
'spring-version': project.version
|
||||
])
|
||||
}
|
||||
|
||||
@@ -110,18 +113,23 @@ asciidoctor {
|
||||
sources {
|
||||
include '*.adoc'
|
||||
}
|
||||
outputDir "$buildDir/docs/ref-docs/html5"
|
||||
outputOptions {
|
||||
backends "spring-html"
|
||||
}
|
||||
logDocuments = true
|
||||
resources {
|
||||
from(sourceDir) {
|
||||
include 'images/*.png'
|
||||
}
|
||||
}
|
||||
outputDir "$buildDir/docs/ref-docs/html5"
|
||||
outputOptions {
|
||||
backends "spring-html"
|
||||
}
|
||||
forkOptions {
|
||||
jvmArgs += ["--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED", "--add-opens", "java.base/java.io=ALL-UNNAMED"]
|
||||
}
|
||||
logDocuments = true
|
||||
}
|
||||
|
||||
asciidoctor.mustRunAfter "check"
|
||||
|
||||
/**
|
||||
* Generate the Spring Framework Reference documentation from "src/docs/asciidoc"
|
||||
* in "build/docs/ref-docs/pdf".
|
||||
@@ -241,7 +249,6 @@ task distZip(type: Zip, dependsOn: [docsZip, schemaZip]) {
|
||||
|
||||
distZip.mustRunAfter moduleProjects.check
|
||||
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
mavenJava(MavenPublication) {
|
||||
@@ -250,4 +257,4 @@ publishing {
|
||||
artifact distZip
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
[[appendix]]
|
||||
= Appendix
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:tabsize: 4
|
||||
:docinfo1:
|
||||
include::attributes.adoc[]
|
||||
include::page-layout.adoc[]
|
||||
|
||||
This part of the reference documentation covers topics that apply to multiple modules
|
||||
within the core Spring Framework.
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
:chomp: default headers packages
|
||||
:docs-site: https://docs.spring.io
|
||||
// Spring Framework
|
||||
:docs-spring-framework: {docs-site}/spring-framework/docs/{spring-version}
|
||||
:api-spring-framework: {docs-spring-framework}/javadoc-api/org/springframework
|
||||
:docs-java: {docdir}/../../main/java/org/springframework/docs
|
||||
:docs-kotlin: {docdir}/../../main/kotlin/org/springframework/docs
|
||||
:docs-resources: {docdir}/../../main/resources
|
||||
:spring-framework-main-code: https://github.com/spring-projects/spring-framework/tree/main
|
||||
// Spring portfolio Links
|
||||
:docs-spring-boot: {docs-site}/spring-boot/docs/current/reference
|
||||
:docs-spring-gemfire: {docs-site}/spring-gemfire/docs/current/reference
|
||||
:docs-spring-security: {docs-site}/spring-security/reference
|
||||
// Third-party Links
|
||||
:docs-graalvm: https://www.graalvm.org/22.3/reference-manual
|
||||
:gh-rsocket: https://github.com/rsocket
|
||||
:gh-rsocket-extensions: {gh-rsocket}/rsocket/blob/master/Extensions
|
||||
:gh-rsocket-java: {gh-rsocket}/rsocket-java
|
||||
@@ -1,9 +1,7 @@
|
||||
[[spring-core]]
|
||||
= Core Technologies
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:tabsize: 4
|
||||
:docinfo1:
|
||||
include::attributes.adoc[]
|
||||
include::page-layout.adoc[]
|
||||
|
||||
This part of the reference documentation covers all the technologies that are
|
||||
absolutely integral to the Spring Framework.
|
||||
|
||||
@@ -1755,5 +1755,5 @@ support for new custom advice types be added without changing the core framework
|
||||
The only constraint on a custom `Advice` type is that it must implement the
|
||||
`org.aopalliance.aop.Advice` marker interface.
|
||||
|
||||
See the {api-spring-framework}/aop/framework/adapter/package-frame.html[`org.springframework.aop.framework.adapter`]
|
||||
See the {api-spring-framework}/aop/framework/adapter/package-summary.html[`org.springframework.aop.framework.adapter`]
|
||||
javadoc for further information.
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
[[aot]]
|
||||
[[core.aot]]
|
||||
= Ahead of Time Optimizations
|
||||
|
||||
This chapter covers Spring's Ahead of Time (AOT) optimizations.
|
||||
|
||||
For AOT support specific to integration tests, see <<testing.adoc#testcontext-aot, Ahead of Time Support for Tests>>.
|
||||
|
||||
[[aot-introduction]]
|
||||
[[core.aot.introduction]]
|
||||
== Introduction to Ahead of Time Optimizations
|
||||
|
||||
Spring's support for AOT optimizations is meant to inspect an `ApplicationContext` at build time and apply decisions and discovery logic that usually happens at runtime.
|
||||
@@ -26,9 +26,9 @@ A Spring AOT processed application typically generates:
|
||||
* {api-spring-framework}/aot/hint/RuntimeHints.html[`RuntimeHints`] for the use of reflection, resource loading, serialization, and JDK proxies.
|
||||
|
||||
NOTE: At the moment, AOT is focused on allowing Spring applications to be deployed as native images using GraalVM.
|
||||
We intend to offer more JVM-based use cases in future generations.
|
||||
We intend to support more JVM-based use cases in future generations.
|
||||
|
||||
[[aot-basics]]
|
||||
[[core.aot.basics]]
|
||||
== AOT engine overview
|
||||
|
||||
The entry point of the AOT engine for processing an `ApplicationContext` arrangement is `ApplicationContextAotGenerator`. It takes care of the following steps, based on a `GenericApplicationContext` that represents the application to optimize and a {api-spring-framework}/aot/generate/GenerationContext.html[`GenerationContext`]:
|
||||
@@ -37,14 +37,14 @@ The entry point of the AOT engine for processing an `ApplicationContext` arrange
|
||||
* Invoke the available `BeanFactoryInitializationAotProcessor` implementations and apply their contributions against the `GenerationContext`.
|
||||
For instance, a core implementation iterates over all candidate bean definitions and generates the necessary code to restore the state of the `BeanFactory`.
|
||||
|
||||
Once this process completes, the `GenerationContext` has been updated with the generated code, resources, and classes that are necessary for the application to run.
|
||||
Once this process completes, the `GenerationContext` will have been updated with the generated code, resources, and classes that are necessary for the application to run.
|
||||
The `RuntimeHints` instance can also be used to generate the relevant GraalVM native image configuration files.
|
||||
|
||||
`ApplicationContextAotGenerator#processAheadOfTime` returns the class name of the `ApplicationContextInitializer` entry point that allows the context to be started with AOT optimizations.
|
||||
|
||||
Those steps are covered in more details in the sections below.
|
||||
Those steps are covered in greater detail in the sections below.
|
||||
|
||||
[[aot-refresh]]
|
||||
[[core.aot.refresh]]
|
||||
== Refresh for AOT Processing
|
||||
|
||||
Refresh for AOT processing is supported on all `GenericApplicationContext` implementations.
|
||||
@@ -52,27 +52,13 @@ An application context is created with any number of entry points, usually in th
|
||||
|
||||
Let's look at a basic example:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@Configuration(proxyBeanMethods=false)
|
||||
@ComponentScan
|
||||
@Import({DataSourceConfiguration.class, ContainerConfiguration.class})
|
||||
public class MyApplication {
|
||||
}
|
||||
----
|
||||
include::code:AotProcessingSample[tag=myapplication]
|
||||
|
||||
Starting this application with the regular runtime involves a number of steps including classpath scanning, configuration class parsing, bean instantiation, and lifecycle callback handling.
|
||||
Refresh for AOT processing only applies a subset of what happens with a <<beans-introduction,regular `refresh`>>.
|
||||
AOT processing can be triggered as follows:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
GenericApplicationContext applicationContext = new AnnotatedConfigApplicationContext();
|
||||
context.register(MyApplication.class);
|
||||
context.refreshForAotProcessing();
|
||||
----
|
||||
include::code:AotProcessingSample[tag=aotcontext]
|
||||
|
||||
In this mode, <<beans-factory-extension-factory-postprocessors,`BeanFactoryPostProcessor` implementations>> are invoked as usual.
|
||||
This includes configuration class parsing, import selectors, classpath scanning, etc.
|
||||
@@ -84,11 +70,11 @@ These are:
|
||||
|
||||
* `MergedBeanDefinitionPostProcessor` implementations post-process bean definitions to extract additional settings, such as `init` and `destroy` methods.
|
||||
* `SmartInstantiationAwareBeanPostProcessor` implementations determine a more precise bean type if necessary.
|
||||
This makes sure to create any proxy that is required at runtime.
|
||||
This makes sure to create any proxy that will be required at runtime.
|
||||
|
||||
One this part completes, the `BeanFactory` contains the bean definitions that are necessary for the application to run. It does not trigger bean instantiation but allows the AOT engine to inspect the beans that would be created at runtime.
|
||||
One this part completes, the `BeanFactory` contains the bean definitions that are necessary for the application to run. It does not trigger bean instantiation but allows the AOT engine to inspect the beans that will be created at runtime.
|
||||
|
||||
[[aot-bean-factory-initialization-contributions]]
|
||||
[[core.aot.bean-factory-initialization-contributions]]
|
||||
== Bean Factory Initialization AOT Contributions
|
||||
|
||||
Components that want to participate in this step can implement the {api-spring-framework}/beans/factory/aot/BeanFactoryInitializationAotProcessor.html[`BeanFactoryInitializationAotProcessor`] interface.
|
||||
@@ -111,7 +97,7 @@ If such a bean is registered using an `@Bean` factory method, ensure the method
|
||||
====
|
||||
|
||||
|
||||
[[aot-bean-registration-contributions]]
|
||||
[[core.aot.bean-registration-contributions]]
|
||||
=== Bean Registration AOT Contributions
|
||||
|
||||
A core `BeanFactoryInitializationAotProcessor` implementation is responsible for collecting the necessary contributions for each candidate `BeanDefinition`.
|
||||
@@ -198,7 +184,7 @@ When a `datasource` instance is required, a `BeanInstanceSupplier` is called.
|
||||
This supplier invokes the `dataSource()` method on the `dataSourceConfiguration` bean.
|
||||
|
||||
|
||||
[[aot-hints]]
|
||||
[[core.aot.hints]]
|
||||
== Runtime Hints
|
||||
|
||||
Running an application as a native image requires additional information compared to a regular JVM runtime.
|
||||
@@ -222,31 +208,14 @@ For cases that the core container cannot infer, you can register such hints prog
|
||||
A number of convenient annotations are also provided for common use cases.
|
||||
|
||||
|
||||
[[aot-hints-import-runtime-hints]]
|
||||
[[core.aot.hints.import-runtime-hints]]
|
||||
=== `@ImportRuntimeHints`
|
||||
|
||||
`RuntimeHintsRegistrar` implementations allow you to get a callback to the `RuntimeHints` instance managed by the AOT engine.
|
||||
Implementations of this interface can be registered using `@ImportRuntimeHints` on any Spring bean or `@Bean` factory method.
|
||||
`RuntimeHintsRegistrar` implementations are detected and invoked at build time.
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@Component
|
||||
@ImportRuntimeHints(MyComponentRuntimeHints.class)
|
||||
public class MyComponent {
|
||||
|
||||
// ...
|
||||
|
||||
private static class MyComponentRuntimeHints implements RuntimeHintsRegistrar {
|
||||
|
||||
@Override
|
||||
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
}
|
||||
----
|
||||
include::code:SpellCheckService[]
|
||||
|
||||
If at all possible, `@ImportRuntimeHints` should be used as close as possible to the component that requires the hints.
|
||||
This way, if the component is not contributed to the `BeanFactory`, the hints won't be contributed either.
|
||||
@@ -254,7 +223,7 @@ This way, if the component is not contributed to the `BeanFactory`, the hints wo
|
||||
It is also possible to register an implementation statically by adding an entry in `META-INF/spring/aot.factories` with a key equal to the fully qualified name of the `RuntimeHintsRegistrar` interface.
|
||||
|
||||
|
||||
[[aot-hints-reflective]]
|
||||
[[core.aot.hints.reflective]]
|
||||
=== `@Reflective`
|
||||
|
||||
{api-spring-framework}/aot/hint/annotation/Reflective.html[`@Reflective`] provides an idiomatic way to flag the need for reflection on an annotated element.
|
||||
@@ -268,7 +237,7 @@ Library authors can reuse this annotation for their own purposes.
|
||||
If components other than Spring beans need to be processed, a `BeanFactoryInitializationAotProcessor` can detect the relevant types and use `ReflectiveRuntimeHintsRegistrar` to process them.
|
||||
|
||||
|
||||
[[aot-hints-register-reflection-for-binding]]
|
||||
[[core.aot.hints.register-reflection-for-binding]]
|
||||
=== `@RegisterReflectionForBinding`
|
||||
|
||||
{api-spring-framework}/aot/hint/annotation/RegisterReflectionForBinding.html[`@RegisterReflectionForBinding`] is a specialization of `@Reflective` that registers the need for serializing arbitrary types.
|
||||
@@ -290,3 +259,49 @@ The following example registers `Account` for serialization.
|
||||
|
||||
}
|
||||
----
|
||||
|
||||
[[core.aot.hints.testing]]
|
||||
=== Testing Runtime Hints
|
||||
|
||||
Spring Core also ships `RuntimeHintsPredicates`, a utility for checking that existing hints match a particular use case.
|
||||
This can be used in your own tests to validate that a `RuntimeHintsRegistrar` contains the expected results.
|
||||
We can write a test for our `SpellCheckService` and ensure that we will be able to load a dictionary at runtime:
|
||||
|
||||
include::code:SpellCheckServiceTests[tag=hintspredicates]
|
||||
|
||||
With `RuntimeHintsPredicates`, we can check for reflection, resource, serialization, or proxy generation hints.
|
||||
This approach works well for unit tests but implies that the runtime behavior of a component is well known.
|
||||
|
||||
You can learn more about the global runtime behavior of an application by running its test suite (or the app itself) with the {docs-graalvm}/native-image/metadata/AutomaticMetadataCollection/[GraalVM tracing agent].
|
||||
This agent will record all relevant calls requiring GraalVM hints at runtime and write them out as JSON configuration files.
|
||||
|
||||
For more targeted discovery and testing, Spring Framework ships a dedicated module with core AOT testing utilities, `"org.springframework:spring-core-test"`.
|
||||
This module contains the RuntimeHints Agent, a Java agent that records all method invocations that are related to runtime hints and helps you to assert that a given `RuntimeHints` instance covers all recorded invocations.
|
||||
Let's consider a piece of infrastructure for which we'd like to test the hints we're contributing during the AOT processing phase.
|
||||
|
||||
include::code:SampleReflection[]
|
||||
|
||||
We can then write a unit test (no native compilation required) that checks our contributed hints:
|
||||
|
||||
include::code:SampleReflectionRuntimeHintsTests[]
|
||||
|
||||
If you forgot to contribute a hint, the test will fail and provide some details about the invocation:
|
||||
|
||||
[source,txt,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
org.springframework.docs.core.aot.hints.testing.SampleReflection performReflection
|
||||
INFO: Spring version:6.0.0-SNAPSHOT
|
||||
|
||||
Missing <"ReflectionHints"> for invocation <java.lang.Class#forName>
|
||||
with arguments ["org.springframework.core.SpringVersion",
|
||||
false,
|
||||
jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7].
|
||||
Stacktrace:
|
||||
<"org.springframework.util.ClassUtils#forName, Line 284
|
||||
io.spring.runtimehintstesting.SampleReflection#performReflection, Line 19
|
||||
io.spring.runtimehintstesting.SampleReflectionRuntimeHintsTests#lambda$shouldRegisterReflectionHints$0, Line 25
|
||||
----
|
||||
|
||||
There are various ways to configure this Java agent in your build, so please refer to the documentation of your build tool and test execution plugin.
|
||||
The agent itself can be configured to instrument specific packages (by default, only `org.springframework` is instrumented).
|
||||
You'll find more details in the {spring-framework-main-code}/buildSrc/README.md[Spring Framework `buildSrc` README] file.
|
||||
|
||||
@@ -107,16 +107,14 @@ configuration metadata is actually written. These days, many developers choose
|
||||
|
||||
For information about using other forms of metadata with the Spring container, see:
|
||||
|
||||
* <<beans-annotation-config,Annotation-based configuration>>: Spring 2.5 introduced
|
||||
support for annotation-based configuration metadata.
|
||||
* <<beans-java, Java-based configuration>>: Starting with Spring 3.0, many features
|
||||
provided by the Spring JavaConfig project became part of the core Spring Framework.
|
||||
Thus, you can define beans external to your application classes by using Java rather
|
||||
than XML files. To use these new features, see the
|
||||
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html[`@Configuration`],
|
||||
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html[`@Bean`],
|
||||
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Import.html[`@Import`],
|
||||
and https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/DependsOn.html[`@DependsOn`] annotations.
|
||||
* <<beans-annotation-config,Annotation-based configuration>>: define beans using
|
||||
annotation-based configuration metadata.
|
||||
* <<beans-java, Java-based configuration>>: define beans external to your application
|
||||
classes by using Java rather than XML files. To use these features, see the
|
||||
{api-spring-framework}/context/annotation/Configuration.html[`@Configuration`],
|
||||
{api-spring-framework}/context/annotation/Bean.html[`@Bean`],
|
||||
{api-spring-framework}/context/annotation/Import.html[`@Import`],
|
||||
and {api-spring-framework}/context/annotation/DependsOn.html[`@DependsOn`] annotations.
|
||||
|
||||
Spring configuration consists of at least one and typically more than one bean
|
||||
definition that the container must manage. XML-based configuration metadata configures these
|
||||
@@ -124,14 +122,12 @@ beans as `<bean/>` elements inside a top-level `<beans/>` element. Java
|
||||
configuration typically uses `@Bean`-annotated methods within a `@Configuration` class.
|
||||
|
||||
These bean definitions correspond to the actual objects that make up your application.
|
||||
Typically, you define service layer objects, data access objects (DAOs), presentation
|
||||
objects such as Struts `Action` instances, infrastructure objects such as Hibernate
|
||||
`SessionFactories`, JMS `Queues`, and so forth. Typically, one does not configure
|
||||
fine-grained domain objects in the container, because it is usually the responsibility
|
||||
of DAOs and business logic to create and load domain objects. However, you can use
|
||||
Spring's integration with AspectJ to configure objects that have been created outside
|
||||
the control of an IoC container. See <<aop-atconfigurable,Using AspectJ to
|
||||
dependency-inject domain objects with Spring>>.
|
||||
Typically, you define service layer objects, persistence layer objects such as
|
||||
repositories or data access objects (DAOs), presentation objects such as Web controllers,
|
||||
infrastructure objects such as a JPA `EntityManagerFactory`, JMS queues, and so forth.
|
||||
Typically, one does not configure fine-grained domain objects in the container, because
|
||||
it is usually the responsibility of repositories and business logic to create and load
|
||||
domain objects.
|
||||
|
||||
The following example shows the basic structure of XML-based configuration metadata:
|
||||
|
||||
@@ -157,12 +153,11 @@ The following example shows the basic structure of XML-based configuration metad
|
||||
----
|
||||
|
||||
<1> The `id` attribute is a string that identifies the individual bean definition.
|
||||
|
||||
<2> The `class` attribute defines the type of the bean and uses the fully qualified
|
||||
classname.
|
||||
class name.
|
||||
|
||||
The value of the `id` attribute refers to collaborating objects. The XML for
|
||||
referring to collaborating objects is not shown in this example. See
|
||||
The value of the `id` attribute can be used to refer to collaborating objects. The XML
|
||||
for referring to collaborating objects is not shown in this example. See
|
||||
<<beans-dependencies,Dependencies>> for more information.
|
||||
|
||||
|
||||
@@ -2839,7 +2834,7 @@ processed by the Spring `DispatcherServlet`, no special setup is necessary.
|
||||
`DispatcherServlet` already exposes all relevant state.
|
||||
|
||||
If you use a Servlet web container, with requests processed outside of Spring's
|
||||
`DispatcherServlet` (for example, when using JSF or Struts), you need to register the
|
||||
`DispatcherServlet` (for example, when using JSF), you need to register the
|
||||
`org.springframework.web.context.request.RequestContextListener` `ServletRequestListener`.
|
||||
This can be done programmatically by using the `WebApplicationInitializer` interface.
|
||||
Alternatively, add the following declaration to your web application's `web.xml` file:
|
||||
@@ -5205,6 +5200,7 @@ with specific arguments, narrowing the set of type matches so that a specific be
|
||||
chosen for each argument. In the simplest case, this can be a plain descriptive value, as
|
||||
shown in the following example:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5229,18 +5225,20 @@ shown in the following example:
|
||||
// ...
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
You can also specify the `@Qualifier` annotation on individual constructor arguments or
|
||||
method parameters, as shown in the following example:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
public class MovieRecommender {
|
||||
|
||||
private MovieCatalog movieCatalog;
|
||||
private final MovieCatalog movieCatalog;
|
||||
|
||||
private CustomerPreferenceDao customerPreferenceDao;
|
||||
private final CustomerPreferenceDao customerPreferenceDao;
|
||||
|
||||
@Autowired
|
||||
public void prepare(@Qualifier("main") MovieCatalog movieCatalog,
|
||||
@@ -5271,9 +5269,11 @@ method parameters, as shown in the following example:
|
||||
// ...
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
The following example shows corresponding bean definitions.
|
||||
|
||||
--
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -5307,6 +5307,7 @@ The following example shows corresponding bean definitions.
|
||||
is qualified with the same value.
|
||||
<2> The bean with the `action` qualifier value is wired with the constructor argument that
|
||||
is qualified with the same value.
|
||||
--
|
||||
|
||||
For a fallback match, the bean name is considered a default qualifier value. Thus, you
|
||||
can define the bean with an `id` of `main` instead of the nested qualifier element, leading
|
||||
@@ -5384,6 +5385,7 @@ constructor or a multi-argument method.
|
||||
You can create your own custom qualifier annotations. To do so, define an annotation and
|
||||
provide the `@Qualifier` annotation within your definition, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5403,10 +5405,12 @@ provide the `@Qualifier` annotation within your definition, as the following exa
|
||||
@Qualifier
|
||||
annotation class Genre(val value: String)
|
||||
----
|
||||
--
|
||||
|
||||
Then you can provide the custom qualifier on autowired fields and parameters, as the
|
||||
following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5445,6 +5449,7 @@ following example shows:
|
||||
// ...
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
Next, you can provide the information for the candidate bean definitions. You can add
|
||||
`<qualifier/>` tags as sub-elements of the `<bean/>` tag and then specify the `type` and
|
||||
@@ -5453,6 +5458,7 @@ fully-qualified class name of the annotation. Alternately, as a convenience if n
|
||||
conflicting names exists, you can use the short class name. The following example
|
||||
demonstrates both approaches:
|
||||
|
||||
--
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -5480,6 +5486,7 @@ demonstrates both approaches:
|
||||
|
||||
</beans>
|
||||
----
|
||||
--
|
||||
|
||||
In <<beans-classpath-scanning>>, you can see an annotation-based alternative to
|
||||
providing the qualifier metadata in XML. Specifically, see <<beans-scanning-qualifiers>>.
|
||||
@@ -5490,6 +5497,7 @@ several different types of dependencies. For example, you may provide an offline
|
||||
catalog that can be searched when no Internet connection is available. First, define
|
||||
the simple annotation, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5497,7 +5505,6 @@ the simple annotation, as the following example shows:
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Qualifier
|
||||
public @interface Offline {
|
||||
|
||||
}
|
||||
----
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
@@ -5508,10 +5515,12 @@ the simple annotation, as the following example shows:
|
||||
@Qualifier
|
||||
annotation class Offline
|
||||
----
|
||||
--
|
||||
|
||||
Then add the annotation to the field or property to be autowired, as shown in the
|
||||
following example:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5539,9 +5548,11 @@ class MovieRecommender {
|
||||
}
|
||||
----
|
||||
<1> This line adds the `@Offline` annotation.
|
||||
--
|
||||
|
||||
Now the bean definition only needs a qualifier `type`, as shown in the following example:
|
||||
|
||||
--
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<bean class="example.SimpleMovieCatalog">
|
||||
@@ -5550,6 +5561,7 @@ Now the bean definition only needs a qualifier `type`, as shown in the following
|
||||
</bean>
|
||||
----
|
||||
<1> This element specifies the qualifier.
|
||||
--
|
||||
|
||||
|
||||
You can also define custom qualifier annotations that accept named attributes in
|
||||
@@ -5558,6 +5570,7 @@ then specified on a field or parameter to be autowired, a bean definition must m
|
||||
all such attribute values to be considered an autowire candidate. As an example,
|
||||
consider the following annotation definition:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5579,9 +5592,11 @@ consider the following annotation definition:
|
||||
@Qualifier
|
||||
annotation class MovieQualifier(val genre: String, val format: Format)
|
||||
----
|
||||
--
|
||||
|
||||
In this case `Format` is an enum, defined as follows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5596,10 +5611,12 @@ In this case `Format` is an enum, defined as follows:
|
||||
VHS, DVD, BLURAY
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
The fields to be autowired are annotated with the custom qualifier and include values
|
||||
for both attributes: `genre` and `format`, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5648,6 +5665,7 @@ for both attributes: `genre` and `format`, as the following example shows:
|
||||
// ...
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
Finally, the bean definitions should contain matching qualifier values. This example
|
||||
also demonstrates that you can use bean meta attributes instead of the
|
||||
@@ -5656,6 +5674,7 @@ precedence, but the autowiring mechanism falls back on the values provided withi
|
||||
`<meta/>` tags if no such qualifier is present, as in the last two bean definitions in
|
||||
the following example:
|
||||
|
||||
--
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -5699,6 +5718,7 @@ the following example:
|
||||
|
||||
</beans>
|
||||
----
|
||||
--
|
||||
|
||||
|
||||
|
||||
@@ -5830,6 +5850,7 @@ endpoints. Spring supports this pattern for Spring-managed objects as well.
|
||||
the bean name to be injected. In other words, it follows by-name semantics,
|
||||
as demonstrated in the following example:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5855,6 +5876,7 @@ class SimpleMovieLister {
|
||||
}
|
||||
----
|
||||
<1> This line injects a `@Resource`.
|
||||
--
|
||||
|
||||
|
||||
If no name is explicitly specified, the default name is derived from the field name or
|
||||
@@ -5862,6 +5884,7 @@ setter method. In case of a field, it takes the field name. In case of a setter
|
||||
it takes the bean property name. The following example is going to have the bean
|
||||
named `movieFinder` injected into its setter method:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5885,6 +5908,7 @@ named `movieFinder` injected into its setter method:
|
||||
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
NOTE: The name provided with the annotation is resolved as a bean name by the
|
||||
`ApplicationContext` of which the `CommonAnnotationBeanPostProcessor` is aware.
|
||||
@@ -5903,6 +5927,7 @@ Thus, in the following example, the `customerPreferenceDao` field first looks fo
|
||||
named "customerPreferenceDao" and then falls back to a primary type match for the type
|
||||
`CustomerPreferenceDao`:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5940,6 +5965,7 @@ named "customerPreferenceDao" and then falls back to a primary type match for th
|
||||
----
|
||||
<1> The `context` field is injected based on the known resolvable dependency type:
|
||||
`ApplicationContext`.
|
||||
--
|
||||
|
||||
[[beans-value-annotations]]
|
||||
=== Using `@Value`
|
||||
@@ -7515,7 +7541,7 @@ container. It includes the following topics:
|
||||
[[beans-java-basic-concepts]]
|
||||
=== Basic Concepts: `@Bean` and `@Configuration`
|
||||
|
||||
The central artifacts in Spring's new Java-configuration support are
|
||||
The central artifacts in Spring's Java configuration support are
|
||||
`@Configuration`-annotated classes and `@Bean`-annotated methods.
|
||||
|
||||
The `@Bean` annotation is used to indicate that a method instantiates, configures, and
|
||||
@@ -8099,7 +8125,7 @@ class AppConfig {
|
||||
By default, beans defined with Java configuration that have a public `close` or `shutdown`
|
||||
method are automatically enlisted with a destruction callback. If you have a public
|
||||
`close` or `shutdown` method and you do not wish for it to be called when the container
|
||||
shuts down, you can add `@Bean(destroyMethod="")` to your bean definition to disable the
|
||||
shuts down, you can add `@Bean(destroyMethod = "")` to your bean definition to disable the
|
||||
default `(inferred)` mode.
|
||||
|
||||
You may want to do that by default for a resource that you acquire with JNDI, as its
|
||||
@@ -8112,7 +8138,7 @@ The following example shows how to prevent an automatic destruction callback for
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@Bean(destroyMethod="")
|
||||
@Bean(destroyMethod = "")
|
||||
public DataSource dataSource() throws NamingException {
|
||||
return (DataSource) jndiTemplate.lookup("MyDS");
|
||||
}
|
||||
@@ -9456,7 +9482,7 @@ now looks like the following listing:
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@Bean(destroyMethod="")
|
||||
@Bean(destroyMethod = "")
|
||||
public DataSource dataSource() throws Exception {
|
||||
Context ctx = new InitialContext();
|
||||
return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
|
||||
@@ -9495,6 +9521,7 @@ annotation lets you indicate that a component is eligible for registration
|
||||
when one or more specified profiles are active. Using our preceding example, we
|
||||
can rewrite the `dataSource` configuration as follows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -9529,7 +9556,9 @@ can rewrite the `dataSource` configuration as follows:
|
||||
}
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -9537,13 +9566,15 @@ can rewrite the `dataSource` configuration as follows:
|
||||
@Profile("production")
|
||||
public class JndiDataConfig {
|
||||
|
||||
@Bean(destroyMethod="")
|
||||
@Bean(destroyMethod = "") // <1>
|
||||
public DataSource dataSource() throws Exception {
|
||||
Context ctx = new InitialContext();
|
||||
return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> `@Bean(destroyMethod = "")` disables default destroy method inference.
|
||||
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
.Kotlin
|
||||
----
|
||||
@@ -9551,13 +9582,15 @@ can rewrite the `dataSource` configuration as follows:
|
||||
@Profile("production")
|
||||
class JndiDataConfig {
|
||||
|
||||
@Bean(destroyMethod = "")
|
||||
@Bean(destroyMethod = "") // <1>
|
||||
fun dataSource(): DataSource {
|
||||
val ctx = InitialContext()
|
||||
return ctx.lookup("java:comp/env/jdbc/datasource") as DataSource
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> `@Bean(destroyMethod = "")` disables default destroy method inference.
|
||||
--
|
||||
|
||||
NOTE: As mentioned earlier, with `@Bean` methods, you typically choose to use programmatic
|
||||
JNDI lookups, by using either Spring's `JndiTemplate`/`JndiLocatorDelegate` helpers or the
|
||||
@@ -9569,9 +9602,9 @@ profile expression. A profile expression allows for more complicated profile log
|
||||
expressed (for example, `production & us-east`). The following operators are supported in
|
||||
profile expressions:
|
||||
|
||||
* `!`: A logical "`not`" of the profile
|
||||
* `&`: A logical "`and`" of the profiles
|
||||
* `|`: A logical "`or`" of the profiles
|
||||
* `!`: A logical `NOT` of the profile
|
||||
* `&`: A logical `AND` of the profiles
|
||||
* `|`: A logical `OR` of the profiles
|
||||
|
||||
NOTE: You cannot mix the `&` and `|` operators without using parentheses. For example,
|
||||
`production & us-east | eu-central` is not a valid expression. It must be expressed as
|
||||
@@ -9582,6 +9615,7 @@ of creating a custom composed annotation. The following example defines a custom
|
||||
`@Production` annotation that you can use as a drop-in replacement for
|
||||
`@Profile("production")`:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -9599,6 +9633,7 @@ of creating a custom composed annotation. The following example defines a custom
|
||||
@Profile("production")
|
||||
annotation class Production
|
||||
----
|
||||
--
|
||||
|
||||
TIP: If a `@Configuration` class is marked with `@Profile`, all of the `@Bean` methods and
|
||||
`@Import` annotations associated with that class are bypassed unless one or more of
|
||||
@@ -9613,6 +9648,7 @@ active. For example, given `@Profile({"p1", "!p2"})`, registration will occur if
|
||||
of a configuration class (for example, for alternative variants of a particular bean), as
|
||||
the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -9664,6 +9700,7 @@ the following example shows:
|
||||
----
|
||||
<1> The `standaloneDataSource` method is available only in the `development` profile.
|
||||
<2> The `jndiDataSource` method is available only in the `production` profile.
|
||||
--
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -9834,7 +9871,7 @@ activates multiple profiles:
|
||||
Declaratively, `spring.profiles.active` may accept a comma-separated list of profile names,
|
||||
as the following example shows:
|
||||
|
||||
[literal,subs="verbatim,quotes"]
|
||||
[literal,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
-Dspring.profiles.active="profile1,profile2"
|
||||
----
|
||||
@@ -10230,13 +10267,13 @@ handled in the JDK-standard way of resolving messages through `ResourceBundle` o
|
||||
purposes of the example, assume the contents of two of the above resource bundle files
|
||||
are as follows:
|
||||
|
||||
[literal,subs="verbatim,quotes"]
|
||||
[source,properties,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
# in format.properties
|
||||
message=Alligators rock!
|
||||
----
|
||||
|
||||
[literal,subs="verbatim,quotes"]
|
||||
[source,properties,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
# in exceptions.properties
|
||||
argument.required=The {0} argument is required.
|
||||
|
||||
@@ -1634,7 +1634,7 @@ If you prefer XML-based configuration, you can use a
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd>
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
|
||||
<property name="registerDefaultFormatters" value="false" />
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
[[spring-data-tier]]
|
||||
= Data Access
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:tabsize: 4
|
||||
:docinfo1:
|
||||
include::attributes.adoc[]
|
||||
include::page-layout.adoc[]
|
||||
|
||||
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.
|
||||
@@ -3482,6 +3480,7 @@ configure a `DataSource` in your Spring configuration file and then dependency-i
|
||||
that shared `DataSource` bean into your DAO classes. The `JdbcTemplate` is created in
|
||||
the setter for the `DataSource`. This leads to DAOs that resemble the following:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -3506,6 +3505,7 @@ the setter for the `DataSource`. This leads to DAOs that resemble the following:
|
||||
// JDBC-backed implementations of the methods on the CorporateEventDao follow...
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
The following example shows the corresponding XML configuration:
|
||||
|
||||
@@ -3542,6 +3542,7 @@ support for dependency injection. In this case, you can annotate the class with
|
||||
(which makes it a candidate for component-scanning) and annotate the `DataSource` setter
|
||||
method with `@Autowired`. The following example shows how to do so:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -3576,6 +3577,7 @@ method with `@Autowired`. The following example shows how to do so:
|
||||
<1> Annotate the class with `@Repository`.
|
||||
<2> Constructor injection of the `DataSource`.
|
||||
<3> Create a new `JdbcTemplate` with the `DataSource`.
|
||||
--
|
||||
|
||||
|
||||
The following example shows the corresponding XML configuration:
|
||||
@@ -5486,8 +5488,7 @@ example shows such a method:
|
||||
.Java
|
||||
----
|
||||
public List<Actor> searchForActors(int age, String namePattern) {
|
||||
List<Actor> actors = actorSearchMappingQuery.execute(age, namePattern);
|
||||
return actors;
|
||||
return actorSearchMappingQuery.execute(age, namePattern);
|
||||
}
|
||||
----
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
@@ -7080,6 +7081,7 @@ in your Spring configuration file and then dependency-inject
|
||||
that shared `ConnectionFactory` bean into your DAO classes. The `DatabaseClient` is created in
|
||||
the setter for the `ConnectionFactory`. This leads to DAOs that resemble the following:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -7104,12 +7106,14 @@ the setter for the `ConnectionFactory`. This leads to DAOs that resemble the fol
|
||||
// R2DBC-backed implementations of the methods on the CorporateEventDao follow...
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
An alternative to explicit configuration is to use component-scanning and annotation
|
||||
support for dependency injection. In this case, you can annotate the class with `@Component`
|
||||
(which makes it a candidate for component-scanning) and annotate the `ConnectionFactory` setter
|
||||
method with `@Autowired`. The following example shows how to do so:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -7144,6 +7148,7 @@ method with `@Autowired`. The following example shows how to do so:
|
||||
<1> Annotate the class with `@Component`.
|
||||
<2> Constructor injection of the `ConnectionFactory`.
|
||||
<3> Create a new `DatabaseClient` with the `ConnectionFactory`.
|
||||
--
|
||||
|
||||
Regardless of which of the above template initialization styles you choose to use (or
|
||||
not), it is seldom necessary to create a new instance of a `DatabaseClient` class each
|
||||
@@ -8868,9 +8873,10 @@ preamble of the XML configuration file. The following example shows how to do so
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:oxm="http://www.springframework.org/schema/oxm" <1>
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/oxm https://www.springframework.org/schema/oxm/spring-oxm.xsd"> <2>
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/oxm
|
||||
https://www.springframework.org/schema/oxm/spring-oxm.xsd"> <2>
|
||||
----
|
||||
<1> Reference the `oxm` schema.
|
||||
<2> Specify the `oxm` schema location.
|
||||
|
||||
@@ -38,12 +38,15 @@ are available to you:
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:aop="http://www.springframework.org/schema/aop"
|
||||
xmlns:tx="http://www.springframework.org/schema/tx" <1>
|
||||
xmlns:aop="http://www.springframework.org/schema/aop"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd <2>
|
||||
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
|
||||
http://www.springframework.org/schema/beans
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/tx
|
||||
https://www.springframework.org/schema/tx/spring-tx.xsd <2>
|
||||
http://www.springframework.org/schema/aop
|
||||
https://www.springframework.org/schema/aop/spring-aop.xsd">
|
||||
|
||||
<!-- bean definitions here -->
|
||||
|
||||
@@ -79,8 +82,10 @@ the correct schema so that the elements in the `jdbc` namespace are available to
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:jdbc="http://www.springframework.org/schema/jdbc" <1>
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/jdbc https://www.springframework.org/schema/jdbc/spring-jdbc.xsd"> <2>
|
||||
http://www.springframework.org/schema/beans
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/jdbc
|
||||
https://www.springframework.org/schema/jdbc/spring-jdbc.xsd"> <2>
|
||||
|
||||
<!-- bean definitions here -->
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
:noheader:
|
||||
= Spring Framework Documentation
|
||||
include::attributes.adoc[]
|
||||
|
||||
[horizontal]
|
||||
<<overview.adoc#overview, Overview>> :: history, design philosophy, feedback,
|
||||
getting started.
|
||||
<<overview.adoc#overview, Overview>> :: History, Design Philosophy, Feedback,
|
||||
Getting Started.
|
||||
<<core.adoc#spring-core, Core>> :: IoC Container, Events, Resources, i18n,
|
||||
Validation, Data Binding, Type Conversion, SpEL, AOP, AOT.
|
||||
<<testing.adoc#testing, Testing>> :: Mock Objects, TestContext Framework,
|
||||
@@ -15,13 +16,13 @@ STOMP Messaging.
|
||||
<<web-reactive.adoc#spring-webflux, Web Reactive>> :: Spring WebFlux, WebClient,
|
||||
WebSocket, RSocket.
|
||||
<<integration.adoc#spring-integration, Integration>> :: REST Clients, JMS, JCA, JMX,
|
||||
Email, Tasks, Scheduling, Caching.
|
||||
Email, Tasks, Scheduling, Caching, Observability.
|
||||
<<languages.adoc#languages, Languages>> :: Kotlin, Groovy, Dynamic Languages.
|
||||
<<appendix.adoc#appendix, Appendix>> :: Spring properties.
|
||||
https://github.com/spring-projects/spring-framework/wiki[*Wiki*] :: What's New,
|
||||
Upgrade Notes, Supported Versions, and other cross-version information.
|
||||
https://github.com/spring-projects/spring-framework/wiki[Wiki] :: What's New,
|
||||
Upgrade Notes, Supported Versions, additional cross-version information.
|
||||
|
||||
NOTE: This documentation is available in {docs-spring-framework}/reference/html/index.html[HTML] and {docs-spring-framework}/reference/pdf/spring-framework.pdf[PDF] formats.
|
||||
NOTE: This documentation is also available in {docs-spring-framework}/reference/pdf/spring-framework.pdf[PDF] format.
|
||||
|
||||
Rod Johnson, Juergen Hoeller, Keith Donald, Colin Sampaleanu, Rob Harrop, Thomas Risberg,
|
||||
Alef Arendsen, Darren Davison, Dmitriy Kopylenko, Mark Pollack, Thierry Templier, Erwin
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,302 @@
|
||||
[[mail]]
|
||||
= Email
|
||||
|
||||
This section describes how to send email with the Spring Framework.
|
||||
|
||||
.Library dependencies
|
||||
****
|
||||
The following JAR needs to be on the classpath of your application in order to use
|
||||
the Spring Framework's email library:
|
||||
|
||||
* The https://eclipse-ee4j.github.io/mail/[JavaMail / Jakarta Mail 1.6] library
|
||||
|
||||
This library is freely available on the web -- for example, in Maven Central as
|
||||
`com.sun.mail:jakarta.mail`. Please make sure to use the latest 1.6.x version
|
||||
rather than Jakarta Mail 2.0 (which comes with a different package namespace).
|
||||
****
|
||||
|
||||
The Spring Framework provides a helpful utility library for sending email that shields
|
||||
you from the specifics of the underlying mailing system and is responsible for
|
||||
low-level resource handling on behalf of the client.
|
||||
|
||||
The `org.springframework.mail` package is the root level package for the Spring
|
||||
Framework's email support. The central interface for sending emails is the `MailSender`
|
||||
interface. A simple value object that encapsulates the properties of a simple mail such
|
||||
as `from` and `to` (plus many others) is the `SimpleMailMessage` class. This package
|
||||
also contains a hierarchy of checked exceptions that provide a higher level of
|
||||
abstraction over the lower level mail system exceptions, with the root exception being
|
||||
`MailException`. See the {api-spring-framework}/mail/MailException.html[javadoc]
|
||||
for more information on the rich mail exception hierarchy.
|
||||
|
||||
The `org.springframework.mail.javamail.JavaMailSender` interface adds specialized
|
||||
JavaMail features, such as MIME message support to the `MailSender` interface
|
||||
(from which it inherits). `JavaMailSender` also provides a callback interface called
|
||||
`org.springframework.mail.javamail.MimeMessagePreparator` for preparing a `MimeMessage`.
|
||||
|
||||
|
||||
|
||||
[[mail-usage]]
|
||||
== Usage
|
||||
|
||||
Assume that we have a business interface called `OrderManager`, as the following example shows:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
public interface OrderManager {
|
||||
|
||||
void placeOrder(Order order);
|
||||
|
||||
}
|
||||
----
|
||||
|
||||
Further assume that we have a requirement stating that an email message with an
|
||||
order number needs to be generated and sent to a customer who placed the relevant order.
|
||||
|
||||
|
||||
[[mail-usage-simple]]
|
||||
=== Basic `MailSender` and `SimpleMailMessage` Usage
|
||||
|
||||
The following example shows how to use `MailSender` and `SimpleMailMessage` to send an
|
||||
email when someone places an order:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
import org.springframework.mail.MailException;
|
||||
import org.springframework.mail.MailSender;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
|
||||
public class SimpleOrderManager implements OrderManager {
|
||||
|
||||
private MailSender mailSender;
|
||||
private SimpleMailMessage templateMessage;
|
||||
|
||||
public void setMailSender(MailSender mailSender) {
|
||||
this.mailSender = mailSender;
|
||||
}
|
||||
|
||||
public void setTemplateMessage(SimpleMailMessage templateMessage) {
|
||||
this.templateMessage = templateMessage;
|
||||
}
|
||||
|
||||
public void placeOrder(Order order) {
|
||||
|
||||
// Do the business calculations...
|
||||
|
||||
// Call the collaborators to persist the order...
|
||||
|
||||
// Create a thread safe "copy" of the template message and customize it
|
||||
SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
|
||||
msg.setTo(order.getCustomer().getEmailAddress());
|
||||
msg.setText(
|
||||
"Dear " + order.getCustomer().getFirstName()
|
||||
+ order.getCustomer().getLastName()
|
||||
+ ", thank you for placing order. Your order number is "
|
||||
+ order.getOrderNumber());
|
||||
try {
|
||||
this.mailSender.send(msg);
|
||||
}
|
||||
catch (MailException ex) {
|
||||
// simply log it and go on...
|
||||
System.err.println(ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
----
|
||||
|
||||
The following example shows the bean definitions for the preceding code:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
|
||||
<property name="host" value="mail.mycompany.example"/>
|
||||
</bean>
|
||||
|
||||
<!-- this is a template message that we can pre-load with default state -->
|
||||
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
|
||||
<property name="from" value="customerservice@mycompany.example"/>
|
||||
<property name="subject" value="Your order"/>
|
||||
</bean>
|
||||
|
||||
<bean id="orderManager" class="com.mycompany.businessapp.support.SimpleOrderManager">
|
||||
<property name="mailSender" ref="mailSender"/>
|
||||
<property name="templateMessage" ref="templateMessage"/>
|
||||
</bean>
|
||||
----
|
||||
|
||||
|
||||
[[mail-usage-mime]]
|
||||
=== Using `JavaMailSender` and `MimeMessagePreparator`
|
||||
|
||||
This section describes another implementation of `OrderManager` that uses the `MimeMessagePreparator`
|
||||
callback interface. In the following example, the `mailSender` property is of type
|
||||
`JavaMailSender` so that we are able to use the JavaMail `MimeMessage` class:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
import jakarta.mail.Message;
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.internet.InternetAddress;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import org.springframework.mail.MailException;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.MimeMessagePreparator;
|
||||
|
||||
public class SimpleOrderManager implements OrderManager {
|
||||
|
||||
private JavaMailSender mailSender;
|
||||
|
||||
public void setMailSender(JavaMailSender mailSender) {
|
||||
this.mailSender = mailSender;
|
||||
}
|
||||
|
||||
public void placeOrder(final Order order) {
|
||||
// Do the business calculations...
|
||||
// Call the collaborators to persist the order...
|
||||
|
||||
MimeMessagePreparator preparator = new MimeMessagePreparator() {
|
||||
public void prepare(MimeMessage mimeMessage) throws Exception {
|
||||
mimeMessage.setRecipient(Message.RecipientType.TO,
|
||||
new InternetAddress(order.getCustomer().getEmailAddress()));
|
||||
mimeMessage.setFrom(new InternetAddress("mail@mycompany.example"));
|
||||
mimeMessage.setText("Dear " + order.getCustomer().getFirstName() + " " +
|
||||
order.getCustomer().getLastName() + ", thanks for your order. " +
|
||||
"Your order number is " + order.getOrderNumber() + ".");
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
this.mailSender.send(preparator);
|
||||
}
|
||||
catch (MailException ex) {
|
||||
// simply log it and go on...
|
||||
System.err.println(ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
----
|
||||
|
||||
NOTE: The mail code is a crosscutting concern and could well be a candidate for
|
||||
refactoring into a <<core.adoc#aop, custom Spring AOP aspect>>, which could then
|
||||
be run at appropriate joinpoints on the `OrderManager` target.
|
||||
|
||||
The Spring Framework's mail support ships with the standard JavaMail implementation.
|
||||
See the relevant javadoc for more information.
|
||||
|
||||
|
||||
|
||||
[[mail-javamail-mime]]
|
||||
== Using the JavaMail `MimeMessageHelper`
|
||||
|
||||
A class that comes in pretty handy when dealing with JavaMail messages is
|
||||
`org.springframework.mail.javamail.MimeMessageHelper`, which shields you from
|
||||
having to use the verbose JavaMail API. Using the `MimeMessageHelper`, it is
|
||||
pretty easy to create a `MimeMessage`, as the following example shows:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
// of course you would use DI in any real-world cases
|
||||
JavaMailSenderImpl sender = new JavaMailSenderImpl();
|
||||
sender.setHost("mail.host.com");
|
||||
|
||||
MimeMessage message = sender.createMimeMessage();
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message);
|
||||
helper.setTo("test@host.com");
|
||||
helper.setText("Thank you for ordering!");
|
||||
|
||||
sender.send(message);
|
||||
----
|
||||
|
||||
|
||||
[[mail-javamail-mime-attachments]]
|
||||
=== Sending Attachments and Inline Resources
|
||||
|
||||
Multipart email messages allow for both attachments and inline resources. Examples of
|
||||
inline resources include an image or a stylesheet that you want to use in your message but
|
||||
that you do not want displayed as an attachment.
|
||||
|
||||
[[mail-javamail-mime-attachments-attachment]]
|
||||
==== Attachments
|
||||
|
||||
The following example shows you how to use the `MimeMessageHelper` to send an email
|
||||
with a single JPEG image attachment:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
JavaMailSenderImpl sender = new JavaMailSenderImpl();
|
||||
sender.setHost("mail.host.com");
|
||||
|
||||
MimeMessage message = sender.createMimeMessage();
|
||||
|
||||
// use the true flag to indicate you need a multipart message
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true);
|
||||
helper.setTo("test@host.com");
|
||||
|
||||
helper.setText("Check out this image!");
|
||||
|
||||
// let's attach the infamous windows Sample file (this time copied to c:/)
|
||||
FileSystemResource file = new FileSystemResource(new File("c:/Sample.jpg"));
|
||||
helper.addAttachment("CoolImage.jpg", file);
|
||||
|
||||
sender.send(message);
|
||||
----
|
||||
|
||||
[[mail-javamail-mime-attachments-inline]]
|
||||
==== Inline Resources
|
||||
|
||||
The following example shows you how to use the `MimeMessageHelper` to send an email
|
||||
with an inline image:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
JavaMailSenderImpl sender = new JavaMailSenderImpl();
|
||||
sender.setHost("mail.host.com");
|
||||
|
||||
MimeMessage message = sender.createMimeMessage();
|
||||
|
||||
// use the true flag to indicate you need a multipart message
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true);
|
||||
helper.setTo("test@host.com");
|
||||
|
||||
// use the true flag to indicate the text included is HTML
|
||||
helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);
|
||||
|
||||
// let's include the infamous windows Sample file (this time copied to c:/)
|
||||
FileSystemResource res = new FileSystemResource(new File("c:/Sample.jpg"));
|
||||
helper.addInline("identifier1234", res);
|
||||
|
||||
sender.send(message);
|
||||
----
|
||||
|
||||
WARNING: Inline resources are added to the `MimeMessage` by using the specified `Content-ID`
|
||||
(`identifier1234` in the above example). The order in which you add the text
|
||||
and the resource are very important. Be sure to first add the text and then
|
||||
the resources. If you are doing it the other way around, it does not work.
|
||||
|
||||
|
||||
[[mail-templates]]
|
||||
=== Creating Email Content by Using a Templating Library
|
||||
|
||||
The code in the examples shown in the previous sections explicitly created the content of the email message,
|
||||
by using methods calls such as `message.setText(..)`. This is fine for simple cases, and it
|
||||
is okay in the context of the aforementioned examples, where the intent was to show you
|
||||
the very basics of the API.
|
||||
|
||||
In your typical enterprise application, though, developers often do not create the content
|
||||
of email messages by using the previously shown approach for a number of reasons:
|
||||
|
||||
* Creating HTML-based email content in Java code is tedious and error prone.
|
||||
* There is no clear separation between display logic and business logic.
|
||||
* Changing the display structure of the email content requires writing Java code,
|
||||
recompiling, redeploying, and so on.
|
||||
|
||||
Typically, the approach taken to address these issues is to use a template library (such
|
||||
as FreeMarker) to define the display structure of email content. This leaves your code
|
||||
tasked only with creating the data that is to be rendered in the email template and
|
||||
sending the email. It is definitely a best practice when the content of your email messages
|
||||
becomes even moderately complex, and, with the Spring Framework's support classes for
|
||||
FreeMarker, it becomes quite easy to do.
|
||||
|
||||
@@ -28,8 +28,10 @@ correct schema so that the elements in the `jee` namespace are available to you:
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:jee="http://www.springframework.org/schema/jee"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/jee https://www.springframework.org/schema/jee/spring-jee.xsd">
|
||||
http://www.springframework.org/schema/beans
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/jee
|
||||
https://www.springframework.org/schema/jee/spring-jee.xsd">
|
||||
|
||||
<!-- bean definitions here -->
|
||||
|
||||
@@ -287,8 +289,10 @@ are available to you:
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:jms="http://www.springframework.org/schema/jms"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/jms https://www.springframework.org/schema/jms/spring-jms.xsd">
|
||||
http://www.springframework.org/schema/beans
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/jms
|
||||
https://www.springframework.org/schema/jms/spring-jms.xsd">
|
||||
|
||||
<!-- bean definitions here -->
|
||||
|
||||
@@ -324,8 +328,10 @@ the correct schema so that the elements in the `cache` namespace are available t
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:cache="http://www.springframework.org/schema/cache"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/cache https://www.springframework.org/schema/cache/spring-cache.xsd">
|
||||
http://www.springframework.org/schema/beans
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/cache
|
||||
https://www.springframework.org/schema/cache/spring-cache.xsd">
|
||||
|
||||
<!-- bean definitions here -->
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,175 @@
|
||||
[[integration.observability]]
|
||||
= Observability Support
|
||||
|
||||
Micrometer defines an https://micrometer.io/docs/observation[Observation concept that enables both Metrics and Traces] in applications.
|
||||
Metrics support offers a way to create timers, gauges or counters for collecting statistics about the runtime behavior of your application.
|
||||
Metrics can help you to track error rates, usage patterns, performance and more.
|
||||
Traces provide a holistic view of an entire system, crossing application boundaries; you can zoom in on particular user requests and follow their entire completion across applications.
|
||||
|
||||
Spring Framework instruments various parts of its own codebase to publish observations if an `ObservationRegistry` is configured.
|
||||
You can learn more about {docs-spring-boot}/html/actuator.html#actuator.metrics[configuring the observability infrastructure in Spring Boot].
|
||||
|
||||
[[integration.observability.concepts]]
|
||||
== Micrometer Observation concepts
|
||||
|
||||
If you are not familiar with Micrometer Observation, here's a quick summary of the new concepts you should know about.
|
||||
|
||||
* `Observation` is the actual recording of something happening in your application. This is processed by `ObservationHandler` implementations to produce metrics or traces.
|
||||
* Each observation has a corresponding `ObservationContext` implementation; this type holds all the relevant information for extracting metadata for it.
|
||||
In the case of an HTTP server observation, the context implementation could hold the HTTP request, the HTTP response, any Exception thrown during processing...
|
||||
* Each `Observation` holds `KeyValues` metadata. In the case of a server HTTP observation, this could be the HTTP request method, the HTTP response status...
|
||||
This metadata is contributed by `ObservationConvention` implementations which should declare the type of `ObservationContext` they support.
|
||||
* `KeyValues` are said to be "low cardinality" if there is a low, bounded number of possible values for the `KeyValue` tuple (HTTP method is a good example).
|
||||
Low cardinality values are contributed to metrics only.
|
||||
High cardinality values are on the other hand unbounded (for example, HTTP request URIs) and are only contributed to Traces.
|
||||
* An `ObservationDocumentation` documents all observations in a particular domain, listing the expected key names and their meaning.
|
||||
|
||||
|
||||
[[integration.observability.config]]
|
||||
== Configuring Observations
|
||||
|
||||
Global configuration options are available at the `ObservationRegistry#observationConfig()` level.
|
||||
Each instrumented component will provide two extension points:
|
||||
|
||||
* setting the `ObservationRegistry`; if not set, observations will not be recorded and will be no-ops
|
||||
* providing a custom `ObservationConvention` to change the default observation name and extracted `KeyValues`
|
||||
|
||||
|
||||
[[integration.observability.config.conventions]]
|
||||
=== Using custom Observation conventions
|
||||
|
||||
Let's take the example of the Spring MVC "http.server.requests" metrics instrumentation with the `ServerHttpObservationFilter`.
|
||||
This observation is using a `ServerRequestObservationConvention` with a `ServerRequestObservationContext`; custom conventions can be configured on the Servlet filter.
|
||||
If you would like to customize the metadata produced with the observation, you can extend the `DefaultServerRequestObservationConvention` for your requirements:
|
||||
|
||||
include::code:ExtendedServerRequestObservationConvention[]
|
||||
|
||||
If you want full control, you can then implement the entire convention contract for the observation you're interested in:
|
||||
|
||||
include::code:CustomServerRequestObservationConvention[]
|
||||
|
||||
You can also achieve similar goals using a custom `ObservationFilter` - adding or removing key values for an observation.
|
||||
Filters do not replace the default convention and are used as a post-processing component.
|
||||
|
||||
include::code:ServerRequestObservationFilter[]
|
||||
|
||||
You can configure `ObservationFilter` instances on the `ObservationRegistry`.
|
||||
|
||||
|
||||
[[integration.observability.http-server]]
|
||||
== HTTP Server instrumentation
|
||||
|
||||
HTTP server exchanges observations are created with the name `"http.server.requests"` for Servlet and Reactive applications.
|
||||
|
||||
[[integration.observability.http-server.servlet]]
|
||||
=== Servlet applications
|
||||
|
||||
Applications need to configure the `org.springframework.web.filter.ServerHttpObservationFilter` Servlet filter in their application.
|
||||
It is using the `org.springframework.http.server.observation.DefaultServerRequestObservationConvention` by default, backed by the `ServerRequestObservationContext`.
|
||||
|
||||
By default, the following `KeyValues` are created:
|
||||
|
||||
.Low cardinality Keys
|
||||
[cols="a,a"]
|
||||
|===
|
||||
|Name | Description
|
||||
|`exception` _(required)_|Name of the exception thrown during the exchange, or `KeyValue#NONE_VALUE`} if no exception happened.
|
||||
|`method` _(required)_|Name of HTTP request method or `"none"` if the request was not received properly.
|
||||
|`outcome` _(required)_|Outcome of the HTTP server exchange.
|
||||
|`status` _(required)_|HTTP response raw status code, or `"UNKNOWN"` if no response was created.
|
||||
|`uri` _(required)_|URI pattern for the matching handler if available, falling back to `REDIRECTION` for 3xx responses, `NOT_FOUND` for 404 responses, `root` for requests with no path info, and `UNKNOWN` for all other requests.
|
||||
|===
|
||||
|
||||
.High cardinality Keys
|
||||
[cols="a,a"]
|
||||
|===
|
||||
|Name | Description
|
||||
|`http.url` _(required)_|HTTP request URI.
|
||||
|===
|
||||
|
||||
|
||||
[[integration.observability.http-server.reactive]]
|
||||
=== Reactive applications
|
||||
|
||||
Applications need to configure the `org.springframework.web.filter.reactive.ServerHttpObservationFilter` reactive `WebFilter` in their application.
|
||||
It is using the `org.springframework.http.server.reactive.observation.DefaultServerRequestObservationConvention` by default, backed by the `ServerRequestObservationContext`.
|
||||
|
||||
By default, the following `KeyValues` are created:
|
||||
|
||||
.Low cardinality Keys
|
||||
[cols="a,a"]
|
||||
|===
|
||||
|Name | Description
|
||||
|`exception` _(required)_|Name of the exception thrown during the exchange, or `"none"` if no exception happened.
|
||||
|`method` _(required)_|Name of HTTP request method or `"none"` if the request was not received properly.
|
||||
|`outcome` _(required)_|Outcome of the HTTP server exchange.
|
||||
|`status` _(required)_|HTTP response raw status code, or `"UNKNOWN"` if no response was created.
|
||||
|`uri` _(required)_|URI pattern for the matching handler if available, falling back to `REDIRECTION` for 3xx responses, `NOT_FOUND` for 404 responses, `root` for requests with no path info, and `UNKNOWN` for all other requests.
|
||||
|===
|
||||
|
||||
.High cardinality Keys
|
||||
[cols="a,a"]
|
||||
|===
|
||||
|Name | Description
|
||||
|`http.url` _(required)_|HTTP request URI.
|
||||
|===
|
||||
|
||||
|
||||
|
||||
[[integration.observability.http-client]]
|
||||
== HTTP Client instrumentation
|
||||
|
||||
HTTP client exchanges observations are created with the name `"http.client.requests"` for blocking and reactive clients.
|
||||
Unlike their server counterparts, the instrumentation is implemented directly in the client so the only required step is to configure an `ObservationRegistry` on the client.
|
||||
|
||||
[[integration.observability.http-client.resttemplate]]
|
||||
=== RestTemplate
|
||||
|
||||
Instrumentation is using the `org.springframework.http.client.observation.ClientRequestObservationConvention` by default, backed by the `ClientRequestObservationContext`.
|
||||
|
||||
.Low cardinality Keys
|
||||
[cols="a,a"]
|
||||
|===
|
||||
|Name | Description
|
||||
|`exception` _(required)_|Name of the exception thrown during the exchange, or `"none"` if no exception happened.
|
||||
|`method` _(required)_|Name of HTTP request method or `"none"` if the request could not be created.
|
||||
|`outcome` _(required)_|Outcome of the HTTP client exchange.
|
||||
|`status` _(required)_|HTTP response raw status code, or `"IO_ERROR"` in case of `IOException`, or `"CLIENT_ERROR"` if no response was received.
|
||||
|`uri` _(required)_|URI template used for HTTP request, or `"none"` if none was provided.
|
||||
|===
|
||||
|
||||
.High cardinality Keys
|
||||
[cols="a,a"]
|
||||
|===
|
||||
|Name | Description
|
||||
|`client.name` _(required)_|Client name derived from the request URI host.
|
||||
|`http.url` _(required)_|HTTP request URI.
|
||||
|===
|
||||
|
||||
|
||||
|
||||
[[integration.observability.http-client.webclient]]
|
||||
=== WebClient
|
||||
|
||||
Instrumentation is using the `org.springframework.web.reactive.function.client.ClientRequestObservationConvention` by default, backed by the `ClientRequestObservationContext`.
|
||||
|
||||
.Low cardinality Keys
|
||||
[cols="a,a"]
|
||||
|===
|
||||
|Name | Description
|
||||
|`exception` _(required)_|Name of the exception thrown during the exchange, or `"none"` if no exception happened.
|
||||
|`method` _(required)_|Name of HTTP request method or `"none"` if the request could not be created.
|
||||
|`outcome` _(required)_|Outcome of the HTTP client exchange.
|
||||
|`status` _(required)_|HTTP response raw status code, or `"IO_ERROR"` in case of `IOException`, or `"CLIENT_ERROR"` if no response was received.
|
||||
|`uri` _(required)_|URI template used for HTTP request, or `"none"` if none was provided.
|
||||
|===
|
||||
|
||||
.High cardinality Keys
|
||||
[cols="a,a"]
|
||||
|===
|
||||
|Name | Description
|
||||
|`client.name` _(required)_|Client name derived from the request URI host.
|
||||
|`http.url` _(required)_|HTTP request URI.
|
||||
|===
|
||||
|
||||
|
||||
@@ -0,0 +1,517 @@
|
||||
[[rest-client-access]]
|
||||
= REST Clients
|
||||
|
||||
The Spring Framework provides the following choices for making calls to REST endpoints:
|
||||
|
||||
* <<rest-webclient>> - non-blocking, reactive client w fluent API.
|
||||
* <<rest-resttemplate>> - synchronous client with template method API.
|
||||
* <<rest-http-interface>> - annotated interface with generated, dynamic proxy implementation.
|
||||
|
||||
|
||||
[[rest-webclient]]
|
||||
== `WebClient`
|
||||
|
||||
`WebClient` is a non-blocking, reactive client to perform HTTP requests. It was
|
||||
introduced in 5.0 and offers an alternative to the `RestTemplate`, with support for
|
||||
synchronous, asynchronous, and streaming scenarios.
|
||||
|
||||
`WebClient` supports the following:
|
||||
|
||||
* Non-blocking I/O.
|
||||
* Reactive Streams back pressure.
|
||||
* High concurrency with fewer hardware resources.
|
||||
* Functional-style, fluent API that takes advantage of Java 8 lambdas.
|
||||
* Synchronous and asynchronous interactions.
|
||||
* Streaming up to or streaming down from a server.
|
||||
|
||||
See <<web-reactive.adoc#webflux-client, WebClient>> for more details.
|
||||
|
||||
|
||||
|
||||
|
||||
[[rest-resttemplate]]
|
||||
== `RestTemplate`
|
||||
|
||||
The `RestTemplate` provides a higher level API over HTTP client libraries. It makes it
|
||||
easy to invoke REST endpoints in a single line. It exposes the following groups of
|
||||
overloaded methods:
|
||||
|
||||
NOTE: `RestTemplate` is in maintenance mode, with only requests for minor
|
||||
changes and bugs to be accepted. Please, consider using the
|
||||
<<web-reactive.adoc#webflux-client, WebClient>> instead.
|
||||
|
||||
[[rest-overview-of-resttemplate-methods-tbl]]
|
||||
.RestTemplate methods
|
||||
[cols="1,3"]
|
||||
|===
|
||||
| Method group | Description
|
||||
|
||||
| `getForObject`
|
||||
| Retrieves a representation via GET.
|
||||
|
||||
| `getForEntity`
|
||||
| Retrieves a `ResponseEntity` (that is, status, headers, and body) by using GET.
|
||||
|
||||
| `headForHeaders`
|
||||
| Retrieves all headers for a resource by using HEAD.
|
||||
|
||||
| `postForLocation`
|
||||
| Creates a new resource by using POST and returns the `Location` header from the response.
|
||||
|
||||
| `postForObject`
|
||||
| Creates a new resource by using POST and returns the representation from the response.
|
||||
|
||||
| `postForEntity`
|
||||
| Creates a new resource by using POST and returns the representation from the response.
|
||||
|
||||
| `put`
|
||||
| Creates or updates a resource by using PUT.
|
||||
|
||||
| `patchForObject`
|
||||
| Updates a resource by using PATCH and returns the representation from the response.
|
||||
Note that the JDK `HttpURLConnection` does not support `PATCH`, but Apache
|
||||
HttpComponents and others do.
|
||||
|
||||
| `delete`
|
||||
| Deletes the resources at the specified URI by using DELETE.
|
||||
|
||||
| `optionsForAllow`
|
||||
| Retrieves allowed HTTP methods for a resource by using ALLOW.
|
||||
|
||||
| `exchange`
|
||||
| More generalized (and less opinionated) version of the preceding methods that provides extra
|
||||
flexibility when needed. It accepts a `RequestEntity` (including HTTP method, URL, headers,
|
||||
and body as input) and returns a `ResponseEntity`.
|
||||
|
||||
These methods allow the use of `ParameterizedTypeReference` instead of `Class` to specify
|
||||
a response type with generics.
|
||||
|
||||
| `execute`
|
||||
| The most generalized way to perform a request, with full control over request
|
||||
preparation and response extraction through callback interfaces.
|
||||
|
||||
|===
|
||||
|
||||
[[rest-resttemplate-create]]
|
||||
=== Initialization
|
||||
|
||||
The default constructor uses `java.net.HttpURLConnection` to perform requests. You can
|
||||
switch to a different HTTP library with an implementation of `ClientHttpRequestFactory`.
|
||||
There is built-in support for the following:
|
||||
|
||||
* Apache HttpComponents
|
||||
* Netty
|
||||
* OkHttp
|
||||
|
||||
For example, to switch to Apache HttpComponents, you can use the following:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
|
||||
----
|
||||
|
||||
Each `ClientHttpRequestFactory` exposes configuration options specific to the underlying
|
||||
HTTP client library -- for example, for credentials, connection pooling, and other details.
|
||||
|
||||
TIP: Note that the `java.net` implementation for HTTP requests can raise an exception when
|
||||
accessing the status of a response that represents an error (such as 401). If this is an
|
||||
issue, switch to another HTTP client library.
|
||||
|
||||
[[rest-resttemplate-uri]]
|
||||
==== URIs
|
||||
|
||||
Many of the `RestTemplate` methods accept a URI template and URI template variables,
|
||||
either as a `String` variable argument, or as `Map<String,String>`.
|
||||
|
||||
The following example uses a `String` variable argument:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
String result = restTemplate.getForObject(
|
||||
"https://example.com/hotels/{hotel}/bookings/{booking}", String.class, "42", "21");
|
||||
----
|
||||
|
||||
The following example uses a `Map<String, String>`:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
Map<String, String> vars = Collections.singletonMap("hotel", "42");
|
||||
|
||||
String result = restTemplate.getForObject(
|
||||
"https://example.com/hotels/{hotel}/rooms/{hotel}", String.class, vars);
|
||||
----
|
||||
|
||||
Keep in mind URI templates are automatically encoded, as the following example shows:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
restTemplate.getForObject("https://example.com/hotel list", String.class);
|
||||
|
||||
// Results in request to "https://example.com/hotel%20list"
|
||||
----
|
||||
|
||||
You can use the `uriTemplateHandler` property of `RestTemplate` to customize how URIs
|
||||
are encoded. Alternatively, you can prepare a `java.net.URI` and pass it into one of
|
||||
the `RestTemplate` methods that accepts a `URI`.
|
||||
|
||||
For more details on working with and encoding URIs, see <<web.adoc#mvc-uri-building, URI Links>>.
|
||||
|
||||
[[rest-template-headers]]
|
||||
==== Headers
|
||||
|
||||
You can use the `exchange()` methods to specify request headers, as the following example shows:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
String uriTemplate = "https://example.com/hotels/{hotel}";
|
||||
URI uri = UriComponentsBuilder.fromUriString(uriTemplate).build(42);
|
||||
|
||||
RequestEntity<Void> requestEntity = RequestEntity.get(uri)
|
||||
.header("MyRequestHeader", "MyValue")
|
||||
.build();
|
||||
|
||||
ResponseEntity<String> response = template.exchange(requestEntity, String.class);
|
||||
|
||||
String responseHeader = response.getHeaders().getFirst("MyResponseHeader");
|
||||
String body = response.getBody();
|
||||
----
|
||||
|
||||
You can obtain response headers through many `RestTemplate` method variants that return
|
||||
`ResponseEntity`.
|
||||
|
||||
[[rest-template-body]]
|
||||
=== Body
|
||||
|
||||
Objects passed into and returned from `RestTemplate` methods are converted to and from raw
|
||||
content with the help of an `HttpMessageConverter`.
|
||||
|
||||
On a POST, an input object is serialized to the request body, as the following example shows:
|
||||
|
||||
----
|
||||
URI location = template.postForLocation("https://example.com/people", person);
|
||||
----
|
||||
|
||||
You need not explicitly set the Content-Type header of the request. In most cases,
|
||||
you can find a compatible message converter based on the source `Object` type, and the chosen
|
||||
message converter sets the content type accordingly. If necessary, you can use the
|
||||
`exchange` methods to explicitly provide the `Content-Type` request header, and that, in
|
||||
turn, influences what message converter is selected.
|
||||
|
||||
On a GET, the body of the response is deserialized to an output `Object`, as the following example shows:
|
||||
|
||||
----
|
||||
Person person = restTemplate.getForObject("https://example.com/people/{id}", Person.class, 42);
|
||||
----
|
||||
|
||||
The `Accept` header of the request does not need to be explicitly set. In most cases,
|
||||
a compatible message converter can be found based on the expected response type, which
|
||||
then helps to populate the `Accept` header. If necessary, you can use the `exchange`
|
||||
methods to provide the `Accept` header explicitly.
|
||||
|
||||
By default, `RestTemplate` registers all built-in
|
||||
<<rest-message-conversion, message converters>>, depending on classpath checks that help
|
||||
to determine what optional conversion libraries are present. You can also set the message
|
||||
converters to use explicitly.
|
||||
|
||||
[[rest-message-conversion]]
|
||||
==== Message Conversion
|
||||
[.small]#<<web-reactive.adoc#webflux-codecs, WebFlux>>#
|
||||
|
||||
The `spring-web` module contains the `HttpMessageConverter` contract for reading and
|
||||
writing the body of HTTP requests and responses through `InputStream` and `OutputStream`.
|
||||
`HttpMessageConverter` instances are used on the client side (for example, in the `RestTemplate`) and
|
||||
on the server side (for example, in Spring MVC REST controllers).
|
||||
|
||||
Concrete implementations for the main media (MIME) types are provided in the framework
|
||||
and are, by default, registered with the `RestTemplate` on the client side and with
|
||||
`RequestMappingHandlerAdapter` on the server side (see
|
||||
<<web.adoc#mvc-config-message-converters, Configuring Message Converters>>).
|
||||
|
||||
The implementations of `HttpMessageConverter` are described in the following sections.
|
||||
For all converters, a default media type is used, but you can override it by setting the
|
||||
`supportedMediaTypes` bean property. The following table describes each implementation:
|
||||
|
||||
[[rest-message-converters-tbl]]
|
||||
.HttpMessageConverter Implementations
|
||||
[cols="1,3"]
|
||||
|===
|
||||
| MessageConverter | Description
|
||||
|
||||
| `StringHttpMessageConverter`
|
||||
| An `HttpMessageConverter` implementation that can read and write `String` instances from the HTTP
|
||||
request and response. By default, this converter supports all text media types
|
||||
(`text/{asterisk}`) and writes with a `Content-Type` of `text/plain`.
|
||||
|
||||
| `FormHttpMessageConverter`
|
||||
| An `HttpMessageConverter` implementation that can read and write form data from the HTTP
|
||||
request and response. By default, this converter reads and writes the
|
||||
`application/x-www-form-urlencoded` media type. Form data is read from and written into a
|
||||
`MultiValueMap<String, String>`. The converter can also write (but not read) multipart
|
||||
data read from a `MultiValueMap<String, Object>`. By default, `multipart/form-data` is
|
||||
supported. As of Spring Framework 5.2, additional multipart subtypes can be supported for
|
||||
writing form data. Consult the javadoc for `FormHttpMessageConverter` for further details.
|
||||
|
||||
| `ByteArrayHttpMessageConverter`
|
||||
| An `HttpMessageConverter` implementation that can read and write byte arrays from the
|
||||
HTTP request and response. By default, this converter supports all media types (`{asterisk}/{asterisk}`)
|
||||
and writes with a `Content-Type` of `application/octet-stream`. You can override this
|
||||
by setting the `supportedMediaTypes` property and overriding `getContentType(byte[])`.
|
||||
|
||||
| `MarshallingHttpMessageConverter`
|
||||
| An `HttpMessageConverter` implementation that can read and write XML by using Spring's
|
||||
`Marshaller` and `Unmarshaller` abstractions from the `org.springframework.oxm` package.
|
||||
This converter requires a `Marshaller` and `Unmarshaller` before it can be used. You can inject these
|
||||
through constructor or bean properties. By default, this converter supports
|
||||
`text/xml` and `application/xml`.
|
||||
|
||||
| `MappingJackson2HttpMessageConverter`
|
||||
| An `HttpMessageConverter` implementation that can read and write JSON by using Jackson's
|
||||
`ObjectMapper`. You can customize JSON mapping as needed through the use of Jackson's
|
||||
provided annotations. When you need further control (for cases where custom JSON
|
||||
serializers/deserializers need to be provided for specific types), you can inject a custom `ObjectMapper`
|
||||
through the `ObjectMapper` property. By default, this
|
||||
converter supports `application/json`.
|
||||
|
||||
| `MappingJackson2XmlHttpMessageConverter`
|
||||
| An `HttpMessageConverter` implementation that can read and write XML by using
|
||||
https://github.com/FasterXML/jackson-dataformat-xml[Jackson XML] extension's
|
||||
`XmlMapper`. You can customize XML mapping as needed through the use of JAXB
|
||||
or Jackson's provided annotations. When you need further control (for cases where custom XML
|
||||
serializers/deserializers need to be provided for specific types), you can inject a custom `XmlMapper`
|
||||
through the `ObjectMapper` property. By default, this
|
||||
converter supports `application/xml`.
|
||||
|
||||
| `SourceHttpMessageConverter`
|
||||
| An `HttpMessageConverter` implementation that can read and write
|
||||
`javax.xml.transform.Source` from the HTTP request and response. Only `DOMSource`,
|
||||
`SAXSource`, and `StreamSource` are supported. By default, this converter supports
|
||||
`text/xml` and `application/xml`.
|
||||
|
||||
| `BufferedImageHttpMessageConverter`
|
||||
| An `HttpMessageConverter` implementation that can read and write
|
||||
`java.awt.image.BufferedImage` from the HTTP request and response. This converter reads
|
||||
and writes the media type supported by the Java I/O API.
|
||||
|
||||
|===
|
||||
|
||||
[[rest-template-jsonview]]
|
||||
=== Jackson JSON Views
|
||||
|
||||
You can specify a https://www.baeldung.com/jackson-json-view-annotation[Jackson JSON View]
|
||||
to serialize only a subset of the object properties, as the following example shows:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
MappingJacksonValue value = new MappingJacksonValue(new User("eric", "7!jd#h23"));
|
||||
value.setSerializationView(User.WithoutPasswordView.class);
|
||||
|
||||
RequestEntity<MappingJacksonValue> requestEntity =
|
||||
RequestEntity.post(new URI("https://example.com/user")).body(value);
|
||||
|
||||
ResponseEntity<String> response = template.exchange(requestEntity, String.class);
|
||||
----
|
||||
|
||||
[[rest-template-multipart]]
|
||||
=== Multipart
|
||||
|
||||
To send multipart data, you need to provide a `MultiValueMap<String, Object>` whose values
|
||||
may be an `Object` for part content, a `Resource` for a file part, or an `HttpEntity` for
|
||||
part content with headers. For example:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
|
||||
|
||||
parts.add("fieldPart", "fieldValue");
|
||||
parts.add("filePart", new FileSystemResource("...logo.png"));
|
||||
parts.add("jsonPart", new Person("Jason"));
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_XML);
|
||||
parts.add("xmlPart", new HttpEntity<>(myBean, headers));
|
||||
----
|
||||
|
||||
In most cases, you do not have to specify the `Content-Type` for each part. The content
|
||||
type is determined automatically based on the `HttpMessageConverter` chosen to serialize
|
||||
it or, in the case of a `Resource` based on the file extension. If necessary, you can
|
||||
explicitly provide the `MediaType` with an `HttpEntity` wrapper.
|
||||
|
||||
Once the `MultiValueMap` is ready, you can pass it to the `RestTemplate`, as show below:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
MultiValueMap<String, Object> parts = ...;
|
||||
template.postForObject("https://example.com/upload", parts, Void.class);
|
||||
----
|
||||
|
||||
If the `MultiValueMap` contains at least one non-`String` value, the `Content-Type` is set
|
||||
to `multipart/form-data` by the `FormHttpMessageConverter`. If the `MultiValueMap` has
|
||||
`String` values the `Content-Type` is defaulted to `application/x-www-form-urlencoded`.
|
||||
If necessary the `Content-Type` may also be set explicitly.
|
||||
|
||||
|
||||
[[rest-http-interface]]
|
||||
== HTTP Interface
|
||||
|
||||
The Spring Framework lets you define an HTTP service as a Java interface with annotated
|
||||
methods for HTTP exchanges. You can then generate a proxy that implements this interface
|
||||
and performs the exchanges. This helps to simplify HTTP remote access which often
|
||||
involves a facade that wraps the details of using the underlying HTTP client.
|
||||
|
||||
One, declare an interface with `@HttpExchange` methods:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
interface RepositoryService {
|
||||
|
||||
@GetExchange("/repos/{owner}/{repo}")
|
||||
Repository getRepository(@PathVariable String owner, @PathVariable String repo);
|
||||
|
||||
// more HTTP exchange methods...
|
||||
|
||||
}
|
||||
----
|
||||
|
||||
Two, create a proxy that will perform the declared HTTP exchanges:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
WebClient client = WebClient.builder().baseUrl("https://api.github.com/").build();
|
||||
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();
|
||||
|
||||
RepositoryService service = factory.createClient(RepositoryService.class);
|
||||
----
|
||||
|
||||
`@HttpExchange` is supported at the type level where it applies to all methods:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
@HttpExchange(url = "/repos/{owner}/{repo}", accept = "application/vnd.github.v3+json")
|
||||
interface RepositoryService {
|
||||
|
||||
@GetExchange
|
||||
Repository getRepository(@PathVariable String owner, @PathVariable String repo);
|
||||
|
||||
@PatchExchange(contentType = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
|
||||
void updateRepository(@PathVariable String owner, @PathVariable String repo,
|
||||
@RequestParam String name, @RequestParam String description, @RequestParam String homepage);
|
||||
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
[[rest-http-interface-method-parameters]]
|
||||
=== Method Parameters
|
||||
|
||||
Annotated, HTTP exchange methods support flexible method signatures with the following
|
||||
method parameters:
|
||||
|
||||
[cols="1,2", options="header"]
|
||||
|===
|
||||
| Method argument | Description
|
||||
|
||||
| `URI`
|
||||
| Dynamically set the URL for the request, overriding the annotation's `url` attribute.
|
||||
|
||||
| `HttpMethod`
|
||||
| Dynamically set the HTTP method for the request, overriding the annotation's `method` attribute
|
||||
|
||||
| `@RequestHeader`
|
||||
| Add a request header or mutliple headers. The argument may be a `Map<String, ?>` or
|
||||
`MultiValueMap<String, ?>` with multiple headers, a `Collection<?>` of values, or an
|
||||
individual value. Type conversion is supported for non-String values.
|
||||
|
||||
| `@PathVariable`
|
||||
| Add a variable for expand a placeholder in the request URL. The argument may be a
|
||||
`Map<String, ?>` with multiple variables, or an individual value. Type conversion
|
||||
is supported for non-String values.
|
||||
|
||||
| `@RequestBody`
|
||||
| Provide the body of the request either as an Object to be serialized, or a
|
||||
Reactive Streams `Publisher` such as `Mono`, `Flux`, or any other async type supported
|
||||
through the configured `ReactiveAdapterRegistry`.
|
||||
|
||||
| `@RequestParam`
|
||||
| Add a request parameter or mutliple parameters. The argument may be a `Map<String, ?>`
|
||||
or `MultiValueMap<String, ?>` with multiple parameters, a `Collection<?>` of values, or
|
||||
an individual value. Type conversion is supported for non-String values.
|
||||
|
||||
When `"content-type"` is set to `"application/x-www-form-urlencoded"`, request
|
||||
parameters are encoded in the request body. Otherwise, they are added as URL query
|
||||
parameters.
|
||||
|
||||
| `@RequestPart`
|
||||
| Add a request part, which may be a String (form field), `Resource` (file part),
|
||||
Object (entity to be encoded, e.g. as JSON), `HttpEntity` (part content and headers),
|
||||
a Spring `Part`, or Reactive Streams `Publisher` of any of the above.
|
||||
|
||||
| `@CookieValue`
|
||||
| Add a cookie or mutliple cookies. The argument may be a `Map<String, ?>` or
|
||||
`MultiValueMap<String, ?>` with multiple cookies, a `Collection<?>` of values, or an
|
||||
individual value. Type conversion is supported for non-String values.
|
||||
|
||||
|===
|
||||
|
||||
|
||||
[[rest-http-interface-return-values]]
|
||||
=== Return Values
|
||||
|
||||
Annotated, HTTP exchange methods support the following return values:
|
||||
|
||||
[cols="1,2", options="header"]
|
||||
|===
|
||||
| Method return value | Description
|
||||
|
||||
| `void`, `Mono<Void>`
|
||||
| Perform the given request, and release the response content, if any.
|
||||
|
||||
| `HttpHeaders`, `Mono<HttpHeaders>`
|
||||
| Perform the given request, release the response content, if any, and return the
|
||||
response headers.
|
||||
|
||||
| `<T>`, `Mono<T>`
|
||||
| Perform the given request and decode the response content to the declared return type.
|
||||
|
||||
| `<T>`, `Flux<T>`
|
||||
| Perform the given request and decode the response content to a stream of the declared
|
||||
element type.
|
||||
|
||||
| `ResponseEntity<Void>`, `Mono<ResponseEntity<Void>>`
|
||||
| Perform the given request, and release the response content, if any, and return a
|
||||
`ResponseEntity` with the status and headers.
|
||||
|
||||
| `ResponseEntity<T>`, `Mono<ResponseEntity<T>>`
|
||||
| Perform the given request, decode the response content to the declared return type, and
|
||||
return a `ResponseEntity` with the status, headers, and the decoded body.
|
||||
|
||||
| `Mono<ResponseEntity<Flux<T>>`
|
||||
| Perform the given request, decode the response content to a stream of the declared
|
||||
element type, and return a `ResponseEntity` with the status, headers, and the decoded
|
||||
response body stream.
|
||||
|
||||
|===
|
||||
|
||||
TIP: You can also use any other async or reactive types registered in the
|
||||
`ReactiveAdapterRegistry`.
|
||||
|
||||
|
||||
[[rest-http-interface-exceptions]]
|
||||
=== Exception Handling
|
||||
|
||||
By default, `WebClient` raises `WebClientResponseException` for 4xx and 5xx HTTP status
|
||||
codes. To customize this, you can register a response status handler that applies to all
|
||||
responses performed through the client:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
WebClient webClient = WebClient.builder()
|
||||
.defaultStatusHandler(HttpStatusCode::isError, resp -> ...)
|
||||
.build();
|
||||
|
||||
WebClientAdapter clientAdapter = WebClientAdapter.forClient(webClient);
|
||||
HttpServiceProxyFactory factory = HttpServiceProxyFactory
|
||||
.builder(clientAdapter).build();
|
||||
----
|
||||
|
||||
For more details and options, such as suppressing error status codes, see the Javadoc of
|
||||
`defaultStatusHandler` in `WebClient.Builder`.
|
||||
@@ -0,0 +1,967 @@
|
||||
[[scheduling]]
|
||||
= Task Execution and Scheduling
|
||||
|
||||
The Spring Framework provides abstractions for the asynchronous execution and scheduling of
|
||||
tasks with the `TaskExecutor` and `TaskScheduler` interfaces, respectively. Spring also
|
||||
features implementations of those interfaces that support thread pools or delegation to
|
||||
CommonJ within an application server environment. Ultimately, the use of these
|
||||
implementations behind the common interfaces abstracts away the differences between Java
|
||||
SE 5, Java SE 6, and Jakarta EE environments.
|
||||
|
||||
Spring also features integration classes to support scheduling with the `Timer`
|
||||
(part of the JDK since 1.3) and the Quartz Scheduler ( https://www.quartz-scheduler.org/[]).
|
||||
You can set up both of those schedulers by using a `FactoryBean` with optional references to
|
||||
`Timer` or `Trigger` instances, respectively. Furthermore, a convenience class for both
|
||||
the Quartz Scheduler and the `Timer` is available that lets you invoke a method of
|
||||
an existing target object (analogous to the normal `MethodInvokingFactoryBean`
|
||||
operation).
|
||||
|
||||
|
||||
|
||||
[[scheduling-task-executor]]
|
||||
== The Spring `TaskExecutor` Abstraction
|
||||
|
||||
Executors are the JDK name for the concept of thread pools. The "`executor`" naming is
|
||||
due to the fact that there is no guarantee that the underlying implementation is
|
||||
actually a pool. An executor may be single-threaded or even synchronous. Spring's
|
||||
abstraction hides implementation details between the Java SE and Jakarta EE environments.
|
||||
|
||||
Spring's `TaskExecutor` interface is identical to the `java.util.concurrent.Executor`
|
||||
interface. In fact, originally, its primary reason for existence was to abstract away
|
||||
the need for Java 5 when using thread pools. The interface has a single method
|
||||
(`execute(Runnable task)`) that accepts a task for execution based on the semantics
|
||||
and configuration of the thread pool.
|
||||
|
||||
The `TaskExecutor` was originally created to give other Spring components an abstraction
|
||||
for thread pooling where needed. Components such as the `ApplicationEventMulticaster`,
|
||||
JMS's `AbstractMessageListenerContainer`, and Quartz integration all use the
|
||||
`TaskExecutor` abstraction to pool threads. However, if your beans need thread pooling
|
||||
behavior, you can also use this abstraction for your own needs.
|
||||
|
||||
|
||||
[[scheduling-task-executor-types]]
|
||||
=== `TaskExecutor` Types
|
||||
|
||||
Spring includes a number of pre-built implementations of `TaskExecutor`.
|
||||
In all likelihood, you should never need to implement your own.
|
||||
The variants that Spring provides are as follows:
|
||||
|
||||
* `SyncTaskExecutor`:
|
||||
This implementation does not run invocations asynchronously. Instead, each
|
||||
invocation takes place in the calling thread. It is primarily used in situations
|
||||
where multi-threading is not necessary, such as in simple test cases.
|
||||
* `SimpleAsyncTaskExecutor`:
|
||||
This implementation does not reuse any threads. Rather, it starts up a new thread
|
||||
for each invocation. However, it does support a concurrency limit that blocks
|
||||
any invocations that are over the limit until a slot has been freed up. If you
|
||||
are looking for true pooling, see `ThreadPoolTaskExecutor`, later in this list.
|
||||
* `ConcurrentTaskExecutor`:
|
||||
This implementation is an adapter for a `java.util.concurrent.Executor` instance.
|
||||
There is an alternative (`ThreadPoolTaskExecutor`) that exposes the `Executor`
|
||||
configuration parameters as bean properties. There is rarely a need to use
|
||||
`ConcurrentTaskExecutor` directly. However, if the `ThreadPoolTaskExecutor` is not
|
||||
flexible enough for your needs, `ConcurrentTaskExecutor` is an alternative.
|
||||
* `ThreadPoolTaskExecutor`:
|
||||
This implementation is most commonly used. It exposes bean properties for
|
||||
configuring a `java.util.concurrent.ThreadPoolExecutor` and wraps it in a `TaskExecutor`.
|
||||
If you need to adapt to a different kind of `java.util.concurrent.Executor`, we
|
||||
recommend that you use a `ConcurrentTaskExecutor` instead.
|
||||
* `DefaultManagedTaskExecutor`:
|
||||
This implementation uses a JNDI-obtained `ManagedExecutorService` in a JSR-236
|
||||
compatible runtime environment (such as a Jakarta EE application server),
|
||||
replacing a CommonJ WorkManager for that purpose.
|
||||
|
||||
|
||||
[[scheduling-task-executor-usage]]
|
||||
=== Using a `TaskExecutor`
|
||||
|
||||
Spring's `TaskExecutor` implementations are used as simple JavaBeans. In the following example,
|
||||
we define a bean that uses the `ThreadPoolTaskExecutor` to asynchronously print
|
||||
out a set of messages:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
|
||||
public class TaskExecutorExample {
|
||||
|
||||
private class MessagePrinterTask implements Runnable {
|
||||
|
||||
private String message;
|
||||
|
||||
public MessagePrinterTask(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
System.out.println(message);
|
||||
}
|
||||
}
|
||||
|
||||
private TaskExecutor taskExecutor;
|
||||
|
||||
public TaskExecutorExample(TaskExecutor taskExecutor) {
|
||||
this.taskExecutor = taskExecutor;
|
||||
}
|
||||
|
||||
public void printMessages() {
|
||||
for(int i = 0; i < 25; i++) {
|
||||
taskExecutor.execute(new MessagePrinterTask("Message" + i));
|
||||
}
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
As you can see, rather than retrieving a thread from the pool and executing it yourself,
|
||||
you add your `Runnable` to the queue. Then the `TaskExecutor` uses its internal rules to
|
||||
decide when the task gets run.
|
||||
|
||||
To configure the rules that the `TaskExecutor` uses, we expose simple bean properties:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
|
||||
<property name="corePoolSize" value="5"/>
|
||||
<property name="maxPoolSize" value="10"/>
|
||||
<property name="queueCapacity" value="25"/>
|
||||
</bean>
|
||||
|
||||
<bean id="taskExecutorExample" class="TaskExecutorExample">
|
||||
<constructor-arg ref="taskExecutor"/>
|
||||
</bean>
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[scheduling-task-scheduler]]
|
||||
== The Spring `TaskScheduler` Abstraction
|
||||
|
||||
In addition to the `TaskExecutor` abstraction, Spring 3.0 introduced a `TaskScheduler`
|
||||
with a variety of methods for scheduling tasks to run at some point in the future.
|
||||
The following listing shows the `TaskScheduler` interface definition:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
public interface TaskScheduler {
|
||||
|
||||
ScheduledFuture schedule(Runnable task, Trigger trigger);
|
||||
|
||||
ScheduledFuture schedule(Runnable task, Instant startTime);
|
||||
|
||||
ScheduledFuture scheduleAtFixedRate(Runnable task, Instant startTime, Duration period);
|
||||
|
||||
ScheduledFuture scheduleAtFixedRate(Runnable task, Duration period);
|
||||
|
||||
ScheduledFuture scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay);
|
||||
|
||||
ScheduledFuture scheduleWithFixedDelay(Runnable task, Duration delay);
|
||||
|
||||
----
|
||||
|
||||
The simplest method is the one named `schedule` that takes only a `Runnable` and an `Instant`.
|
||||
That causes the task to run once after the specified time. All of the other methods
|
||||
are capable of scheduling tasks to run repeatedly. The fixed-rate and fixed-delay
|
||||
methods are for simple, periodic execution, but the method that accepts a `Trigger` is
|
||||
much more flexible.
|
||||
|
||||
|
||||
[[scheduling-trigger-interface]]
|
||||
=== `Trigger` Interface
|
||||
|
||||
The `Trigger` interface is essentially inspired by JSR-236 which, as of Spring 3.0,
|
||||
was not yet officially implemented. The basic idea of the `Trigger` is that execution
|
||||
times may be determined based on past execution outcomes or even arbitrary conditions.
|
||||
If these determinations do take into account the outcome of the preceding execution,
|
||||
that information is available within a `TriggerContext`. The `Trigger` interface itself
|
||||
is quite simple, as the following listing shows:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
public interface Trigger {
|
||||
|
||||
Date nextExecutionTime(TriggerContext triggerContext);
|
||||
}
|
||||
----
|
||||
|
||||
The `TriggerContext` is the most important part. It encapsulates all of
|
||||
the relevant data and is open for extension in the future, if necessary. The
|
||||
`TriggerContext` is an interface (a `SimpleTriggerContext` implementation is used by
|
||||
default). The following listing shows the available methods for `Trigger` implementations.
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
public interface TriggerContext {
|
||||
|
||||
Date lastScheduledExecutionTime();
|
||||
|
||||
Date lastActualExecutionTime();
|
||||
|
||||
Date lastCompletionTime();
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
[[scheduling-trigger-implementations]]
|
||||
=== `Trigger` Implementations
|
||||
|
||||
Spring provides two implementations of the `Trigger` interface. The most interesting one
|
||||
is the `CronTrigger`. It enables the scheduling of tasks based on
|
||||
<<scheduling-cron-expression,cron expressions>>.
|
||||
For example, the following task is scheduled to run 15 minutes past each hour but only
|
||||
during the 9-to-5 "`business hours`" on weekdays:
|
||||
|
||||
[source,java,indent=0]
|
||||
[subs="verbatim"]
|
||||
----
|
||||
scheduler.schedule(task, new CronTrigger("0 15 9-17 * * MON-FRI"));
|
||||
----
|
||||
|
||||
The other implementation is a `PeriodicTrigger` that accepts a fixed
|
||||
period, an optional initial delay value, and a boolean to indicate whether the period
|
||||
should be interpreted as a fixed-rate or a fixed-delay. Since the `TaskScheduler`
|
||||
interface already defines methods for scheduling tasks at a fixed rate or with a
|
||||
fixed delay, those methods should be used directly whenever possible. The value of the
|
||||
`PeriodicTrigger` implementation is that you can use it within components that rely on
|
||||
the `Trigger` abstraction. For example, it may be convenient to allow periodic triggers,
|
||||
cron-based triggers, and even custom trigger implementations to be used interchangeably.
|
||||
Such a component could take advantage of dependency injection so that you can configure such `Triggers`
|
||||
externally and, therefore, easily modify or extend them.
|
||||
|
||||
|
||||
[[scheduling-task-scheduler-implementations]]
|
||||
=== `TaskScheduler` implementations
|
||||
|
||||
As with Spring's `TaskExecutor` abstraction, the primary benefit of the `TaskScheduler`
|
||||
arrangement is that an application's scheduling needs are decoupled from the deployment
|
||||
environment. This abstraction level is particularly relevant when deploying to an
|
||||
application server environment where threads should not be created directly by the
|
||||
application itself. For such scenarios, Spring provides a `TimerManagerTaskScheduler`
|
||||
that delegates to a CommonJ `TimerManager` on WebLogic or WebSphere as well as a more recent
|
||||
`DefaultManagedTaskScheduler` that delegates to a JSR-236 `ManagedScheduledExecutorService`
|
||||
in a Jakarta EE environment. Both are typically configured with a JNDI lookup.
|
||||
|
||||
Whenever external thread management is not a requirement, a simpler alternative is
|
||||
a local `ScheduledExecutorService` setup within the application, which can be adapted
|
||||
through Spring's `ConcurrentTaskScheduler`. As a convenience, Spring also provides a
|
||||
`ThreadPoolTaskScheduler`, which internally delegates to a `ScheduledExecutorService`
|
||||
to provide common bean-style configuration along the lines of `ThreadPoolTaskExecutor`.
|
||||
These variants work perfectly fine for locally embedded thread pool setups in lenient
|
||||
application server environments, as well -- in particular on Tomcat and Jetty.
|
||||
|
||||
|
||||
|
||||
[[scheduling-annotation-support]]
|
||||
== Annotation Support for Scheduling and Asynchronous Execution
|
||||
|
||||
Spring provides annotation support for both task scheduling and asynchronous method
|
||||
execution.
|
||||
|
||||
|
||||
[[scheduling-enable-annotation-support]]
|
||||
=== Enable Scheduling Annotations
|
||||
|
||||
To enable support for `@Scheduled` and `@Async` annotations, you can add `@EnableScheduling` and
|
||||
`@EnableAsync` to one of your `@Configuration` classes, as the following example shows:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
@EnableScheduling
|
||||
public class AppConfig {
|
||||
}
|
||||
----
|
||||
|
||||
You can pick and choose the relevant annotations for your application. For example,
|
||||
if you need only support for `@Scheduled`, you can omit `@EnableAsync`. For more
|
||||
fine-grained control, you can additionally implement the `SchedulingConfigurer`
|
||||
interface, the `AsyncConfigurer` interface, or both. See the
|
||||
{api-spring-framework}/scheduling/annotation/SchedulingConfigurer.html[`SchedulingConfigurer`]
|
||||
and {api-spring-framework}/scheduling/annotation/AsyncConfigurer.html[`AsyncConfigurer`]
|
||||
javadoc for full details.
|
||||
|
||||
If you prefer XML configuration, you can use the `<task:annotation-driven>` element,
|
||||
as the following example shows:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
|
||||
<task:executor id="myExecutor" pool-size="5"/>
|
||||
<task:scheduler id="myScheduler" pool-size="10"/>
|
||||
----
|
||||
|
||||
Note that, with the preceding XML, an executor reference is provided for handling those
|
||||
tasks that correspond to methods with the `@Async` annotation, and the scheduler
|
||||
reference is provided for managing those methods annotated with `@Scheduled`.
|
||||
|
||||
NOTE: The default advice mode for processing `@Async` annotations is `proxy` which allows
|
||||
for interception of calls through the proxy only. Local calls within the same class
|
||||
cannot get intercepted that way. For a more advanced mode of interception, consider
|
||||
switching to `aspectj` mode in combination with compile-time or load-time weaving.
|
||||
|
||||
|
||||
[[scheduling-annotation-support-scheduled]]
|
||||
=== The `@Scheduled` annotation
|
||||
|
||||
You can add the `@Scheduled` annotation to a method, along with trigger metadata. For
|
||||
example, the following method is invoked every five seconds (5000 milliseconds) with a
|
||||
fixed delay, meaning that the period is measured from the completion time of each
|
||||
preceding invocation.
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
@Scheduled(fixedDelay = 5000)
|
||||
public void doSomething() {
|
||||
// something that should run periodically
|
||||
}
|
||||
----
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
By default, milliseconds will be used as the time unit for fixed delay, fixed rate, and
|
||||
initial delay values. If you would like to use a different time unit such as seconds or
|
||||
minutes, you can configure this via the `timeUnit` attribute in `@Scheduled`.
|
||||
|
||||
For example, the previous example can also be written as follows.
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
@Scheduled(fixedDelay = 5, timeUnit = TimeUnit.SECONDS)
|
||||
public void doSomething() {
|
||||
// something that should run periodically
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
If you need a fixed-rate execution, you can use the `fixedRate` attribute within the
|
||||
annotation. The following method is invoked every five seconds (measured between the
|
||||
successive start times of each invocation).
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
@Scheduled(fixedRate = 5, timeUnit = TimeUnit.SECONDS)
|
||||
public void doSomething() {
|
||||
// something that should run periodically
|
||||
}
|
||||
----
|
||||
|
||||
For fixed-delay and fixed-rate tasks, you can specify an initial delay by indicating the
|
||||
amount of time to wait before the first execution of the method, as the following
|
||||
`fixedRate` example shows.
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
@Scheduled(initialDelay = 1000, fixedRate = 5000)
|
||||
public void doSomething() {
|
||||
// something that should run periodically
|
||||
}
|
||||
----
|
||||
|
||||
If simple periodic scheduling is not expressive enough, you can provide a
|
||||
<<scheduling-cron-expression,cron expression>>.
|
||||
The following example runs only on weekdays:
|
||||
|
||||
[source,java,indent=0]
|
||||
[subs="verbatim"]
|
||||
----
|
||||
@Scheduled(cron="*/5 * * * * MON-FRI")
|
||||
public void doSomething() {
|
||||
// something that should run on weekdays only
|
||||
}
|
||||
----
|
||||
|
||||
TIP: You can also use the `zone` attribute to specify the time zone in which the cron
|
||||
expression is resolved.
|
||||
|
||||
Notice that the methods to be scheduled must have void returns and must not accept any
|
||||
arguments. If the method needs to interact with other objects from the application
|
||||
context, those would typically have been provided through dependency injection.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
As of Spring Framework 4.3, `@Scheduled` methods are supported on beans of any scope.
|
||||
|
||||
Make sure that you are not initializing multiple instances of the same `@Scheduled`
|
||||
annotation class at runtime, unless you do want to schedule callbacks to each such
|
||||
instance. Related to this, make sure that you do not use `@Configurable` on bean
|
||||
classes that are annotated with `@Scheduled` and registered as regular Spring beans
|
||||
with the container. Otherwise, you would get double initialization (once through the
|
||||
container and once through the `@Configurable` aspect), with the consequence of each
|
||||
`@Scheduled` method being invoked twice.
|
||||
====
|
||||
|
||||
|
||||
[[scheduling-annotation-support-async]]
|
||||
=== The `@Async` annotation
|
||||
|
||||
You can provide the `@Async` annotation on a method so that invocation of that method
|
||||
occurs asynchronously. In other words, the caller returns immediately upon
|
||||
invocation, while the actual execution of the method occurs in a task that has been
|
||||
submitted to a Spring `TaskExecutor`. In the simplest case, you can apply the annotation
|
||||
to a method that returns `void`, as the following example shows:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
@Async
|
||||
void doSomething() {
|
||||
// this will be run asynchronously
|
||||
}
|
||||
----
|
||||
|
||||
Unlike the methods annotated with the `@Scheduled` annotation, these methods can expect
|
||||
arguments, because they are invoked in the "`normal`" way by callers at runtime rather
|
||||
than from a scheduled task being managed by the container. For example, the following code is
|
||||
a legitimate application of the `@Async` annotation:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
@Async
|
||||
void doSomething(String s) {
|
||||
// this will be run asynchronously
|
||||
}
|
||||
----
|
||||
|
||||
Even methods that return a value can be invoked asynchronously. However, such methods
|
||||
are required to have a `Future`-typed return value. This still provides the benefit of
|
||||
asynchronous execution so that the caller can perform other tasks prior to calling
|
||||
`get()` on that `Future`. The following example shows how to use `@Async` on a method
|
||||
that returns a value:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
@Async
|
||||
Future<String> returnSomething(int i) {
|
||||
// this will be run asynchronously
|
||||
}
|
||||
----
|
||||
|
||||
TIP: `@Async` methods may not only declare a regular `java.util.concurrent.Future` return type
|
||||
but also Spring's `org.springframework.util.concurrent.ListenableFuture` or, as of Spring
|
||||
4.2, JDK 8's `java.util.concurrent.CompletableFuture`, for richer interaction with the
|
||||
asynchronous task and for immediate composition with further processing steps.
|
||||
|
||||
You can not use `@Async` in conjunction with lifecycle callbacks such as
|
||||
`@PostConstruct`. To asynchronously initialize Spring beans, you currently have to use
|
||||
a separate initializing Spring bean that then invokes the `@Async` annotated method on the
|
||||
target, as the following example shows:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
public class SampleBeanImpl implements SampleBean {
|
||||
|
||||
@Async
|
||||
void doSomething() {
|
||||
// ...
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public class SampleBeanInitializer {
|
||||
|
||||
private final SampleBean bean;
|
||||
|
||||
public SampleBeanInitializer(SampleBean bean) {
|
||||
this.bean = bean;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void initialize() {
|
||||
bean.doSomething();
|
||||
}
|
||||
|
||||
}
|
||||
----
|
||||
|
||||
NOTE: There is no direct XML equivalent for `@Async`, since such methods should be designed
|
||||
for asynchronous execution in the first place, not externally re-declared to be asynchronous.
|
||||
However, you can manually set up Spring's `AsyncExecutionInterceptor` with Spring AOP,
|
||||
in combination with a custom pointcut.
|
||||
|
||||
|
||||
[[scheduling-annotation-support-qualification]]
|
||||
=== Executor Qualification with `@Async`
|
||||
|
||||
By default, when specifying `@Async` on a method, the executor that is used is the
|
||||
one <<scheduling-enable-annotation-support, configured when enabling async support>>,
|
||||
i.e. the "`annotation-driven`" element if you are using XML or your `AsyncConfigurer`
|
||||
implementation, if any. However, you can use the `value` attribute of the `@Async`
|
||||
annotation when you need to indicate that an executor other than the default should be
|
||||
used when executing a given method. The following example shows how to do so:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
@Async("otherExecutor")
|
||||
void doSomething(String s) {
|
||||
// this will be run asynchronously by "otherExecutor"
|
||||
}
|
||||
----
|
||||
|
||||
In this case, `"otherExecutor"` can be the name of any `Executor` bean in the Spring
|
||||
container, or it may be the name of a qualifier associated with any `Executor` (for example, as
|
||||
specified with the `<qualifier>` element or Spring's `@Qualifier` annotation).
|
||||
|
||||
|
||||
[[scheduling-annotation-support-exception]]
|
||||
=== Exception Management with `@Async`
|
||||
|
||||
When an `@Async` method has a `Future`-typed return value, it is easy to manage
|
||||
an exception that was thrown during the method execution, as this exception is
|
||||
thrown when calling `get` on the `Future` result. With a `void` return type,
|
||||
however, the exception is uncaught and cannot be transmitted. You can provide an
|
||||
`AsyncUncaughtExceptionHandler` to handle such exceptions. The following example shows
|
||||
how to do so:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
public class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {
|
||||
|
||||
@Override
|
||||
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
|
||||
// handle exception
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
By default, the exception is merely logged. You can define a custom `AsyncUncaughtExceptionHandler`
|
||||
by using `AsyncConfigurer` or the `<task:annotation-driven/>` XML element.
|
||||
|
||||
|
||||
|
||||
[[scheduling-task-namespace]]
|
||||
== The `task` Namespace
|
||||
|
||||
As of version 3.0, Spring includes an XML namespace for configuring `TaskExecutor` and
|
||||
`TaskScheduler` instances. It also provides a convenient way to configure tasks to be
|
||||
scheduled with a trigger.
|
||||
|
||||
|
||||
[[scheduling-task-namespace-scheduler]]
|
||||
=== The 'scheduler' Element
|
||||
|
||||
The following element creates a `ThreadPoolTaskScheduler` instance with the
|
||||
specified thread pool size:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<task:scheduler id="scheduler" pool-size="10"/>
|
||||
----
|
||||
|
||||
The value provided for the `id` attribute is used as the prefix for thread names
|
||||
within the pool. The `scheduler` element is relatively straightforward. If you do not
|
||||
provide a `pool-size` attribute, the default thread pool has only a single thread.
|
||||
There are no other configuration options for the scheduler.
|
||||
|
||||
|
||||
[[scheduling-task-namespace-executor]]
|
||||
=== The `executor` Element
|
||||
|
||||
The following creates a `ThreadPoolTaskExecutor` instance:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<task:executor id="executor" pool-size="10"/>
|
||||
----
|
||||
|
||||
As with the scheduler shown in the <<scheduling-task-namespace-scheduler, previous section>>,
|
||||
the value provided for the `id` attribute is used as the prefix for thread names within
|
||||
the pool. As far as the pool size is concerned, the `executor` element supports more
|
||||
configuration options than the `scheduler` element. For one thing, the thread pool for
|
||||
a `ThreadPoolTaskExecutor` is itself more configurable. Rather than only a single size,
|
||||
an executor's thread pool can have different values for the core and the max size.
|
||||
If you provide a single value, the executor has a fixed-size thread pool (the core and
|
||||
max sizes are the same). However, the `executor` element's `pool-size` attribute also
|
||||
accepts a range in the form of `min-max`. The following example sets a minimum value of
|
||||
`5` and a maximum value of `25`:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<task:executor
|
||||
id="executorWithPoolSizeRange"
|
||||
pool-size="5-25"
|
||||
queue-capacity="100"/>
|
||||
----
|
||||
|
||||
In the preceding configuration, a `queue-capacity` value has also been provided.
|
||||
The configuration of the thread pool should also be considered in light of the
|
||||
executor's queue capacity. For the full description of the relationship between pool
|
||||
size and queue capacity, see the documentation for
|
||||
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html[`ThreadPoolExecutor`].
|
||||
The main idea is that, when a task is submitted, the executor first tries to use a
|
||||
free thread if the number of active threads is currently less than the core size.
|
||||
If the core size has been reached, the task is added to the queue, as long as its
|
||||
capacity has not yet been reached. Only then, if the queue's capacity has been
|
||||
reached, does the executor create a new thread beyond the core size. If the max size
|
||||
has also been reached, then the executor rejects the task.
|
||||
|
||||
By default, the queue is unbounded, but this is rarely the desired configuration,
|
||||
because it can lead to `OutOfMemoryErrors` if enough tasks are added to that queue while
|
||||
all pool threads are busy. Furthermore, if the queue is unbounded, the max size has
|
||||
no effect at all. Since the executor always tries the queue before creating a new
|
||||
thread beyond the core size, a queue must have a finite capacity for the thread pool to
|
||||
grow beyond the core size (this is why a fixed-size pool is the only sensible case
|
||||
when using an unbounded queue).
|
||||
|
||||
Consider the case, as mentioned above, when a task is rejected. By default, when a
|
||||
task is rejected, a thread pool executor throws a `TaskRejectedException`. However,
|
||||
the rejection policy is actually configurable. The exception is thrown when using
|
||||
the default rejection policy, which is the `AbortPolicy` implementation.
|
||||
For applications where some tasks can be skipped under heavy load, you can instead
|
||||
configure either `DiscardPolicy` or `DiscardOldestPolicy`. Another option that works
|
||||
well for applications that need to throttle the submitted tasks under heavy load is
|
||||
the `CallerRunsPolicy`. Instead of throwing an exception or discarding tasks,
|
||||
that policy forces the thread that is calling the submit method to run the task itself.
|
||||
The idea is that such a caller is busy while running that task and not able to submit
|
||||
other tasks immediately. Therefore, it provides a simple way to throttle the incoming
|
||||
load while maintaining the limits of the thread pool and queue. Typically, this allows
|
||||
the executor to "`catch up`" on the tasks it is handling and thereby frees up some
|
||||
capacity on the queue, in the pool, or both. You can choose any of these options from an
|
||||
enumeration of values available for the `rejection-policy` attribute on the `executor`
|
||||
element.
|
||||
|
||||
The following example shows an `executor` element with a number of attributes to specify
|
||||
various behaviors:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<task:executor
|
||||
id="executorWithCallerRunsPolicy"
|
||||
pool-size="5-25"
|
||||
queue-capacity="100"
|
||||
rejection-policy="CALLER_RUNS"/>
|
||||
----
|
||||
|
||||
Finally, the `keep-alive` setting determines the time limit (in seconds) for which threads
|
||||
may remain idle before being stopped. If there are more than the core number of threads
|
||||
currently in the pool, after waiting this amount of time without processing a task, excess
|
||||
threads get stopped. A time value of zero causes excess threads to stop
|
||||
immediately after executing a task without remaining follow-up work in the task queue.
|
||||
The following example sets the `keep-alive` value to two minutes:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<task:executor
|
||||
id="executorWithKeepAlive"
|
||||
pool-size="5-25"
|
||||
keep-alive="120"/>
|
||||
----
|
||||
|
||||
|
||||
[[scheduling-task-namespace-scheduled-tasks]]
|
||||
=== The 'scheduled-tasks' Element
|
||||
|
||||
The most powerful feature of Spring's task namespace is the support for configuring
|
||||
tasks to be scheduled within a Spring Application Context. This follows an approach
|
||||
similar to other "`method-invokers`" in Spring, such as that provided by the JMS namespace
|
||||
for configuring message-driven POJOs. Basically, a `ref` attribute can point to any
|
||||
Spring-managed object, and the `method` attribute provides the name of a method to be
|
||||
invoked on that object. The following listing shows a simple example:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<task:scheduled-tasks scheduler="myScheduler">
|
||||
<task:scheduled ref="beanA" method="methodA" fixed-delay="5000"/>
|
||||
</task:scheduled-tasks>
|
||||
|
||||
<task:scheduler id="myScheduler" pool-size="10"/>
|
||||
----
|
||||
|
||||
The scheduler is referenced by the outer element, and each individual
|
||||
task includes the configuration of its trigger metadata. In the preceding example, that
|
||||
metadata defines a periodic trigger with a fixed delay indicating the number of
|
||||
milliseconds to wait after each task execution has completed. Another option is
|
||||
`fixed-rate`, indicating how often the method should be run regardless of how long
|
||||
any previous execution takes. Additionally, for both `fixed-delay` and `fixed-rate` tasks, you can specify an
|
||||
'initial-delay' parameter, indicating the number of milliseconds to wait
|
||||
before the first execution of the method. For more control, you can instead provide a `cron` attribute
|
||||
to provide a <<scheduling-cron-expression,cron expression>>.
|
||||
The following example shows these other options:
|
||||
|
||||
[source,xml,indent=0]
|
||||
[subs="verbatim"]
|
||||
----
|
||||
<task:scheduled-tasks scheduler="myScheduler">
|
||||
<task:scheduled ref="beanA" method="methodA" fixed-delay="5000" initial-delay="1000"/>
|
||||
<task:scheduled ref="beanB" method="methodB" fixed-rate="5000"/>
|
||||
<task:scheduled ref="beanC" method="methodC" cron="*/5 * * * * MON-FRI"/>
|
||||
</task:scheduled-tasks>
|
||||
|
||||
<task:scheduler id="myScheduler" pool-size="10"/>
|
||||
----
|
||||
|
||||
|
||||
|
||||
[[scheduling-cron-expression]]
|
||||
== Cron Expressions
|
||||
|
||||
All Spring cron expressions have to conform to the same format, whether you are using them in
|
||||
<<scheduling-annotation-support-scheduled,`@Scheduled` annotations>>,
|
||||
<<scheduling-task-namespace-scheduled-tasks,`task:scheduled-tasks` elements>>,
|
||||
or someplace else.
|
||||
A well-formed cron expression, such as `* * * * * *`, consists of six space-separated time and date
|
||||
fields, each with its own range of valid values:
|
||||
|
||||
|
||||
....
|
||||
┌───────────── second (0-59)
|
||||
│ ┌───────────── minute (0 - 59)
|
||||
│ │ ┌───────────── hour (0 - 23)
|
||||
│ │ │ ┌───────────── day of the month (1 - 31)
|
||||
│ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)
|
||||
│ │ │ │ │ ┌───────────── day of the week (0 - 7)
|
||||
│ │ │ │ │ │ (0 or 7 is Sunday, or MON-SUN)
|
||||
│ │ │ │ │ │
|
||||
* * * * * *
|
||||
....
|
||||
|
||||
There are some rules that apply:
|
||||
|
||||
* A field may be an asterisk (`*`), which always stands for "`first-last`".
|
||||
For the day-of-the-month or day-of-the-week fields, a question mark (`?`) may be used instead of an
|
||||
asterisk.
|
||||
* Commas (`,`) are used to separate items of a list.
|
||||
* Two numbers separated with a hyphen (`-`) express a range of numbers.
|
||||
The specified range is inclusive.
|
||||
* Following a range (or `*`) with `/` specifies the interval of the number's value through the range.
|
||||
* English names can also be used for the month and day-of-week fields.
|
||||
Use the first three letters of the particular day or month (case does not matter).
|
||||
* The day-of-month and day-of-week fields can contain an `L` character, which has a different meaning.
|
||||
** In the day-of-month field, `L` stands for _the last day of the month_.
|
||||
If followed by a negative offset (that is, `L-n`), it means _``n``th-to-last day of the month_.
|
||||
** In the day-of-week field, `L` stands for _the last day of the week_.
|
||||
If prefixed by a number or three-letter name (`dL` or `DDDL`), it means _the last day of week (`d`
|
||||
or `DDD`) in the month_.
|
||||
* The day-of-month field can be `nW`, which stands for _the nearest weekday to day of the month ``n``_.
|
||||
If `n` falls on Saturday, this yields the Friday before it.
|
||||
If `n` falls on Sunday, this yields the Monday after, which also happens if `n` is `1` and falls on
|
||||
a Saturday (that is: `1W` stands for _the first weekday of the month_).
|
||||
* If the day-of-month field is `LW`, it means _the last weekday of the month_.
|
||||
* The day-of-week field can be `d#n` (or `DDD#n`), which stands for _the ``n``th day of week `d`
|
||||
(or ``DDD``) in the month_.
|
||||
|
||||
Here are some examples:
|
||||
|
||||
|===
|
||||
| Cron Expression | Meaning
|
||||
|
||||
|`0 0 * * * *` | top of every hour of every day
|
||||
|`*/10 * * * * *` | every ten seconds
|
||||
| `0 0 8-10 * * *` | 8, 9 and 10 o'clock of every day
|
||||
| `0 0 6,19 * * *` | 6:00 AM and 7:00 PM every day
|
||||
| `0 0/30 8-10 * * *` | 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day
|
||||
| `0 0 9-17 * * MON-FRI`| on the hour nine-to-five weekdays
|
||||
| `0 0 0 25 DEC ?` | every Christmas Day at midnight
|
||||
| `0 0 0 L * *` | last day of the month at midnight
|
||||
| `0 0 0 L-3 * *` | third-to-last day of the month at midnight
|
||||
| `0 0 0 * * 5L` | last Friday of the month at midnight
|
||||
| `0 0 0 * * THUL` | last Thursday of the month at midnight
|
||||
| `0 0 0 1W * *` | first weekday of the month at midnight
|
||||
| `0 0 0 LW * *` | last weekday of the month at midnight
|
||||
| `0 0 0 ? * 5#2` | the second Friday in the month at midnight
|
||||
| `0 0 0 ? * MON#1` | the first Monday in the month at midnight
|
||||
|===
|
||||
|
||||
=== Macros
|
||||
|
||||
Expressions such as `0 0 * * * *` are hard for humans to parse and are, therefore, hard to fix in case of bugs.
|
||||
To improve readability, Spring supports the following macros, which represent commonly used sequences.
|
||||
You can use these macros instead of the six-digit value, thus: `@Scheduled(cron = "@hourly")`.
|
||||
|
||||
|===
|
||||
|Macro | Meaning
|
||||
|
||||
| `@yearly` (or `@annually`) | once a year (`0 0 0 1 1 *`)
|
||||
| `@monthly` | once a month (`0 0 0 1 * *`)
|
||||
| `@weekly` | once a week (`0 0 0 * * 0`)
|
||||
| `@daily` (or `@midnight`) | once a day (`0 0 0 * * *`), or
|
||||
| `@hourly` | once an hour, (`0 0 * * * *`)
|
||||
|===
|
||||
|
||||
|
||||
|
||||
[[scheduling-quartz]]
|
||||
== Using the Quartz Scheduler
|
||||
|
||||
Quartz uses `Trigger`, `Job`, and `JobDetail` objects to realize scheduling of all kinds
|
||||
of jobs. For the basic concepts behind Quartz, see
|
||||
https://www.quartz-scheduler.org/[]. For convenience purposes, Spring offers a couple of
|
||||
classes that simplify using Quartz within Spring-based applications.
|
||||
|
||||
|
||||
[[scheduling-quartz-jobdetail]]
|
||||
=== Using the `JobDetailFactoryBean`
|
||||
|
||||
Quartz `JobDetail` objects contain all the information needed to run a job. Spring provides a
|
||||
`JobDetailFactoryBean`, which provides bean-style properties for XML configuration purposes.
|
||||
Consider the following example:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<bean name="exampleJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
|
||||
<property name="jobClass" value="example.ExampleJob"/>
|
||||
<property name="jobDataAsMap">
|
||||
<map>
|
||||
<entry key="timeout" value="5"/>
|
||||
</map>
|
||||
</property>
|
||||
</bean>
|
||||
----
|
||||
|
||||
The job detail configuration has all the information it needs to run the job (`ExampleJob`).
|
||||
The timeout is specified in the job data map. The job data map is available through the
|
||||
`JobExecutionContext` (passed to you at execution time), but the `JobDetail` also gets
|
||||
its properties from the job data mapped to properties of the job instance. So, in the following example,
|
||||
the `ExampleJob` contains a bean property named `timeout`, and the `JobDetail`
|
||||
has it applied automatically:
|
||||
|
||||
[source,java,indent=0]
|
||||
[subs="verbatim"]
|
||||
----
|
||||
package example;
|
||||
|
||||
public class ExampleJob extends QuartzJobBean {
|
||||
|
||||
private int timeout;
|
||||
|
||||
/**
|
||||
* Setter called after the ExampleJob is instantiated
|
||||
* with the value from the JobDetailFactoryBean (5)
|
||||
*/
|
||||
public void setTimeout(int timeout) {
|
||||
this.timeout = timeout;
|
||||
}
|
||||
|
||||
protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
|
||||
// do the actual work
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
All additional properties from the job data map are available to you as well.
|
||||
|
||||
NOTE: By using the `name` and `group` properties, you can modify the name and the group
|
||||
of the job, respectively. By default, the name of the job matches the bean name
|
||||
of the `JobDetailFactoryBean` (`exampleJob` in the preceding example above).
|
||||
|
||||
|
||||
[[scheduling-quartz-method-invoking-job]]
|
||||
=== Using the `MethodInvokingJobDetailFactoryBean`
|
||||
|
||||
Often you merely need to invoke a method on a specific object. By using the
|
||||
`MethodInvokingJobDetailFactoryBean`, you can do exactly this, as the following example shows:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
|
||||
<property name="targetObject" ref="exampleBusinessObject"/>
|
||||
<property name="targetMethod" value="doIt"/>
|
||||
</bean>
|
||||
----
|
||||
|
||||
The preceding example results in the `doIt` method being called on the
|
||||
`exampleBusinessObject` method, as the following example shows:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
public class ExampleBusinessObject {
|
||||
|
||||
// properties and collaborators
|
||||
|
||||
public void doIt() {
|
||||
// do the actual work
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<bean id="exampleBusinessObject" class="examples.ExampleBusinessObject"/>
|
||||
----
|
||||
|
||||
By using the `MethodInvokingJobDetailFactoryBean`, you need not create one-line jobs
|
||||
that merely invoke a method. You need only create the actual business object and
|
||||
wire up the detail object.
|
||||
|
||||
By default, Quartz Jobs are stateless, resulting in the possibility of jobs interfering
|
||||
with each other. If you specify two triggers for the same `JobDetail`, it is
|
||||
possible that, before the first job has finished, the second one starts. If
|
||||
`JobDetail` classes implement the `Stateful` interface, this does not happen. The second
|
||||
job does not start before the first one has finished. To make jobs resulting from the
|
||||
`MethodInvokingJobDetailFactoryBean` be non-concurrent, set the `concurrent` flag to
|
||||
`false`, as the following example shows:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
|
||||
<property name="targetObject" ref="exampleBusinessObject"/>
|
||||
<property name="targetMethod" value="doIt"/>
|
||||
<property name="concurrent" value="false"/>
|
||||
</bean>
|
||||
----
|
||||
|
||||
NOTE: By default, jobs will run in a concurrent fashion.
|
||||
|
||||
|
||||
[[scheduling-quartz-cron]]
|
||||
=== Wiring up Jobs by Using Triggers and `SchedulerFactoryBean`
|
||||
|
||||
We have created job details and jobs. We have also reviewed the convenience bean that lets
|
||||
you invoke a method on a specific object. Of course, we still need to schedule the
|
||||
jobs themselves. This is done by using triggers and a `SchedulerFactoryBean`. Several
|
||||
triggers are available within Quartz, and Spring offers two Quartz `FactoryBean`
|
||||
implementations with convenient defaults: `CronTriggerFactoryBean` and
|
||||
`SimpleTriggerFactoryBean`.
|
||||
|
||||
Triggers need to be scheduled. Spring offers a `SchedulerFactoryBean` that exposes
|
||||
triggers to be set as properties. `SchedulerFactoryBean` schedules the actual jobs with
|
||||
those triggers.
|
||||
|
||||
The following listing uses both a `SimpleTriggerFactoryBean` and a `CronTriggerFactoryBean`:
|
||||
|
||||
[source,xml,indent=0]
|
||||
[subs="verbatim"]
|
||||
----
|
||||
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
|
||||
<!-- see the example of method invoking job above -->
|
||||
<property name="jobDetail" ref="jobDetail"/>
|
||||
<!-- 10 seconds -->
|
||||
<property name="startDelay" value="10000"/>
|
||||
<!-- repeat every 50 seconds -->
|
||||
<property name="repeatInterval" value="50000"/>
|
||||
</bean>
|
||||
|
||||
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
|
||||
<property name="jobDetail" ref="exampleJob"/>
|
||||
<!-- run every morning at 6 AM -->
|
||||
<property name="cronExpression" value="0 0 6 * * ?"/>
|
||||
</bean>
|
||||
----
|
||||
|
||||
The preceding example sets up two triggers, one running every 50 seconds with a starting delay of 10
|
||||
seconds and one running every morning at 6 AM. To finalize everything, we need to set up the
|
||||
`SchedulerFactoryBean`, as the following example shows:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
|
||||
<property name="triggers">
|
||||
<list>
|
||||
<ref bean="cronTrigger"/>
|
||||
<ref bean="simpleTrigger"/>
|
||||
</list>
|
||||
</property>
|
||||
</bean>
|
||||
----
|
||||
|
||||
More properties are available for the `SchedulerFactoryBean`, such as the calendars used by the
|
||||
job details, properties to customize Quartz with, and a Spring-provided JDBC DataSource. See
|
||||
the {api-spring-framework}/scheduling/quartz/SchedulerFactoryBean.html[`SchedulerFactoryBean`]
|
||||
javadoc for more information.
|
||||
|
||||
NOTE: `SchedulerFactoryBean` also recognizes a `quartz.properties` file in the classpath,
|
||||
based on Quartz property keys, as with regular Quartz configuration. Please note that many
|
||||
`SchedulerFactoryBean` settings interact with common Quartz settings in the properties file;
|
||||
it is therefore not recommended to specify values at both levels. For example, do not set
|
||||
an "org.quartz.jobStore.class" property if you mean to rely on a Spring-provided DataSource,
|
||||
or specify an `org.springframework.scheduling.quartz.LocalDataSourceJobStore` variant which
|
||||
is a full-fledged replacement for the standard `org.quartz.impl.jdbcjobstore.JobStoreTX`.
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
[[languages]]
|
||||
= Language Support
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:tabsize: 4
|
||||
:docinfo1:
|
||||
include::attributes.adoc[]
|
||||
include::page-layout.adoc[]
|
||||
|
||||
include::languages/kotlin.adoc[leveloffset=+1]
|
||||
|
||||
|
||||
@@ -20,6 +20,9 @@ Feel free to join the #spring channel of https://slack.kotlinlang.org/[Kotlin Sl
|
||||
or ask a question with `spring` and `kotlin` as tags on
|
||||
https://stackoverflow.com/questions/tagged/spring+kotlin[Stackoverflow] if you need support.
|
||||
|
||||
|
||||
|
||||
|
||||
[[kotlin-requirements]]
|
||||
== Requirements
|
||||
|
||||
@@ -37,6 +40,9 @@ for serializing or deserializing JSON data for Kotlin classes with Jackson, so m
|
||||
`com.fasterxml.jackson.module:jackson-module-kotlin` dependency to your project if you have such need.
|
||||
It is automatically registered when found in the classpath.
|
||||
|
||||
|
||||
|
||||
|
||||
[[kotlin-extensions]]
|
||||
== Extensions
|
||||
|
||||
@@ -80,6 +86,9 @@ With Kotlin and the Spring Framework extensions, you can instead write the follo
|
||||
As in Java, `users` in Kotlin is strongly typed, but Kotlin's clever type inference allows
|
||||
for shorter syntax.
|
||||
|
||||
|
||||
|
||||
|
||||
[[kotlin-null-safety]]
|
||||
== Null-safety
|
||||
|
||||
@@ -115,6 +124,9 @@ NOTE: Generic type arguments, varargs, and array elements nullability are not su
|
||||
but should be in an upcoming release. See https://github.com/Kotlin/KEEP/issues/79[this discussion]
|
||||
for up-to-date information.
|
||||
|
||||
|
||||
|
||||
|
||||
[[kotlin-classes-interfaces]]
|
||||
== Classes and Interfaces
|
||||
|
||||
@@ -124,12 +136,16 @@ with default values.
|
||||
|
||||
Kotlin parameter names are recognized through a dedicated `KotlinReflectionParameterNameDiscoverer`,
|
||||
which allows finding interface method parameter names without requiring the Java 8 `-parameters`
|
||||
compiler flag to be enabled during compilation.
|
||||
compiler flag to be enabled during compilation. (For completeness, we nevertheless recommend
|
||||
running the Kotlin compiler with its `-java-parameters` flag for standard Java parameter exposure.)
|
||||
|
||||
You can declare configuration classes as
|
||||
https://kotlinlang.org/docs/reference/nested-classes.html[top level or nested but not inner],
|
||||
since the later requires a reference to the outer class.
|
||||
|
||||
|
||||
|
||||
|
||||
[[kotlin-annotations]]
|
||||
== Annotations
|
||||
|
||||
@@ -156,6 +172,9 @@ https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targe
|
||||
such as `@field:NotNull` or `@get:Size(min=5, max=15)`, as described in
|
||||
https://stackoverflow.com/a/35853200/1092077[this Stack Overflow response].
|
||||
|
||||
|
||||
|
||||
|
||||
[[kotlin-bean-definition-dsl]]
|
||||
== Bean Definition DSL
|
||||
|
||||
@@ -263,16 +282,20 @@ as the following example shows:
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
NOTE: Spring Boot is based on JavaConfig and
|
||||
https://github.com/spring-projects/spring-boot/issues/8115[does not yet provide specific support for functional bean definition],
|
||||
but you can experimentally use functional bean definitions through Spring Boot's `ApplicationContextInitializer` support.
|
||||
See https://stackoverflow.com/questions/45935931/how-to-use-functional-bean-definition-kotlin-dsl-with-spring-boot-and-spring-w/46033685#46033685[this Stack Overflow answer]
|
||||
for more details and up-to-date information. See also the experimental Kofu DSL developed in https://github.com/spring-projects/spring-fu[Spring Fu incubator].
|
||||
|
||||
|
||||
|
||||
|
||||
[[kotlin-web]]
|
||||
== Web
|
||||
|
||||
|
||||
|
||||
=== Router DSL
|
||||
|
||||
Spring Framework comes with a Kotlin router DSL available in 3 flavors:
|
||||
@@ -314,6 +337,8 @@ when you need to register routes depending on dynamic data (for example, from a
|
||||
|
||||
See https://github.com/mixitconf/mixit/[MiXiT project] for a concrete example.
|
||||
|
||||
|
||||
|
||||
=== MockMvc DSL
|
||||
|
||||
A Kotlin DSL is provided via `MockMvc` Kotlin extensions in order to provide a more
|
||||
@@ -339,6 +364,8 @@ mockMvc.get("/person/{name}", "Lee") {
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
|
||||
=== Kotlin Script Templates
|
||||
|
||||
Spring Framework provides a
|
||||
@@ -357,9 +384,7 @@ dependencies {
|
||||
}
|
||||
----
|
||||
|
||||
Configuration is usually done with `ScriptTemplateConfigurer` and `ScriptTemplateViewResolver`
|
||||
beans.
|
||||
|
||||
Configuration is usually done with `ScriptTemplateConfigurer` and `ScriptTemplateViewResolver` beans.
|
||||
|
||||
`KotlinScriptConfiguration.kt`
|
||||
[source,kotlin,indent=0]
|
||||
@@ -386,6 +411,8 @@ class KotlinScriptConfiguration {
|
||||
See the https://github.com/sdeleuze/kotlin-script-templating[kotlin-script-templating] example
|
||||
project for more details.
|
||||
|
||||
|
||||
|
||||
=== Kotlin multiplatform serialization
|
||||
|
||||
As of Spring Framework 5.3, https://github.com/Kotlin/kotlinx.serialization[Kotlin multiplatform serialization] is
|
||||
@@ -397,6 +424,9 @@ Kotlin serialization is designed to serialize only Kotlin classes annotated with
|
||||
With Spring Messaging (RSocket), make sure that neither Jackson, GSON or JSONB are in the classpath if you want automatic configuration,
|
||||
if Jackson is needed configure `KotlinSerializationJsonMessageConverter` manually.
|
||||
|
||||
|
||||
|
||||
|
||||
== Coroutines
|
||||
|
||||
Kotlin https://kotlinlang.org/docs/reference/coroutines-overview.html[Coroutines] are Kotlin
|
||||
@@ -415,6 +445,8 @@ Spring Framework provides support for Coroutines on the following scope:
|
||||
* Suspending function and `Flow` support in RSocket `@MessageMapping` annotated methods
|
||||
* Extensions for {docs-spring-framework}/kdoc-api/spring-messaging/org.springframework.messaging.rsocket/index.html[`RSocketRequester`]
|
||||
|
||||
|
||||
|
||||
=== Dependencies
|
||||
|
||||
Coroutines support is enabled when `kotlinx-coroutines-core` and `kotlinx-coroutines-reactor`
|
||||
@@ -432,6 +464,8 @@ dependencies {
|
||||
|
||||
Version `1.4.0` and above are supported.
|
||||
|
||||
|
||||
|
||||
=== How Reactive translates to Coroutines?
|
||||
|
||||
For return values, the translation from Reactive to Coroutines APIs is the following:
|
||||
@@ -458,6 +492,8 @@ https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coro
|
||||
Read this blog post about https://spring.io/blog/2019/04/12/going-reactive-with-spring-coroutines-and-kotlin-flow[Going Reactive with Spring, Coroutines and Kotlin Flow]
|
||||
for more details, including how to run code concurrently with Coroutines.
|
||||
|
||||
|
||||
|
||||
=== Controllers
|
||||
|
||||
Here is an example of a Coroutines `@RestController`.
|
||||
@@ -554,6 +590,8 @@ class CoroutinesViewController(banner: Banner) {
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
|
||||
=== WebFlux.fn
|
||||
|
||||
Here is an example of Coroutines router defined via the {docs-spring-framework}/kdoc-api/spring-webflux/org.springframework.web.reactive.function.server/co-router.html[coRouter { }] DSL and related handlers.
|
||||
@@ -587,6 +625,8 @@ class UserHandler(builder: WebClient.Builder) {
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
|
||||
=== Transactions
|
||||
|
||||
Transactions on Coroutines are supported via the programmatic variant of the Reactive
|
||||
@@ -636,6 +676,8 @@ For Kotlin `Flow`, a `Flow<T>.transactional` extension is provided.
|
||||
----
|
||||
|
||||
|
||||
|
||||
|
||||
[[kotlin-spring-projects-in-kotlin]]
|
||||
== Spring Projects in Kotlin
|
||||
|
||||
@@ -683,6 +725,8 @@ NOTE: The Kotlin code samples in Spring Framework documentation do not explicitl
|
||||
`open` on the classes and their member functions. The samples are written for projects
|
||||
using the `kotlin-allopen` plugin, since this is the most commonly used setup.
|
||||
|
||||
|
||||
|
||||
=== Using Immutable Class Instances for Persistence
|
||||
|
||||
In Kotlin, it is convenient and considered to be a best practice to declare read-only properties
|
||||
@@ -726,6 +770,8 @@ NOTE: As of the Kay release train, Spring Data supports Kotlin immutable class i
|
||||
does not require the `kotlin-noarg` plugin if the module uses Spring Data object mappings
|
||||
(such as MongoDB, Redis, Cassandra, and others).
|
||||
|
||||
|
||||
|
||||
=== Injecting Dependencies
|
||||
|
||||
Our recommendation is to try to favor constructor injection with `val` read-only (and
|
||||
@@ -761,6 +807,8 @@ as the following example shows:
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
|
||||
=== Injecting Configuration Properties
|
||||
|
||||
In Java, you can inject configuration properties by using annotations (such as pass:q[`@Value("${property}")`)].
|
||||
@@ -801,6 +849,7 @@ that uses the `${...}` syntax, with configuration beans, as the following exampl
|
||||
----
|
||||
|
||||
|
||||
|
||||
=== Checked Exceptions
|
||||
|
||||
Java and https://kotlinlang.org/docs/reference/exceptions.html[Kotlin exception handling]
|
||||
@@ -813,6 +862,8 @@ To get the original exception thrown like in Java, methods should be annotated w
|
||||
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-throws/index.html[`@Throws`]
|
||||
to specify explicitly the checked exceptions thrown (for example `@Throws(IOException::class)`).
|
||||
|
||||
|
||||
|
||||
=== Annotation Array Attributes
|
||||
|
||||
Kotlin annotations are mostly similar to Java annotations, but array attributes (which are
|
||||
@@ -857,6 +908,8 @@ use a shortcut annotation, such as `@GetMapping`, `@PostMapping`, and others.
|
||||
NOTE: If the `@RequestMapping` `method` attribute is not specified, all HTTP methods will
|
||||
be matched, not only the `GET` method.
|
||||
|
||||
|
||||
|
||||
=== Testing
|
||||
|
||||
This section addresses testing with the combination of Kotlin and Spring Framework.
|
||||
@@ -866,6 +919,7 @@ https://mockk.io/[Mockk] for mocking.
|
||||
NOTE: If you are using Spring Boot, see
|
||||
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-kotlin-testing[this related documentation].
|
||||
|
||||
|
||||
==== Constructor injection
|
||||
|
||||
As described in the <<testing#testcontext-junit-jupiter-di, dedicated section>>,
|
||||
@@ -887,6 +941,7 @@ class OrderServiceIntegrationTests(val orderService: OrderService,
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
==== `PER_CLASS` Lifecycle
|
||||
|
||||
Kotlin lets you specify meaningful test function names between backticks (```).
|
||||
@@ -930,6 +985,7 @@ class IntegrationTests {
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
==== Specification-like Tests
|
||||
|
||||
You can create specification-like tests with JUnit 5 and Kotlin.
|
||||
@@ -959,6 +1015,7 @@ class SpecificationLikeTests {
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
[[kotlin-webtestclient-issue]]
|
||||
==== `WebTestClient` Type Inference Issue in Kotlin
|
||||
|
||||
@@ -968,17 +1025,24 @@ since it provides a workaround for the Kotlin issue with the Java API.
|
||||
|
||||
See also the related https://jira.spring.io/browse/SPR-16057[SPR-16057] issue.
|
||||
|
||||
|
||||
|
||||
|
||||
[[kotlin-getting-started]]
|
||||
== Getting Started
|
||||
|
||||
The easiest way to learn how to build a Spring application with Kotlin is to follow
|
||||
https://spring.io/guides/tutorials/spring-boot-kotlin/[the dedicated tutorial].
|
||||
|
||||
|
||||
|
||||
=== `start.spring.io`
|
||||
|
||||
The easiest way to start a new Spring Framework project in Kotlin is to create a new Spring
|
||||
Boot 2 project on https://start.spring.io/#!language=kotlin&type=gradle-project[start.spring.io].
|
||||
|
||||
|
||||
|
||||
=== Choosing the Web Flavor
|
||||
|
||||
Spring Framework now comes with two different web stacks: <<web#mvc, Spring MVC>> and
|
||||
@@ -991,6 +1055,9 @@ Kotlin DSL.
|
||||
For other use cases, especially if you are using blocking technologies such as JPA, Spring
|
||||
MVC and its annotation-based programming model is the recommended choice.
|
||||
|
||||
|
||||
|
||||
|
||||
[[kotlin-resources]]
|
||||
== Resources
|
||||
|
||||
@@ -1004,6 +1071,8 @@ Kotlin and the Spring Framework:
|
||||
* https://blog.jetbrains.com/kotlin/[Kotlin blog]
|
||||
* https://kotlin.link/[Awesome Kotlin]
|
||||
|
||||
|
||||
|
||||
=== Examples
|
||||
|
||||
The following Github projects offer examples that you can learn from and possibly even extend:
|
||||
@@ -1016,6 +1085,8 @@ The following Github projects offer examples that you can learn from and possibl
|
||||
* https://github.com/sdeleuze/spring-kotlin-deepdive[spring-kotlin-deepdive]: A step-by-step migration guide for Boot 1.0 and Java to Boot 2.0 and Kotlin
|
||||
* https://github.com/spring-cloud/spring-cloud-gcp/tree/master/spring-cloud-gcp-kotlin-samples/spring-cloud-gcp-kotlin-app-sample[spring-cloud-gcp-kotlin-app-sample]: Spring Boot with Google Cloud Platform Integrations
|
||||
|
||||
|
||||
|
||||
=== Issues
|
||||
|
||||
The following list categorizes the pending issues related to Spring and Kotlin support:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
[[overview]]
|
||||
= Spring Framework Overview
|
||||
include::attributes.adoc[]
|
||||
:toc: left
|
||||
:toclevels: 1
|
||||
:docinfo1:
|
||||
@@ -7,10 +8,8 @@
|
||||
Spring makes it easy to create Java enterprise applications. It provides everything you
|
||||
need to embrace the Java language in an enterprise environment, with support for Groovy
|
||||
and Kotlin as alternative languages on the JVM, and with the flexibility to create many
|
||||
kinds of architectures depending on an application's needs. As of Spring Framework 5.1,
|
||||
Spring requires JDK 8+ (Java SE 8+) and provides out-of-the-box support for JDK 11 LTS.
|
||||
Java SE 8 update 60 is suggested as the minimum patch release for Java 8, but it is
|
||||
generally recommended to use a recent patch release.
|
||||
kinds of architectures depending on an application's needs. As of Spring Framework 6.0,
|
||||
Spring requires Java 17+.
|
||||
|
||||
Spring supports a wide range of application scenarios. In a large enterprise, applications
|
||||
often exist for a long time and have to run on a JDK and application server whose upgrade
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:tabsize: 4
|
||||
:docinfo1:
|
||||
@@ -1,8 +1,7 @@
|
||||
[[rsocket]]
|
||||
= RSocket
|
||||
:gh-rsocket: https://github.com/rsocket
|
||||
:gh-rsocket-java: {gh-rsocket}/rsocket-java
|
||||
:gh-rsocket-extensions: {gh-rsocket}/rsocket/blob/master/Extensions
|
||||
include::attributes.adoc[]
|
||||
include::page-layout.adoc[]
|
||||
|
||||
This section describes Spring Framework's support for the RSocket protocol.
|
||||
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
:noheader:
|
||||
:toc:
|
||||
include::attributes.adoc[]
|
||||
= Spring Framework Documentation
|
||||
Rod Johnson; Juergen Hoeller; Keith Donald; Colin Sampaleanu; Rob Harrop; Thomas Risberg; Alef Arendsen; Darren Davison; Dmitriy Kopylenko; Mark Pollack; Thierry Templier; Erwin Vervaet; Portia Tung; Ben Hale; Adrian Colyer; John Lewis; Costin Leau; Mark Fisher; Sam Brannen; Ramnivas Laddad; Arjen Poutsma; Chris Beams; Tareq Abedrabbo; Andy Clement; Dave Syer; Oliver Gierke; Rossen Stoyanchev; Phillip Webb; Rob Winch; Brian Clozel; Stephane Nicoll; Sebastien Deleuze; Jay Bryant; Mark Paluch
|
||||
|
||||
NOTE: This documentation is also available in {docs-spring-framework}/reference/html/index.html[HTML] format.
|
||||
|
||||
[[legal]]
|
||||
== Legal
|
||||
|
||||
Copyright © 2002 - 2022 VMware, Inc. All Rights Reserved.
|
||||
|
||||
Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
|
||||
|
||||
include::overview.adoc[leveloffset=+1]
|
||||
include::core.adoc[leveloffset=+1]
|
||||
@@ -10,16 +22,3 @@ include::web-reactive.adoc[leveloffset=+1]
|
||||
include::integration.adoc[leveloffset=+1]
|
||||
include::languages.adoc[leveloffset=+1]
|
||||
include::appendix.adoc[leveloffset=+1]
|
||||
|
||||
Rod Johnson, Juergen Hoeller, Keith Donald, Colin Sampaleanu, Rob Harrop, Thomas Risberg,
|
||||
Alef Arendsen, Darren Davison, Dmitriy Kopylenko, Mark Pollack, Thierry Templier, Erwin
|
||||
Vervaet, Portia Tung, Ben Hale, Adrian Colyer, John Lewis, Costin Leau, Mark Fisher, Sam
|
||||
Brannen, Ramnivas Laddad, Arjen Poutsma, Chris Beams, Tareq Abedrabbo, Andy Clement, Dave
|
||||
Syer, Oliver Gierke, Rossen Stoyanchev, Phillip Webb, Rob Winch, Brian Clozel, Stephane
|
||||
Nicoll, Sebastien Deleuze, Jay Bryant, Mark Paluch
|
||||
|
||||
Copyright © 2002 - 2022 VMware, Inc. All Rights Reserved.
|
||||
|
||||
Copies of this document may be made for your own use and for distribution to others,
|
||||
provided that you do not charge any fee for such copies and further provided that each
|
||||
copy contains this Copyright Notice, whether distributed in print or electronically.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,155 @@
|
||||
[[integration-testing]]
|
||||
= Integration Testing
|
||||
|
||||
It is important to be able to perform some integration testing without requiring
|
||||
deployment to your application server or connecting to other enterprise infrastructure.
|
||||
Doing so lets you test things such as:
|
||||
|
||||
* The correct wiring of your Spring IoC container contexts.
|
||||
* Data access using JDBC or an ORM tool. This can include such things as the correctness
|
||||
of SQL statements, Hibernate queries, JPA entity mappings, and so forth.
|
||||
|
||||
The Spring Framework provides first-class support for integration testing in the
|
||||
`spring-test` module. The name of the actual JAR file might include the release version
|
||||
and might also be in the long `org.springframework.test` form, depending on where you get
|
||||
it from (see the <<core.adoc#beans-dependencies, section on Dependency Management>>
|
||||
for an explanation). This library includes the `org.springframework.test` package, which
|
||||
contains valuable classes for integration testing with a Spring container. This testing
|
||||
does not rely on an application server or other deployment environment. Such tests are
|
||||
slower to run than unit tests but much faster than the equivalent Selenium tests or
|
||||
remote tests that rely on deployment to an application server.
|
||||
|
||||
Unit and integration testing support is provided in the form of the annotation-driven
|
||||
<<testcontext-framework, Spring TestContext Framework>>. The TestContext framework is
|
||||
agnostic of the actual testing framework in use, which allows instrumentation of tests
|
||||
in various environments, including JUnit, TestNG, and others.
|
||||
|
||||
The following section provides an overview of the high-level goals of Spring's
|
||||
integration support, and the rest of this chapter then focuses on dedicated topics:
|
||||
|
||||
* <<integration-testing-support-jdbc>>
|
||||
* <<testcontext-framework>>
|
||||
* <<webtestclient>>
|
||||
* <<spring-mvc-test-framework>>
|
||||
* <<spring-mvc-test-client>>
|
||||
* <<integration-testing-annotations>>
|
||||
|
||||
|
||||
|
||||
[[integration-testing-goals]]
|
||||
== Goals of Integration Testing
|
||||
|
||||
Spring's integration testing support has the following primary goals:
|
||||
|
||||
* To manage <<testing-ctx-management, Spring IoC container caching>> between tests.
|
||||
* To provide <<testing-fixture-di, Dependency Injection of test fixture instances>>.
|
||||
* To provide <<testing-tx, transaction management>> appropriate to integration testing.
|
||||
* To supply <<testing-support-classes, Spring-specific base classes>> that assist
|
||||
developers in writing integration tests.
|
||||
|
||||
The next few sections describe each goal and provide links to implementation and
|
||||
configuration details.
|
||||
|
||||
|
||||
[[testing-ctx-management]]
|
||||
=== Context Management and Caching
|
||||
|
||||
The Spring TestContext Framework provides consistent loading of Spring
|
||||
`ApplicationContext` instances and `WebApplicationContext` instances as well as caching
|
||||
of those contexts. Support for the caching of loaded contexts is important, because
|
||||
startup time can become an issue -- not because of the overhead of Spring itself, but
|
||||
because the objects instantiated by the Spring container take time to instantiate. For
|
||||
example, a project with 50 to 100 Hibernate mapping files might take 10 to 20 seconds to
|
||||
load the mapping files, and incurring that cost before running every test in every test
|
||||
fixture leads to slower overall test runs that reduce developer productivity.
|
||||
|
||||
Test classes typically declare either an array of resource locations for XML or Groovy
|
||||
configuration metadata -- often in the classpath -- or an array of component classes that
|
||||
is used to configure the application. These locations or classes are the same as or
|
||||
similar to those specified in `web.xml` or other configuration files for production
|
||||
deployments.
|
||||
|
||||
By default, once loaded, the configured `ApplicationContext` is reused for each test.
|
||||
Thus, the setup cost is incurred only once per test suite, and subsequent test execution
|
||||
is much faster. In this context, the term "`test suite`" means all tests run in the same
|
||||
JVM -- for example, all tests run from an Ant, Maven, or Gradle build for a given project
|
||||
or module. In the unlikely case that a test corrupts the application context and requires
|
||||
reloading (for example, by modifying a bean definition or the state of an application
|
||||
object) the TestContext framework can be configured to reload the configuration and
|
||||
rebuild the application context before executing the next test.
|
||||
|
||||
See <<testcontext-ctx-management>> and <<testcontext-ctx-management-caching>> with the
|
||||
TestContext framework.
|
||||
|
||||
|
||||
[[testing-fixture-di]]
|
||||
=== Dependency Injection of Test Fixtures
|
||||
|
||||
When the TestContext framework loads your application context, it can optionally
|
||||
configure instances of your test classes by using Dependency Injection. This provides a
|
||||
convenient mechanism for setting up test fixtures by using preconfigured beans from your
|
||||
application context. A strong benefit here is that you can reuse application contexts
|
||||
across various testing scenarios (for example, for configuring Spring-managed object
|
||||
graphs, transactional proxies, `DataSource` instances, and others), thus avoiding the
|
||||
need to duplicate complex test fixture setup for individual test cases.
|
||||
|
||||
As an example, consider a scenario where we have a class (`HibernateTitleRepository`)
|
||||
that implements data access logic for a `Title` domain entity. We want to write
|
||||
integration tests that test the following areas:
|
||||
|
||||
* The Spring configuration: Basically, is everything related to the configuration of the
|
||||
`HibernateTitleRepository` bean correct and present?
|
||||
* The Hibernate mapping file configuration: Is everything mapped correctly and are the
|
||||
correct lazy-loading settings in place?
|
||||
* The logic of the `HibernateTitleRepository`: Does the configured instance of this class
|
||||
perform as anticipated?
|
||||
|
||||
See dependency injection of test fixtures with the
|
||||
<<testcontext-fixture-di, TestContext framework>>.
|
||||
|
||||
|
||||
[[testing-tx]]
|
||||
=== Transaction Management
|
||||
|
||||
One common issue in tests that access a real database is their effect on the state of the
|
||||
persistence store. Even when you use a development database, changes to the state may
|
||||
affect future tests. Also, many operations -- such as inserting or modifying persistent
|
||||
data -- cannot be performed (or verified) outside of a transaction.
|
||||
|
||||
The TestContext framework addresses this issue. By default, the framework creates and
|
||||
rolls back a transaction for each test. You can write code that can assume the existence
|
||||
of a transaction. If you call transactionally proxied objects in your tests, they behave
|
||||
correctly, according to their configured transactional semantics. In addition, if a test
|
||||
method deletes the contents of selected tables while running within the transaction
|
||||
managed for the test, the transaction rolls back by default, and the database returns to
|
||||
its state prior to execution of the test. Transactional support is provided to a test by
|
||||
using a `PlatformTransactionManager` bean defined in the test's application context.
|
||||
|
||||
If you want a transaction to commit (unusual, but occasionally useful when you want a
|
||||
particular test to populate or modify the database), you can tell the TestContext
|
||||
framework to cause the transaction to commit instead of roll back by using the
|
||||
<<integration-testing-annotations, `@Commit`>> annotation.
|
||||
|
||||
See transaction management with the <<testcontext-tx, TestContext framework>>.
|
||||
|
||||
|
||||
[[testing-support-classes]]
|
||||
=== Support Classes for Integration Testing
|
||||
|
||||
The Spring TestContext Framework provides several `abstract` support classes that
|
||||
simplify the writing of integration tests. These base test classes provide well-defined
|
||||
hooks into the testing framework as well as convenient instance variables and methods,
|
||||
which let you access:
|
||||
|
||||
* The `ApplicationContext`, for performing explicit bean lookups or testing the state of
|
||||
the context as a whole.
|
||||
* A `JdbcTemplate`, for executing SQL statements to query the database. You can use such
|
||||
queries to confirm database state both before and after execution of database-related
|
||||
application code, and Spring ensures that such queries run in the scope of the same
|
||||
transaction as the application code. When used in conjunction with an ORM tool, be sure
|
||||
to avoid <<testcontext-tx-false-positives, false positives>>.
|
||||
|
||||
In addition, you may want to create your own custom, application-wide superclass with
|
||||
instance variables and methods specific to your project.
|
||||
|
||||
See support classes for the <<testcontext-support-classes, TestContext framework>>.
|
||||
@@ -0,0 +1,136 @@
|
||||
[[spring-mvc-test-client]]
|
||||
= Testing Client Applications
|
||||
|
||||
You can use client-side tests to test code that internally uses the `RestTemplate`. The
|
||||
idea is to declare expected requests and to provide "`stub`" responses so that you can
|
||||
focus on testing the code in isolation (that is, without running a server). The following
|
||||
example shows how to do so:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();
|
||||
mockServer.expect(requestTo("/greeting")).andRespond(withSuccess());
|
||||
|
||||
// Test code that uses the above RestTemplate ...
|
||||
|
||||
mockServer.verify();
|
||||
----
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
.Kotlin
|
||||
----
|
||||
val restTemplate = RestTemplate()
|
||||
|
||||
val mockServer = MockRestServiceServer.bindTo(restTemplate).build()
|
||||
mockServer.expect(requestTo("/greeting")).andRespond(withSuccess())
|
||||
|
||||
// Test code that uses the above RestTemplate ...
|
||||
|
||||
mockServer.verify()
|
||||
----
|
||||
|
||||
In the preceding example, `MockRestServiceServer` (the central class for client-side REST
|
||||
tests) configures the `RestTemplate` with a custom `ClientHttpRequestFactory` that
|
||||
asserts actual requests against expectations and returns "`stub`" responses. In this
|
||||
case, we expect a request to `/greeting` and want to return a 200 response with
|
||||
`text/plain` content. We can define additional expected requests and stub responses as
|
||||
needed. When we define expected requests and stub responses, the `RestTemplate` can be
|
||||
used in client-side code as usual. At the end of testing, `mockServer.verify()` can be
|
||||
used to verify that all expectations have been satisfied.
|
||||
|
||||
By default, requests are expected in the order in which expectations were declared. You
|
||||
can set the `ignoreExpectOrder` option when building the server, in which case all
|
||||
expectations are checked (in order) to find a match for a given request. That means
|
||||
requests are allowed to come in any order. The following example uses `ignoreExpectOrder`:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
server = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build();
|
||||
----
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
.Kotlin
|
||||
----
|
||||
server = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build()
|
||||
----
|
||||
|
||||
Even with unordered requests by default, each request is allowed to run once only.
|
||||
The `expect` method provides an overloaded variant that accepts an `ExpectedCount`
|
||||
argument that specifies a count range (for example, `once`, `manyTimes`, `max`, `min`,
|
||||
`between`, and so on). The following example uses `times`:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();
|
||||
mockServer.expect(times(2), requestTo("/something")).andRespond(withSuccess());
|
||||
mockServer.expect(times(3), requestTo("/somewhere")).andRespond(withSuccess());
|
||||
|
||||
// ...
|
||||
|
||||
mockServer.verify();
|
||||
----
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
.Kotlin
|
||||
----
|
||||
val restTemplate = RestTemplate()
|
||||
|
||||
val mockServer = MockRestServiceServer.bindTo(restTemplate).build()
|
||||
mockServer.expect(times(2), requestTo("/something")).andRespond(withSuccess())
|
||||
mockServer.expect(times(3), requestTo("/somewhere")).andRespond(withSuccess())
|
||||
|
||||
// ...
|
||||
|
||||
mockServer.verify()
|
||||
----
|
||||
|
||||
Note that, when `ignoreExpectOrder` is not set (the default), and, therefore, requests
|
||||
are expected in order of declaration, then that order applies only to the first of any
|
||||
expected request. For example if "/something" is expected two times followed by
|
||||
"/somewhere" three times, then there should be a request to "/something" before there is
|
||||
a request to "/somewhere", but, aside from that subsequent "/something" and "/somewhere",
|
||||
requests can come at any time.
|
||||
|
||||
As an alternative to all of the above, the client-side test support also provides a
|
||||
`ClientHttpRequestFactory` implementation that you can configure into a `RestTemplate` to
|
||||
bind it to a `MockMvc` instance. That allows processing requests using actual server-side
|
||||
logic but without running a server. The following example shows how to do so:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
||||
this.restTemplate = new RestTemplate(new MockMvcClientHttpRequestFactory(mockMvc));
|
||||
|
||||
// Test code that uses the above RestTemplate ...
|
||||
----
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
.Kotlin
|
||||
----
|
||||
val mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build()
|
||||
restTemplate = RestTemplate(MockMvcClientHttpRequestFactory(mockMvc))
|
||||
|
||||
// Test code that uses the above RestTemplate ...
|
||||
----
|
||||
|
||||
[[spring-mvc-test-client-static-imports]]
|
||||
== Static Imports
|
||||
|
||||
As with server-side tests, the fluent API for client-side tests requires a few static
|
||||
imports. Those are easy to find by searching for `MockRest*`. Eclipse users should add
|
||||
`MockRestRequestMatchers.{asterisk}` and `MockRestResponseCreators.{asterisk}` as
|
||||
"`favorite static members`" in the Eclipse preferences under Java -> Editor -> Content
|
||||
Assist -> Favorites. That allows using content assist after typing the first character of
|
||||
the static method name. Other IDEs (such IntelliJ) may not require any additional
|
||||
configuration. Check for the support for code completion on static members.
|
||||
|
||||
[[spring-mvc-test-client-resources]]
|
||||
== Further Examples of Client-side REST Tests
|
||||
|
||||
Spring MVC Test's own tests include
|
||||
{spring-framework-main-code}/spring-test/src/test/java/org/springframework/test/web/client/samples[example
|
||||
tests] of client-side REST tests.
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,6 @@
|
||||
[[testing.appendix]]
|
||||
= Appendix
|
||||
|
||||
include::testing-annotations.adoc[leveloffset=+1]
|
||||
|
||||
include::testing-resources.adoc[leveloffset=+1]
|
||||
@@ -0,0 +1,8 @@
|
||||
[[testing-introduction]]
|
||||
= Introduction to Spring Testing
|
||||
|
||||
Testing is an integral part of enterprise software development. This chapter focuses on
|
||||
the value added by the IoC principle to <<unit-testing, unit testing>> and on the benefits
|
||||
of the Spring Framework's support for <<integration-testing, integration testing>>. (A
|
||||
thorough treatment of testing in the enterprise is beyond the scope of this reference
|
||||
manual.)
|
||||
@@ -0,0 +1,32 @@
|
||||
[[testing-resources]]
|
||||
= Further Resources
|
||||
See the following resources for more information about testing:
|
||||
|
||||
* https://www.junit.org/[JUnit]: "A programmer-friendly testing framework for Java and the JVM".
|
||||
Used by the Spring Framework in its test suite and supported in the
|
||||
<<testcontext-framework, Spring TestContext Framework>>.
|
||||
* https://testng.org/[TestNG]: A testing framework inspired by JUnit with added support
|
||||
for test groups, data-driven testing, distributed testing, and other features. Supported
|
||||
in the <<testcontext-framework, Spring TestContext Framework>>
|
||||
* https://assertj.github.io/doc/[AssertJ]: "Fluent assertions for Java",
|
||||
including support for Java 8 lambdas, streams, and numerous other features.
|
||||
* https://en.wikipedia.org/wiki/Mock_Object[Mock Objects]: Article in Wikipedia.
|
||||
* http://www.mockobjects.com/[MockObjects.com]: Web site dedicated to mock objects, a
|
||||
technique for improving the design of code within test-driven development.
|
||||
* https://mockito.github.io[Mockito]: Java mock library based on the
|
||||
http://xunitpatterns.com/Test%20Spy.html[Test Spy] pattern. Used by the Spring Framework
|
||||
in its test suite.
|
||||
* https://easymock.org/[EasyMock]: Java library "that provides Mock Objects for
|
||||
interfaces (and objects through the class extension) by generating them on the fly using
|
||||
Java's proxy mechanism."
|
||||
* https://jmock.org/[JMock]: Library that supports test-driven development of Java code
|
||||
with mock objects.
|
||||
* https://www.dbunit.org/[DbUnit]: JUnit extension (also usable with Ant and Maven) that
|
||||
is targeted at database-driven projects and, among other things, puts your database into
|
||||
a known state between test runs.
|
||||
* https://www.testcontainers.org/[Testcontainers]: Java library that supports JUnit
|
||||
tests, providing lightweight, throwaway instances of common databases, Selenium web
|
||||
browsers, or anything else that can run in a Docker container.
|
||||
* https://sourceforge.net/projects/grinder/[The Grinder]: Java load testing framework.
|
||||
* https://github.com/Ninja-Squad/springmockk[SpringMockK]: Support for Spring Boot
|
||||
integration tests written in Kotlin using https://mockk.io/[MockK] instead of Mockito.
|
||||
@@ -0,0 +1,35 @@
|
||||
[[integration-testing-support-jdbc]]
|
||||
= JDBC Testing Support
|
||||
|
||||
[[integration-testing-support-jdbc-test-utils]]
|
||||
== JdbcTestUtils
|
||||
|
||||
The `org.springframework.test.jdbc` package contains `JdbcTestUtils`, which is a
|
||||
collection of JDBC-related utility functions intended to simplify standard database
|
||||
testing scenarios. Specifically, `JdbcTestUtils` provides the following static utility
|
||||
methods.
|
||||
|
||||
* `countRowsInTable(..)`: Counts the number of rows in the given table.
|
||||
* `countRowsInTableWhere(..)`: Counts the number of rows in the given table by using the
|
||||
provided `WHERE` clause.
|
||||
* `deleteFromTables(..)`: Deletes all rows from the specified tables.
|
||||
* `deleteFromTableWhere(..)`: Deletes rows from the given table by using the provided
|
||||
`WHERE` clause.
|
||||
* `dropTables(..)`: Drops the specified tables.
|
||||
|
||||
[TIP]
|
||||
====
|
||||
<<testcontext-support-classes-junit4, `AbstractTransactionalJUnit4SpringContextTests`>>
|
||||
and <<testcontext-support-classes-testng, `AbstractTransactionalTestNGSpringContextTests`>>
|
||||
provide convenience methods that delegate to the aforementioned methods in
|
||||
`JdbcTestUtils`.
|
||||
====
|
||||
|
||||
[[integration-testing-support-jdbc-embedded-database]]
|
||||
== Embedded Databases
|
||||
|
||||
The `spring-jdbc` module provides support for configuring and launching an embedded
|
||||
database, which you can use in integration tests that interact with a database.
|
||||
For details, see <<data-access.adoc#jdbc-embedded-database-support, Embedded Database
|
||||
Support>> and <<data-access.adoc#jdbc-embedded-database-dao-testing, Testing Data Access
|
||||
Logic with an Embedded Database>>.
|
||||
@@ -0,0 +1,168 @@
|
||||
[[unit-testing]]
|
||||
= Unit Testing
|
||||
|
||||
Dependency injection should make your code less dependent on the container than it would
|
||||
be with traditional J2EE / Java EE development. The POJOs that make up your application
|
||||
should be testable in JUnit or TestNG tests, with objects instantiated by using the `new`
|
||||
operator, without Spring or any other container. You can use <<mock-objects, mock objects>>
|
||||
(in conjunction with other valuable testing techniques) to test your code in isolation.
|
||||
If you follow the architecture recommendations for Spring, the resulting clean layering
|
||||
and componentization of your codebase facilitate easier unit testing. For example,
|
||||
you can test service layer objects by stubbing or mocking DAO or repository interfaces,
|
||||
without needing to access persistent data while running unit tests.
|
||||
|
||||
True unit tests typically run extremely quickly, as there is no runtime infrastructure to
|
||||
set up. Emphasizing true unit tests as part of your development methodology can boost
|
||||
your productivity. You may not need this section of the testing chapter to help you write
|
||||
effective unit tests for your IoC-based applications. For certain unit testing scenarios,
|
||||
however, the Spring Framework provides mock objects and testing support classes, which
|
||||
are described in this chapter.
|
||||
|
||||
|
||||
|
||||
[[mock-objects]]
|
||||
== Mock Objects
|
||||
|
||||
Spring includes a number of packages dedicated to mocking:
|
||||
|
||||
* <<mock-objects-env>>
|
||||
* <<mock-objects-jndi>>
|
||||
* <<mock-objects-servlet>>
|
||||
* <<mock-objects-web-reactive>>
|
||||
|
||||
|
||||
[[mock-objects-env]]
|
||||
=== Environment
|
||||
|
||||
The `org.springframework.mock.env` package contains mock implementations of the
|
||||
`Environment` and `PropertySource` abstractions (see
|
||||
<<core.adoc#beans-definition-profiles, Bean Definition Profiles>>
|
||||
and <<core.adoc#beans-property-source-abstraction, `PropertySource` Abstraction>>).
|
||||
`MockEnvironment` and `MockPropertySource` are useful for developing
|
||||
out-of-container tests for code that depends on environment-specific properties.
|
||||
|
||||
|
||||
[[mock-objects-jndi]]
|
||||
=== JNDI
|
||||
|
||||
The `org.springframework.mock.jndi` package contains a partial implementation of the JNDI
|
||||
SPI, which you can use to set up a simple JNDI environment for test suites or stand-alone
|
||||
applications. If, for example, JDBC `DataSource` instances get bound to the same JNDI
|
||||
names in test code as they do in a Jakarta EE container, you can reuse both application code
|
||||
and configuration in testing scenarios without modification.
|
||||
|
||||
WARNING: The mock JNDI support in the `org.springframework.mock.jndi` package is
|
||||
officially deprecated as of Spring Framework 5.2 in favor of complete solutions from third
|
||||
parties such as https://github.com/h-thurow/Simple-JNDI[Simple-JNDI].
|
||||
|
||||
|
||||
[[mock-objects-servlet]]
|
||||
=== Servlet API
|
||||
|
||||
The `org.springframework.mock.web` package contains a comprehensive set of Servlet API
|
||||
mock objects that are useful for testing web contexts, controllers, and filters. These
|
||||
mock objects are targeted at usage with Spring's Web MVC framework and are generally more
|
||||
convenient to use than dynamic mock objects (such as https://easymock.org/[EasyMock])
|
||||
or alternative Servlet API mock objects (such as http://www.mockobjects.com[MockObjects]).
|
||||
|
||||
TIP: Since Spring Framework 6.0, the mock objects in `org.springframework.mock.web` are
|
||||
based on the Servlet 6.0 API.
|
||||
|
||||
The Spring MVC Test framework builds on the mock Servlet API objects to provide an
|
||||
integration testing framework for Spring MVC. See <<spring-mvc-test-framework>>.
|
||||
|
||||
|
||||
[[mock-objects-web-reactive]]
|
||||
=== Spring Web Reactive
|
||||
|
||||
The `org.springframework.mock.http.server.reactive` package contains mock implementations
|
||||
of `ServerHttpRequest` and `ServerHttpResponse` for use in WebFlux applications. The
|
||||
`org.springframework.mock.web.server` package contains a mock `ServerWebExchange` that
|
||||
depends on those mock request and response objects.
|
||||
|
||||
Both `MockServerHttpRequest` and `MockServerHttpResponse` extend from the same abstract
|
||||
base classes as server-specific implementations and share behavior with them. For
|
||||
example, a mock request is immutable once created, but you can use the `mutate()` method
|
||||
from `ServerHttpRequest` to create a modified instance.
|
||||
|
||||
In order for the mock response to properly implement the write contract and return a
|
||||
write completion handle (that is, `Mono<Void>`), it by default uses a `Flux` with
|
||||
`cache().then()`, which buffers the data and makes it available for assertions in tests.
|
||||
Applications can set a custom write function (for example, to test an infinite stream).
|
||||
|
||||
The <<webtestclient>> builds on the mock request and response to provide support for
|
||||
testing WebFlux applications without an HTTP server. The client can also be used for
|
||||
end-to-end tests with a running server.
|
||||
|
||||
|
||||
|
||||
[[unit-testing-support-classes]]
|
||||
== Unit Testing Support Classes
|
||||
|
||||
Spring includes a number of classes that can help with unit testing. They fall into two
|
||||
categories:
|
||||
|
||||
* <<unit-testing-utilities>>
|
||||
* <<unit-testing-spring-mvc>>
|
||||
|
||||
|
||||
[[unit-testing-utilities]]
|
||||
=== General Testing Utilities
|
||||
|
||||
The `org.springframework.test.util` package contains several general purpose utilities
|
||||
for use in unit and integration testing.
|
||||
|
||||
{api-spring-framework}/test/util/AopTestUtils.html[`AopTestUtils`] is a collection of
|
||||
AOP-related utility methods. You can use these methods to obtain a reference to the
|
||||
underlying target object hidden behind one or more Spring proxies. For example, if you
|
||||
have configured a bean as a dynamic mock by using a library such as EasyMock or Mockito,
|
||||
and the mock is wrapped in a Spring proxy, you may need direct access to the underlying
|
||||
mock to configure expectations on it and perform verifications. For Spring's core AOP
|
||||
utilities, see {api-spring-framework}/aop/support/AopUtils.html[`AopUtils`] and
|
||||
{api-spring-framework}/aop/framework/AopProxyUtils.html[`AopProxyUtils`].
|
||||
|
||||
{api-spring-framework}/test/util/ReflectionTestUtils.html[`ReflectionTestUtils`] is a
|
||||
collection of reflection-based utility methods. You can use these methods in testing
|
||||
scenarios where you need to change the value of a constant, set a non-`public` field,
|
||||
invoke a non-`public` setter method, or invoke a non-`public` configuration or lifecycle
|
||||
callback method when testing application code for use cases such as the following:
|
||||
|
||||
* ORM frameworks (such as JPA and Hibernate) that condone `private` or `protected` field
|
||||
access as opposed to `public` setter methods for properties in a domain entity.
|
||||
* Spring's support for annotations (such as `@Autowired`, `@Inject`, and `@Resource`),
|
||||
that provide dependency injection for `private` or `protected` fields, setter methods,
|
||||
and configuration methods.
|
||||
* Use of annotations such as `@PostConstruct` and `@PreDestroy` for lifecycle callback
|
||||
methods.
|
||||
|
||||
{api-spring-framework}/test/util/TestSocketUtils.html[`TestSocketUtils`] is a simple
|
||||
utility for finding available TCP ports on `localhost` for use in integration testing
|
||||
scenarios.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
`TestSocketUtils` can be used in integration tests which start an external server on an
|
||||
available random port. However, these utilities make no guarantee about the subsequent
|
||||
availability of a given port and are therefore unreliable. Instead of using
|
||||
`TestSocketUtils` to find an available local port for a server, it is recommended that
|
||||
you rely on a server's ability to start on a random ephemeral port that it selects or is
|
||||
assigned by the operating system. To interact with that server, you should query the
|
||||
server for the port it is currently using.
|
||||
====
|
||||
|
||||
|
||||
[[unit-testing-spring-mvc]]
|
||||
=== Spring MVC Testing Utilities
|
||||
|
||||
The `org.springframework.test.web` package contains
|
||||
{api-spring-framework}/test/web/ModelAndViewAssert.html[`ModelAndViewAssert`], which you
|
||||
can use in combination with JUnit, TestNG, or any other testing framework for unit tests
|
||||
that deal with Spring MVC `ModelAndView` objects.
|
||||
|
||||
.Unit testing Spring MVC Controllers
|
||||
TIP: To unit test your Spring MVC `Controller` classes as POJOs, use `ModelAndViewAssert`
|
||||
combined with `MockHttpServletRequest`, `MockHttpSession`, and so on from Spring's
|
||||
<<mock-objects-servlet, Servlet API mocks>>. For thorough integration testing of your
|
||||
Spring MVC and REST `Controller` classes in conjunction with your `WebApplicationContext`
|
||||
configuration for Spring MVC, use the
|
||||
<<spring-mvc-test-framework, Spring MVC Test Framework>> instead.
|
||||
@@ -1,14 +1,12 @@
|
||||
[[spring-web-reactive]]
|
||||
= Web on Reactive Stack
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:tabsize: 4
|
||||
:docinfo1:
|
||||
include::attributes.adoc[]
|
||||
include::page-layout.adoc[]
|
||||
|
||||
This part of the documentation covers support for reactive-stack web applications built
|
||||
on a https://www.reactive-streams.org/[Reactive Streams] API to run on non-blocking
|
||||
servers, such as Netty, Undertow, and Servlet containers. Individual chapters cover
|
||||
the <<webflux.adoc#webflux, Spring WebFlux>> framework,
|
||||
the <<webflux, Spring WebFlux>> framework,
|
||||
the reactive <<webflux-client, `WebClient`>>, support for <<webflux-test, testing>>,
|
||||
and <<webflux-reactive-libraries, reactive libraries>>. For Servlet-stack web applications,
|
||||
see <<web.adoc#spring-web, Web on Servlet Stack>>.
|
||||
@@ -35,7 +33,7 @@ include::web/webflux-websocket.adoc[leveloffset=+1]
|
||||
|
||||
[[webflux-test]]
|
||||
== Testing
|
||||
[.small]#<<web.adoc#testing, Same in Spring MVC>>#
|
||||
[.small]#<<web.adoc#webmvc.test, Same in Spring MVC>>#
|
||||
|
||||
The `spring-test` module provides mock implementations of `ServerHttpRequest`,
|
||||
`ServerHttpResponse`, and `ServerWebExchange`.
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
[[spring-web]]
|
||||
= Web on Servlet Stack
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:tabsize: 4
|
||||
:docinfo1:
|
||||
include::attributes.adoc[]
|
||||
include::page-layout.adoc[]
|
||||
|
||||
This part of the documentation covers support for Servlet-stack web applications built on the
|
||||
Servlet API and deployed to Servlet containers. Individual chapters include <<mvc, Spring MVC>>,
|
||||
|
||||
@@ -9,7 +9,7 @@ particular architecture, technology, or methodology (although it certainly recom
|
||||
some over others). This freedom to pick and choose the architecture, technology, or
|
||||
methodology that is most relevant to a developer and their development team is
|
||||
arguably most evident in the web area, where Spring provides its own web frameworks
|
||||
(<<mvc, Spring MVC>> and <<webflux.adoc#webflux, Spring WebFlux>>) while, at the same time,
|
||||
(<<mvc, Spring MVC>> and <<web-reactive.adoc#webflux, Spring WebFlux>>) while, at the same time,
|
||||
supporting integration with a number of popular third-party web frameworks.
|
||||
|
||||
|
||||
@@ -23,21 +23,21 @@ first take a look at common Spring configuration that is not specific to any one
|
||||
framework. (This section is equally applicable to Spring's own web framework variants.)
|
||||
|
||||
One of the concepts (for want of a better word) espoused by Spring's lightweight
|
||||
application model is that of a layered architecture. Remember that in a "`classic`"
|
||||
application model is that of a layered architecture. Remember that in a "classic"
|
||||
layered architecture, the web layer is but one of many layers. It serves as one of the
|
||||
entry points into a server-side application, and it delegates to service objects
|
||||
(facades) that are defined in a service layer to satisfy business-specific (and
|
||||
presentation-technology agnostic) use cases. In Spring, these service objects, any other
|
||||
business-specific objects, data-access objects, and others exist in a distinct "`business
|
||||
context`", which contains no web or presentation layer objects (presentation objects,
|
||||
such as Spring MVC controllers, are typically configured in a distinct "`presentation
|
||||
context`"). This section details how you can configure a Spring container (a
|
||||
business-specific objects, data-access objects, and others exist in a distinct "business
|
||||
context", which contains no web or presentation layer objects (presentation objects,
|
||||
such as Spring MVC controllers, are typically configured in a distinct "presentation
|
||||
context"). This section details how you can configure a Spring container (a
|
||||
`WebApplicationContext`) that contains all of the 'business beans' in your application.
|
||||
|
||||
Moving on to specifics, all you need to do is declare a
|
||||
{api-spring-framework}/web/context/ContextLoaderListener.html[`ContextLoaderListener`]
|
||||
in the standard Jakarta EE servlet `web.xml` file of your web application and add a
|
||||
`contextConfigLocation`<context-param/> section (in the same file) that defines which
|
||||
`contextConfigLocation` `<context-param/>` section (in the same file) that defines which
|
||||
set of Spring XML configuration files to load.
|
||||
|
||||
Consider the following `<listener/>` configuration:
|
||||
@@ -67,7 +67,7 @@ object based on the bean definitions and stores it in the `ServletContext` of th
|
||||
application.
|
||||
|
||||
All Java web frameworks are built on top of the Servlet API, so you can use the
|
||||
following code snippet to get access to this "`business context`" `ApplicationContext`
|
||||
following code snippet to get access to this "business context" `ApplicationContext`
|
||||
created by the `ContextLoaderListener`.
|
||||
|
||||
The following example shows how to get the `WebApplicationContext`:
|
||||
@@ -119,7 +119,7 @@ The key element in Spring's JSF integration is the JSF `ELResolver` mechanism.
|
||||
|
||||
`SpringBeanFacesELResolver` is a JSF compliant `ELResolver` implementation,
|
||||
integrating with the standard Unified EL as used by JSF and JSP. It delegates to
|
||||
Spring's "`business context`" `WebApplicationContext` first and then to the
|
||||
Spring's "business context" `WebApplicationContext` first and then to the
|
||||
default resolver of the underlying JSF implementation.
|
||||
|
||||
Configuration-wise, you can define `SpringBeanFacesELResolver` in your JSF
|
||||
@@ -157,27 +157,26 @@ The following example shows how to use `FacesContextUtils`:
|
||||
|
||||
|
||||
[[struts]]
|
||||
== Apache Struts 2.x
|
||||
== Apache Struts
|
||||
|
||||
Invented by Craig McClanahan, https://struts.apache.org[Struts] is an open-source project
|
||||
hosted by the Apache Software Foundation. At the time, it greatly simplified the
|
||||
hosted by the Apache Software Foundation. Struts 1.x greatly simplified the
|
||||
JSP/Servlet programming paradigm and won over many developers who were using proprietary
|
||||
frameworks. It simplified the programming model, it was open source (and thus free as in
|
||||
beer), and it had a large community, which let the project grow and become popular among
|
||||
Java web developers.
|
||||
frameworks. It simplified the programming model; it was open source; and it had a large
|
||||
community, which let the project grow and become popular among Java web developers.
|
||||
|
||||
As a successor to the original Struts 1.x, check out Struts 2.x and the Struts-provided
|
||||
https://struts.apache.org/release/2.3.x/docs/spring-plugin.html[Spring Plugin] for the
|
||||
built-in Spring integration.
|
||||
As a successor to the original Struts 1.x, check out Struts 2.x or more recent versions
|
||||
as well as the Struts-provided
|
||||
https://struts.apache.org/plugins/spring/[Spring Plugin] for built-in Spring integration.
|
||||
|
||||
|
||||
|
||||
|
||||
[[tapestry]]
|
||||
== Apache Tapestry 5.x
|
||||
== Apache Tapestry
|
||||
|
||||
https://tapestry.apache.org/[Tapestry] is a ""Component oriented framework for creating
|
||||
dynamic, robust, highly scalable web applications in Java.""
|
||||
https://tapestry.apache.org/[Tapestry] is a "Component oriented framework for creating
|
||||
dynamic, robust, highly scalable web applications in Java."
|
||||
|
||||
While Spring has its own <<mvc, powerful web layer>>, there are a number of unique
|
||||
advantages to building an enterprise Java application by using a combination of Tapestry
|
||||
@@ -195,6 +194,6 @@ https://tapestry.apache.org/integrating-with-spring-framework.html[integration m
|
||||
The following links go to further resources about the various web frameworks described in
|
||||
this chapter.
|
||||
|
||||
* The https://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html[JSF] homepage
|
||||
* The https://www.oracle.com/java/technologies/javaserverfaces.html[JSF] homepage
|
||||
* The https://struts.apache.org/[Struts] homepage
|
||||
* The https://tapestry.apache.org/[Tapestry] homepage
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
.Java
|
||||
----
|
||||
UriComponents uriComponents = UriComponentsBuilder
|
||||
.fromUriString("https://example.com/hotels/{hotel}") // <1>
|
||||
.queryParam("q", "{q}") // <2>
|
||||
.fromUriString("https://example.com/hotels/{hotel}") // <1>
|
||||
.queryParam("q", "{q}") // <2>
|
||||
.encode() // <3>
|
||||
.build(); // <4>
|
||||
|
||||
URI uri = uriComponents.expand("Westin", "123").toUri(); // <5>
|
||||
URI uri = uriComponents.expand("Westin", "123").toUri(); // <5>
|
||||
----
|
||||
<1> Static factory method with a URI template.
|
||||
<2> Add or replace URI components.
|
||||
@@ -25,12 +25,12 @@
|
||||
.Kotlin
|
||||
----
|
||||
val uriComponents = UriComponentsBuilder
|
||||
.fromUriString("https://example.com/hotels/{hotel}") // <1>
|
||||
.queryParam("q", "{q}") // <2>
|
||||
.fromUriString("https://example.com/hotels/{hotel}") // <1>
|
||||
.queryParam("q", "{q}") // <2>
|
||||
.encode() // <3>
|
||||
.build() // <4>
|
||||
|
||||
val uri = uriComponents.expand("Westin", "123").toUri() // <5>
|
||||
val uri = uriComponents.expand("Westin", "123").toUri() // <5>
|
||||
----
|
||||
<1> Static factory method with a URI template.
|
||||
<2> Add or replace URI components.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
[[webflux-cors]]
|
||||
= CORS
|
||||
:doc-spring-security: {doc-root}/spring-security/reference
|
||||
[.small]#<<web.adoc#mvc-cors, Web MVC>>#
|
||||
|
||||
Spring WebFlux lets you handle CORS (Cross-Origin Resource Sharing). This section
|
||||
@@ -84,6 +83,7 @@ The {api-spring-framework}/web/bind/annotation/CrossOrigin.html[`@CrossOrigin`]
|
||||
annotation enables cross-origin requests on annotated controller methods, as the
|
||||
following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -122,6 +122,7 @@ following example shows:
|
||||
}
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
By default, `@CrossOrigin` allows:
|
||||
|
||||
@@ -140,6 +141,7 @@ the `allowOriginPatterns` property may be used to match to a dynamic set of orig
|
||||
`@CrossOrigin` is supported at the class level, too, and inherited by all methods.
|
||||
The following example specifies a certain domain and sets `maxAge` to an hour:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -178,10 +180,12 @@ The following example specifies a certain domain and sets `maxAge` to an hour:
|
||||
}
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
You can use `@CrossOrigin` at both the class and the method level,
|
||||
as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -227,6 +231,7 @@ as the following example shows:
|
||||
----
|
||||
<1> Using `@CrossOrigin` at the class level.
|
||||
<2> Using `@CrossOrigin` at the method level.
|
||||
--
|
||||
|
||||
|
||||
|
||||
@@ -310,7 +315,7 @@ You can apply CORS support through the built-in
|
||||
good fit with <<webflux-fn, functional endpoints>>.
|
||||
|
||||
NOTE: If you try to use the `CorsFilter` with Spring Security, keep in mind that Spring
|
||||
Security has {doc-spring-security}/servlet/integrations/cors.html[built-in support] for
|
||||
Security has {docs-spring-security}/servlet/integrations/cors.html[built-in support] for
|
||||
CORS.
|
||||
|
||||
To configure the filter, you can declare a `CorsWebFilter` bean and pass a
|
||||
|
||||
@@ -98,7 +98,7 @@ as the following example shows:
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> Create router using Coroutines router DSL, a Reactive alternative is also available via `router { }`.
|
||||
<1> Create router using Coroutines router DSL; a Reactive alternative is also available via `router { }`.
|
||||
|
||||
One way to run a `RouterFunction` is to turn it into an `HttpHandler` and install it
|
||||
through one of the built-in <<web-reactive.adoc#webflux-httphandler, server adapters>>:
|
||||
@@ -300,7 +300,6 @@ ServerResponse.created(location).build()
|
||||
Depending on the codec used, it is possible to pass hint parameters to customize how the
|
||||
body is serialized or deserialized. For example, to specify a https://www.baeldung.com/jackson-json-view-annotation[Jackson JSON view]:
|
||||
|
||||
====
|
||||
[source,java,role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -311,7 +310,6 @@ ServerResponse.ok().hint(Jackson2CodecSupport.JSON_VIEW_HINT, MyJacksonView.clas
|
||||
----
|
||||
ServerResponse.ok().hint(Jackson2CodecSupport.JSON_VIEW_HINT, MyJacksonView::class.java).body(...)
|
||||
----
|
||||
====
|
||||
|
||||
|
||||
[[webflux-fn-handler-classes]]
|
||||
@@ -319,6 +317,7 @@ ServerResponse.ok().hint(Jackson2CodecSupport.JSON_VIEW_HINT, MyJacksonView::cla
|
||||
|
||||
We can write a handler function as a lambda, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -330,6 +329,7 @@ HandlerFunction<ServerResponse> helloWorld =
|
||||
----
|
||||
val helloWorld = HandlerFunction<ServerResponse> { ServerResponse.ok().bodyValue("Hello World") }
|
||||
----
|
||||
--
|
||||
|
||||
That is convenient, but in an application we need multiple functions, and multiple inline
|
||||
lambda's can get messy.
|
||||
@@ -337,6 +337,7 @@ Therefore, it is useful to group related handler functions together into a handl
|
||||
has a similar role as `@Controller` in an annotation-based application.
|
||||
For example, the following class exposes a reactive `Person` repository:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -411,6 +412,7 @@ Note that `PersonRepository.savePerson(Person)` is a suspending function with no
|
||||
<3> `getPerson` is a handler function that returns a single person, identified by the `id` path
|
||||
variable. We retrieve that `Person` from the repository and create a JSON response, if it is
|
||||
found. If it is not found, we return a 404 Not Found response.
|
||||
--
|
||||
|
||||
|
||||
[[webflux-fn-handler-validation]]
|
||||
@@ -525,8 +527,8 @@ header:
|
||||
----
|
||||
val route = coRouter {
|
||||
GET("/hello-world", accept(TEXT_PLAIN)) {
|
||||
ServerResponse.ok().bodyValueAndAwait("Hello World")
|
||||
}
|
||||
ServerResponse.ok().bodyValueAndAwait("Hello World")
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
@@ -642,7 +644,7 @@ RouterFunction<ServerResponse> route = route()
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
.Kotlin
|
||||
----
|
||||
val route = coRouter {
|
||||
val route = coRouter { // <1>
|
||||
"/person".nest {
|
||||
GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)
|
||||
GET(accept(APPLICATION_JSON), handler::listPeople)
|
||||
@@ -650,6 +652,7 @@ RouterFunction<ServerResponse> route = route()
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> Create router using Coroutines router DSL; a Reactive alternative is also available via `router { }`.
|
||||
|
||||
Though path-based nesting is the most common, you can nest on any kind of predicate by using
|
||||
the `nest` method on the builder.
|
||||
|
||||
@@ -156,6 +156,7 @@ application deployed as a WAR), you can declare a Spring-managed bean of type
|
||||
Netty global resources are shut down when the Spring `ApplicationContext` is closed,
|
||||
as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -170,11 +171,13 @@ as the following example shows:
|
||||
@Bean
|
||||
fun reactorResourceFactory() = ReactorResourceFactory()
|
||||
----
|
||||
--
|
||||
|
||||
You can also choose not to participate in the global Reactor Netty resources. However,
|
||||
in this mode, the burden is on you to ensure that all Reactor Netty client and server
|
||||
instances use shared resources, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -225,6 +228,7 @@ instances use shared resources, as the following example shows:
|
||||
<1> Create resources independent of global ones.
|
||||
<2> Use the `ReactorClientHttpConnector` constructor with resource factory.
|
||||
<3> Plug the connector into the `WebClient.Builder`.
|
||||
--
|
||||
|
||||
|
||||
[[webflux-client-builder-reactor-timeout]]
|
||||
@@ -253,7 +257,7 @@ To configure a connection timeout:
|
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
|
||||
|
||||
val webClient = WebClient.builder()
|
||||
.clientConnector(new ReactorClientHttpConnector(httpClient))
|
||||
.clientConnector(ReactorClientHttpConnector(httpClient))
|
||||
.build();
|
||||
----
|
||||
|
||||
@@ -281,8 +285,8 @@ To configure a read or write timeout:
|
||||
|
||||
val httpClient = HttpClient.create()
|
||||
.doOnConnected { conn -> conn
|
||||
.addHandlerLast(new ReadTimeoutHandler(10))
|
||||
.addHandlerLast(new WriteTimeoutHandler(10))
|
||||
.addHandlerLast(ReadTimeoutHandler(10))
|
||||
.addHandlerLast(WriteTimeoutHandler(10))
|
||||
}
|
||||
|
||||
// Create WebClient...
|
||||
@@ -375,6 +379,7 @@ The following example shows how to customize the JDK `HttpClient`:
|
||||
|
||||
The following example shows how to customize Jetty `HttpClient` settings:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -392,9 +397,10 @@ The following example shows how to customize Jetty `HttpClient` settings:
|
||||
httpClient.cookieStore = ...
|
||||
|
||||
val webClient = WebClient.builder()
|
||||
.clientConnector(new JettyClientHttpConnector(httpClient))
|
||||
.clientConnector(JettyClientHttpConnector(httpClient))
|
||||
.build();
|
||||
----
|
||||
--
|
||||
|
||||
By default, `HttpClient` creates its own resources (`Executor`, `ByteBufferPool`, `Scheduler`),
|
||||
which remain active until the process exits or `stop()` is called.
|
||||
@@ -404,6 +410,7 @@ ensure that the resources are shut down when the Spring `ApplicationContext` is
|
||||
declaring a Spring-managed bean of type `JettyResourceFactory`, as the following example
|
||||
shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -446,6 +453,7 @@ shows:
|
||||
----
|
||||
<1> Use the `JettyClientHttpConnector` constructor with resource factory.
|
||||
<2> Plug the connector into the `WebClient.Builder`.
|
||||
--
|
||||
|
||||
|
||||
|
||||
@@ -788,8 +796,8 @@ multipart request. The following example shows how to create a `MultiValueMap<St
|
||||
----
|
||||
val builder = MultipartBodyBuilder().apply {
|
||||
part("fieldPart", "fieldValue")
|
||||
part("filePart1", new FileSystemResource("...logo.png"))
|
||||
part("jsonPart", new Person("Jason"))
|
||||
part("filePart1", FileSystemResource("...logo.png"))
|
||||
part("jsonPart", Person("Jason"))
|
||||
part("myPart", part) // Part from a server request
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
[[webflux]]
|
||||
:chapter: webflux
|
||||
= Spring WebFlux
|
||||
:doc-spring-security: {doc-root}/spring-security/reference
|
||||
|
||||
The original web framework included in the Spring Framework, Spring Web MVC, was
|
||||
purpose-built for the Servlet API and Servlet containers. The reactive-stack web framework,
|
||||
@@ -388,14 +387,14 @@ The code snippets below show using the `HttpHandler` adapters with each server A
|
||||
----
|
||||
HttpHandler handler = ...
|
||||
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
|
||||
HttpServer.create().host(host).port(port).handle(adapter).bind().block();
|
||||
HttpServer.create().host(host).port(port).handle(adapter).bindNow();
|
||||
----
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
.Kotlin
|
||||
----
|
||||
val handler: HttpHandler = ...
|
||||
val adapter = ReactorHttpHandlerAdapter(handler)
|
||||
HttpServer.create().host(host).port(port).handle(adapter).bind().block()
|
||||
HttpServer.create().host(host).port(port).handle(adapter).bindNow()
|
||||
----
|
||||
|
||||
*Undertow*
|
||||
@@ -1475,6 +1474,7 @@ You can map requests by using glob patterns and wildcards:
|
||||
|
||||
Captured URI variables can be accessed with `@PathVariable`, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -1491,9 +1491,11 @@ Captured URI variables can be accessed with `@PathVariable`, as the following ex
|
||||
// ...
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
You can declare URI variables at the class and method levels, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -1525,6 +1527,7 @@ You can declare URI variables at the class and method levels, as the following e
|
||||
----
|
||||
<1> Class-level URI mapping.
|
||||
<2> Method-level URI mapping.
|
||||
--
|
||||
|
||||
|
||||
URI variables are automatically converted to the appropriate type or a `TypeMismatchException`
|
||||
@@ -1533,8 +1536,8 @@ register support for any other data type.
|
||||
See <<webflux-ann-typeconversion>> and <<webflux-ann-initbinder>>.
|
||||
|
||||
URI variables can be named explicitly (for example, `@PathVariable("customId")`), but you can
|
||||
leave that detail out if the names are the same and you compile your code with debugging
|
||||
information or with the `-parameters` compiler flag on Java 8.
|
||||
leave that detail out if the names are the same and you compile your code with the `-parameters`
|
||||
compiler flag.
|
||||
|
||||
The syntax `{*varName}` declares a URI variable that matches zero or more remaining path
|
||||
segments. For example `/resources/{*path}` matches all files under `/resources/`, and the
|
||||
@@ -1544,6 +1547,7 @@ The syntax `{varName:regex}` declares a URI variable with a regular expression t
|
||||
syntax: `{varName:regex}`. For example, given a URL of `/spring-web-3.0.5.jar`, the following method
|
||||
extracts the name, version, and file extension:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -1560,6 +1564,7 @@ extracts the name, version, and file extension:
|
||||
// ...
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
URI path patterns can also have embedded `${...}` placeholders that are resolved on startup
|
||||
through `PropertySourcesPlaceholderConfigurer` against local, system, environment, and
|
||||
@@ -2005,7 +2010,7 @@ generally supported for all return values.
|
||||
value) is considered to have fully handled the response if it also has a `ServerHttpResponse`,
|
||||
a `ServerWebExchange` argument, or an `@ResponseStatus` annotation. The same is also true
|
||||
if the controller has made a positive ETag or `lastModified` timestamp check.
|
||||
// TODO: See <<webflux-caching-etag-lastmodified>> for details.
|
||||
See <<webflux-caching-etag-lastmodified>> for details.
|
||||
|
||||
If none of the above is true, a `void` return type can also indicate "`no response body`" for
|
||||
REST controllers or default view name selection for HTML controllers.
|
||||
@@ -2661,6 +2666,7 @@ content. The best way to handle a file upload form (for example, from a browser)
|
||||
is through data binding to a <<webflux-ann-modelattrib-method-args, command object>>,
|
||||
as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -2701,6 +2707,7 @@ as the following example shows:
|
||||
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
You can also submit multipart requests from non-browser clients in a RESTful service
|
||||
scenario. The following example uses a file along with JSON:
|
||||
@@ -2727,6 +2734,7 @@ Content-Transfer-Encoding: 8bit
|
||||
|
||||
You can access individual parts with `@RequestPart`, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -2750,11 +2758,13 @@ You can access individual parts with `@RequestPart`, as the following example sh
|
||||
----
|
||||
<1> Using `@RequestPart` to get the metadata.
|
||||
<2> Using `@RequestPart` to get the file.
|
||||
--
|
||||
|
||||
|
||||
To deserialize the raw part content (for example, to JSON -- similar to `@RequestBody`),
|
||||
you can declare a concrete target `Object`, instead of `Part`, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -2774,6 +2784,7 @@ you can declare a concrete target `Object`, instead of `Part`, as the following
|
||||
}
|
||||
----
|
||||
<1> Using `@RequestPart` to get the metadata.
|
||||
--
|
||||
|
||||
You can use `@RequestPart` in combination with `jakarta.validation.Valid` or Spring's
|
||||
`@Validated` annotation, which causes Standard Bean Validation to be applied. Validation
|
||||
@@ -2782,6 +2793,7 @@ The exception contains a `BindingResult` with the error details and can also be
|
||||
in the controller method by declaring the argument with an async wrapper and then using
|
||||
error related operators:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -2799,10 +2811,12 @@ error related operators:
|
||||
// ...
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
To access all multipart data as a `MultiValueMap`, you can use `@RequestBody`,
|
||||
as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -2822,6 +2836,7 @@ as the following example shows:
|
||||
}
|
||||
----
|
||||
<1> Using `@RequestBody`.
|
||||
--
|
||||
|
||||
===== `PartEvent`
|
||||
|
||||
@@ -3348,6 +3363,7 @@ do, except for `@ModelAttribute` (command object) arguments. Typically, they are
|
||||
with a `WebDataBinder` argument, for registrations, and a `void` return value.
|
||||
The following example uses the `@InitBinder` annotation:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -3382,11 +3398,14 @@ The following example uses the `@InitBinder` annotation:
|
||||
// ...
|
||||
}
|
||||
----
|
||||
<1> Using the `@InitBinder` annotation.
|
||||
--
|
||||
|
||||
Alternatively, when using a `Formatter`-based setup through a shared
|
||||
`FormattingConversionService`, you could re-use the same approach and register
|
||||
controller-specific `Formatter` instances, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -3418,6 +3437,8 @@ controller-specific `Formatter` instances, as the following example shows:
|
||||
}
|
||||
----
|
||||
<1> Adding a custom formatter (a `DateFormatter`, in this case).
|
||||
--
|
||||
|
||||
|
||||
[[webflux-ann-initbinder-model-design]]
|
||||
==== Model Design
|
||||
@@ -3743,10 +3764,10 @@ The https://spring.io/projects/spring-security[Spring Security] project provides
|
||||
for protecting web applications from malicious exploits. See the Spring Security
|
||||
reference documentation, including:
|
||||
|
||||
* {doc-spring-security}/reactive/configuration/webflux.html[WebFlux Security]
|
||||
* {doc-spring-security}/reactive/test/index.html[WebFlux Testing Support]
|
||||
* {doc-spring-security}/features/exploits/csrf.html#csrf-protection[CSRF protection]
|
||||
* {doc-spring-security}/features/exploits/headers.html[Security Response Headers]
|
||||
* {docs-spring-security}/reactive/configuration/webflux.html[WebFlux Security]
|
||||
* {docs-spring-security}/reactive/test/index.html[WebFlux Testing Support]
|
||||
* {docs-spring-security}/features/exploits/csrf.html#csrf-protection[CSRF protection]
|
||||
* {docs-spring-security}/features/exploits/headers.html[Security Response Headers]
|
||||
|
||||
|
||||
|
||||
@@ -3824,6 +3845,7 @@ Controllers can add explicit support for HTTP caching. We recommend doing so, si
|
||||
against conditional request headers. A controller can add an `ETag` and `Cache-Control`
|
||||
settings to a `ResponseEntity`, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -3857,6 +3879,7 @@ settings to a `ResponseEntity`, as the following example shows:
|
||||
.body(book)
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
The preceding example sends a 304 (NOT_MODIFIED) response with an empty body if the comparison
|
||||
to the conditional request headers indicates the content has not changed. Otherwise, the
|
||||
@@ -3865,6 +3888,7 @@ to the conditional request headers indicates the content has not changed. Otherw
|
||||
You can also make the check against conditional request headers in the controller,
|
||||
as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -3904,6 +3928,7 @@ as the following example shows:
|
||||
<1> Application-specific calculation.
|
||||
<2> Response has been set to 304 (NOT_MODIFIED). No further processing.
|
||||
<3> Continue with request processing.
|
||||
--
|
||||
|
||||
There are three variants for checking conditional requests against `eTag` values, `lastModified`
|
||||
values, or both. For conditional `GET` and `HEAD` requests, you can set the response to
|
||||
@@ -4409,7 +4434,7 @@ In the next example, given a request that starts with `/resources`, the relative
|
||||
used to find and serve static resources relative to `/static` on the classpath. Resources
|
||||
are served with a one-year future expiration to ensure maximum use of the browser cache
|
||||
and a reduction in HTTP requests made by the browser. The `Last-Modified` header is also
|
||||
evaluated and, if present, a `304` status code is returned. The following list shows
|
||||
evaluated and, if present, a `304` status code is returned. The following listing shows
|
||||
the example:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
@@ -4443,7 +4468,7 @@ the example:
|
||||
}
|
||||
----
|
||||
|
||||
// TODO: See also <<webflux-caching-static-resources, HTTP caching support for static resources>>.
|
||||
See also <<webflux-caching-static-resources, HTTP caching support for static resources>>.
|
||||
|
||||
The resource handler also supports a chain of
|
||||
{api-spring-framework}/web/reactive/resource/ResourceResolver.html[`ResourceResolver`] implementations and
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
[[mvc-cors]]
|
||||
= CORS
|
||||
:doc-spring-security: {doc-root}/spring-security/reference
|
||||
[.small]#<<web-reactive.adoc#webflux-cors, WebFlux>>#
|
||||
|
||||
Spring MVC lets you handle CORS (Cross-Origin Resource Sharing). This section
|
||||
@@ -336,7 +335,7 @@ You can apply CORS support through the built-in
|
||||
{api-spring-framework}/web/filter/CorsFilter.html[`CorsFilter`].
|
||||
|
||||
NOTE: If you try to use the `CorsFilter` with Spring Security, keep in mind that Spring
|
||||
Security has {doc-spring-security}/servlet/integrations/cors.html[built-in support] for
|
||||
Security has {docs-spring-security}/servlet/integrations/cors.html[built-in support] for
|
||||
CORS.
|
||||
|
||||
To configure the filter, pass a `CorsConfigurationSource` to its constructor, as the
|
||||
|
||||
@@ -40,7 +40,7 @@ as the following example shows:
|
||||
PersonRepository repository = ...
|
||||
PersonHandler handler = new PersonHandler(repository);
|
||||
|
||||
RouterFunction<ServerResponse> route = route()
|
||||
RouterFunction<ServerResponse> route = route() // <1>
|
||||
.GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson)
|
||||
.GET("/person", accept(APPLICATION_JSON), handler::listPeople)
|
||||
.POST("/person", handler::createPerson)
|
||||
@@ -64,6 +64,7 @@ as the following example shows:
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> Create router using `route()`.
|
||||
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
.Kotlin
|
||||
@@ -289,6 +290,7 @@ allows you to send Strings, or other objects as JSON. For example:
|
||||
|
||||
We can write a handler function as a lambda, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -301,6 +303,7 @@ HandlerFunction<ServerResponse> helloWorld =
|
||||
val helloWorld: (ServerRequest) -> ServerResponse =
|
||||
{ ServerResponse.ok().body("Hello World") }
|
||||
----
|
||||
--
|
||||
|
||||
That is convenient, but in an application we need multiple functions, and multiple inline
|
||||
lambda's can get messy.
|
||||
@@ -308,6 +311,7 @@ Therefore, it is useful to group related handler functions together into a handl
|
||||
has a similar role as `@Controller` in an annotation-based application.
|
||||
For example, the following class exposes a reactive `Person` repository:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -383,6 +387,7 @@ JSON.
|
||||
<3> `getPerson` is a handler function that returns a single person, identified by the `id` path
|
||||
variable. We retrieve that `Person` from the repository and create a JSON response, if it is
|
||||
found. If it is not found, we return a 404 Not Found response.
|
||||
--
|
||||
|
||||
|
||||
[[webmvc-fn-handler-validation]]
|
||||
@@ -623,13 +628,14 @@ RouterFunction<ServerResponse> route = route()
|
||||
import org.springframework.web.servlet.function.router
|
||||
|
||||
val route = router {
|
||||
"/person".nest {
|
||||
"/person".nest { // <1>
|
||||
GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)
|
||||
GET(accept(APPLICATION_JSON), handler::listPeople)
|
||||
POST(handler::createPerson)
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> Using `nest` DSL.
|
||||
|
||||
Though path-based nesting is the most common, you can nest on any kind of predicate by using
|
||||
the `nest` method on the builder.
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
[[mvc]]
|
||||
:chapter: mvc
|
||||
= Spring Web MVC
|
||||
:doc-spring-security: {doc-root}/spring-security/reference
|
||||
|
||||
Spring Web MVC is the original web framework built on the Servlet API and has been included
|
||||
in the Spring Framework from the very beginning. The formal name, "`Spring Web MVC,`"
|
||||
in the Spring Framework from the very beginning. The formal name, "Spring Web MVC,"
|
||||
comes from the name of its source module
|
||||
({spring-framework-main-code}/spring-webmvc[`spring-webmvc`]),
|
||||
but it is more commonly known as "`Spring MVC`".
|
||||
but it is more commonly known as "Spring MVC".
|
||||
|
||||
Parallel to Spring Web MVC, Spring Framework 5.0 introduced a reactive-stack web framework
|
||||
whose name, "`Spring WebFlux,`" is also based on its source module
|
||||
whose name, "Spring WebFlux," is also based on its source module
|
||||
({spring-framework-main-code}/spring-webflux[`spring-webflux`]).
|
||||
This section covers Spring Web MVC. The <<web-reactive.adoc#spring-web-reactive, next section>>
|
||||
This chapter covers Spring Web MVC. The <<web-reactive.adoc#spring-web-reactive, next chapter>>
|
||||
covers Spring WebFlux.
|
||||
|
||||
For baseline information and compatibility with Servlet container and Jakarta EE version
|
||||
@@ -1142,9 +1141,10 @@ request with a simple request parameter.
|
||||
[.small]#<<web-reactive.adoc#webflux-multipart, WebFlux>>#
|
||||
|
||||
`MultipartResolver` from the `org.springframework.web.multipart` package is a strategy
|
||||
for parsing multipart requests including file uploads. There is one implementation
|
||||
based on https://commons.apache.org/proper/commons-fileupload[Commons FileUpload] and
|
||||
another based on Servlet multipart request parsing.
|
||||
for parsing multipart requests including file uploads. There is a container-based
|
||||
`StandardServletMultipartResolver` implementation for Servlet multipart request parsing.
|
||||
Note that the outdated `CommonsMultipartResolver` based on Apache Commons FileUpload is
|
||||
not available anymore, as of Spring Framework 6.0 with its new Servlet 5.0+ baseline.
|
||||
|
||||
To enable multipart handling, you need to declare a `MultipartResolver` bean in your
|
||||
`DispatcherServlet` Spring configuration with a name of `multipartResolver`.
|
||||
@@ -1154,26 +1154,6 @@ content wraps the current `HttpServletRequest` as a `MultipartHttpServletRequest
|
||||
provide access to resolved files in addition to exposing parts as request parameters.
|
||||
|
||||
|
||||
[[mvc-multipart-resolver-commons]]
|
||||
==== Apache Commons `FileUpload`
|
||||
|
||||
To use Apache Commons `FileUpload`, you can configure a bean of type
|
||||
`CommonsMultipartResolver` with a name of `multipartResolver`. You also need to have
|
||||
the `commons-fileupload` jar as a dependency on your classpath.
|
||||
|
||||
This resolver variant delegates to a local library within the application, providing
|
||||
maximum portability across Servlet containers. As an alternative, consider standard
|
||||
Servlet multipart resolution through the container's own parser as discussed below.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
Commons FileUpload traditionally applies to POST requests only but accepts any
|
||||
`multipart/` content type. See the
|
||||
{api-spring-framework}/web/multipart/commons/CommonsMultipartResolver.html[`CommonsMultipartResolver`]
|
||||
javadoc for details and configuration options.
|
||||
====
|
||||
|
||||
|
||||
[[mvc-multipart-resolver-standard]]
|
||||
==== Servlet Multipart Parsing
|
||||
|
||||
@@ -1700,8 +1680,8 @@ register support for any other data type.
|
||||
See <<mvc-ann-typeconversion>> and <<mvc-ann-initbinder>>.
|
||||
|
||||
You can explicitly name URI variables (for example, `@PathVariable("customId")`), but you can
|
||||
leave that detail out if the names are the same and your code is compiled with debugging
|
||||
information or with the `-parameters` compiler flag on Java 8.
|
||||
leave that detail out if the names are the same and your code is compiled with the `-parameters`
|
||||
compiler flag.
|
||||
|
||||
The syntax `{varName:regex}` declares a URI variable with a regular expression that has
|
||||
syntax of `{varName:regex}`. For example, given URL `"/spring-web-3.0.5.jar"`, the following method
|
||||
@@ -1938,6 +1918,7 @@ You can also use the same with request header conditions, as the following examp
|
||||
// ...
|
||||
}
|
||||
----
|
||||
<1> Testing whether `myHeader` equals `myValue`.
|
||||
|
||||
TIP: You can match `Content-Type` and `Accept` with the headers condition, but it is better to use
|
||||
<<mvc-ann-requestmapping-consumes, consumes>> and <<mvc-ann-requestmapping-produces, produces>>
|
||||
@@ -2661,19 +2642,21 @@ query parameters and form fields. The following example shows how to do so:
|
||||
.Java
|
||||
----
|
||||
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
|
||||
public String processSubmit(@ModelAttribute Pet pet) {
|
||||
public String processSubmit(@ModelAttribute Pet pet) { // <1>
|
||||
// method logic...
|
||||
}
|
||||
----
|
||||
<1> Bind an instance of `Pet`.
|
||||
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
.Kotlin
|
||||
----
|
||||
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
|
||||
fun processSubmit(@ModelAttribute pet: Pet): String {
|
||||
fun processSubmit(@ModelAttribute pet: Pet): String { // <1>
|
||||
// method logic...
|
||||
}
|
||||
----
|
||||
<1> Bind an instance of `Pet`.
|
||||
|
||||
The `Pet` instance above is sourced in one of the following ways:
|
||||
|
||||
@@ -2701,18 +2684,21 @@ could load the `Account` from a data store:
|
||||
.Java
|
||||
----
|
||||
@PutMapping("/accounts/{account}")
|
||||
public String save(@ModelAttribute("account") Account account) {
|
||||
public String save(@ModelAttribute("account") Account account) { // <1>
|
||||
// ...
|
||||
}
|
||||
----
|
||||
<1> Bind an instance of `Account` using an explicit attribute name.
|
||||
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
.Kotlin
|
||||
----
|
||||
@PutMapping("/accounts/{account}")
|
||||
fun save(@ModelAttribute("account") account: Account): String {
|
||||
fun save(@ModelAttribute("account") account: Account): String { // <1>
|
||||
// ...
|
||||
}
|
||||
----
|
||||
<1> Bind an instance of `Account` using an explicit attribute name.
|
||||
|
||||
After the model attribute instance is obtained, data binding is applied. The
|
||||
`WebDataBinder` class matches Servlet request parameter names (query parameters and form
|
||||
@@ -2826,6 +2812,7 @@ You can automatically apply validation after data binding by adding the
|
||||
// ...
|
||||
}
|
||||
----
|
||||
<1> Validate the `Pet` instance.
|
||||
|
||||
Note that using `@ModelAttribute` is optional (for example, to set its attributes).
|
||||
By default, any argument that is not a simple value type (as determined by
|
||||
@@ -2945,6 +2932,7 @@ as the following example shows:
|
||||
// ...
|
||||
}
|
||||
----
|
||||
<1> Using a `@SessionAttribute` annotation.
|
||||
|
||||
For use cases that require adding or removing session attributes, consider injecting
|
||||
`org.springframework.web.context.request.WebRequest` or
|
||||
@@ -3559,8 +3547,6 @@ to the model, as the following example shows:
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
.Kotlin
|
||||
----
|
||||
import org.springframework.ui.set
|
||||
|
||||
@Controller
|
||||
class UserController : AbstractController() {
|
||||
|
||||
@@ -4449,13 +4435,7 @@ as the following example shows:
|
||||
----
|
||||
@PostMapping
|
||||
public Callable<String> processUpload(final MultipartFile file) {
|
||||
|
||||
return new Callable<String>() {
|
||||
public String call() throws Exception {
|
||||
// ...
|
||||
return "someView";
|
||||
}
|
||||
};
|
||||
return () -> "someView";
|
||||
}
|
||||
----
|
||||
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
|
||||
@@ -4792,7 +4772,7 @@ are written to the Reactor `Context` as key-value pairs, using the key assigned
|
||||
For other asynchronous handling scenarios, you can use the Context Propagation library
|
||||
directly. For example:
|
||||
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
[source,java,indent=0,subs="verbatim,quotes"]
|
||||
.Java
|
||||
----
|
||||
// Capture ThreadLocal values from the main thread ...
|
||||
@@ -5073,10 +5053,10 @@ The https://spring.io/projects/spring-security[Spring Security] project provides
|
||||
for protecting web applications from malicious exploits. See the Spring Security
|
||||
reference documentation, including:
|
||||
|
||||
* {doc-spring-security}/servlet/integrations/mvc.html[Spring MVC Security]
|
||||
* {doc-spring-security}/servlet/test/mockmvc/setup.html[Spring MVC Test Support]
|
||||
* {doc-spring-security}/features/exploits/csrf.html#csrf-protection[CSRF protection]
|
||||
* {doc-spring-security}/features/exploits/headers.html[Security Response Headers]
|
||||
* {docs-spring-security}/servlet/integrations/mvc.html[Spring MVC Security]
|
||||
* {docs-spring-security}/servlet/test/mockmvc/setup.html[Spring MVC Test Support]
|
||||
* {docs-spring-security}/features/exploits/csrf.html#csrf-protection[CSRF protection]
|
||||
* {docs-spring-security}/features/exploits/headers.html[Security Response Headers]
|
||||
|
||||
https://hdiv.org/[HDIV] is another web security framework that integrates with Spring MVC.
|
||||
|
||||
@@ -5164,6 +5144,7 @@ Controllers can add explicit support for HTTP caching. We recommended doing so,
|
||||
against conditional request headers. A controller can add an `ETag` header and `Cache-Control`
|
||||
settings to a `ResponseEntity`, as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5196,6 +5177,7 @@ settings to a `ResponseEntity`, as the following example shows:
|
||||
.body(book)
|
||||
}
|
||||
----
|
||||
--
|
||||
|
||||
The preceding example sends a 304 (NOT_MODIFIED) response with an empty body if the comparison
|
||||
to the conditional request headers indicates that the content has not changed. Otherwise, the
|
||||
@@ -5204,6 +5186,7 @@ to the conditional request headers indicates that the content has not changed. O
|
||||
You can also make the check against conditional request headers in the controller,
|
||||
as the following example shows:
|
||||
|
||||
--
|
||||
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
|
||||
.Java
|
||||
----
|
||||
@@ -5243,6 +5226,7 @@ as the following example shows:
|
||||
<1> Application-specific calculation.
|
||||
<2> The response has been set to 304 (NOT_MODIFIED) -- no further processing.
|
||||
<3> Continue with the request processing.
|
||||
--
|
||||
|
||||
|
||||
There are three variants for checking conditional requests against `eTag` values, `lastModified`
|
||||
@@ -5914,7 +5898,6 @@ The MVC namespace provides dedicated elements. The following example works with
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,quotes"]
|
||||
----
|
||||
|
||||
<mvc:view-resolvers>
|
||||
<mvc:content-negotiation>
|
||||
<mvc:default-views>
|
||||
@@ -5927,7 +5910,6 @@ The MVC namespace provides dedicated elements. The following example works with
|
||||
<mvc:freemarker-configurer>
|
||||
<mvc:template-loader-path location="/freemarker"/>
|
||||
</mvc:freemarker-configurer>
|
||||
|
||||
----
|
||||
|
||||
In Java configuration, you can add the respective `Configurer` bean,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
[[{chapter}.websocket-intro]]
|
||||
[id={chapter}.websocket-intro]
|
||||
= Introduction to WebSocket
|
||||
|
||||
The WebSocket protocol, https://tools.ietf.org/html/rfc6455[RFC 6455], provides a standardized
|
||||
@@ -54,7 +54,7 @@ instructions of the cloud provider related to WebSocket support.
|
||||
|
||||
|
||||
|
||||
[[{chapter}.websocket-intro-architecture]]
|
||||
[id={chapter}.websocket-intro-architecture]
|
||||
== HTTP Versus WebSocket
|
||||
|
||||
Even though WebSocket is designed to be HTTP-compatible and starts with an HTTP request,
|
||||
@@ -80,7 +80,7 @@ In the absence of that, they need to come up with their own conventions.
|
||||
|
||||
|
||||
|
||||
[[{chapter}.websocket-intro-when-to-use]]
|
||||
[id={chapter}.websocket-intro-when-to-use]
|
||||
== When to Use WebSockets
|
||||
|
||||
WebSockets can make a web page be dynamic and interactive. However, in many cases,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
[[websocket]]
|
||||
= WebSockets
|
||||
:doc-spring-security: {doc-root}/spring-security/reference
|
||||
[.small]#<<web-reactive.adoc#webflux-websocket, WebFlux>>#
|
||||
|
||||
This part of the reference documentation covers support for Servlet stack, WebSocket
|
||||
@@ -185,7 +184,7 @@ HTTP requests. It is also easy to integrate into other HTTP processing scenarios
|
||||
by invoking `WebSocketHttpRequestHandler`. This is convenient and easy to
|
||||
understand. However, special considerations apply with regards to JSR-356 runtimes.
|
||||
|
||||
The Java WebSocket API (JSR-356) provides two deployment mechanisms. The first
|
||||
The Jakarta WebSocket API (JSR-356) provides two deployment mechanisms. The first
|
||||
involves a Servlet container classpath scan (a Servlet 3 feature) at startup.
|
||||
The other is a registration API to use at Servlet container initialization.
|
||||
Neither of these mechanism makes it possible to use a single "`front controller`"
|
||||
@@ -194,17 +193,9 @@ requests -- such as Spring MVC's `DispatcherServlet`.
|
||||
|
||||
This is a significant limitation of JSR-356 that Spring's WebSocket support addresses with
|
||||
server-specific `RequestUpgradeStrategy` implementations even when running in a JSR-356 runtime.
|
||||
Such strategies currently exist for Tomcat, Jetty, GlassFish, WebLogic, WebSphere, and
|
||||
Undertow (and WildFly).
|
||||
|
||||
|
||||
|
||||
NOTE: A request to overcome the preceding limitation in the Java WebSocket API has been
|
||||
created and can be followed at
|
||||
https://github.com/eclipse-ee4j/websocket-api/issues/211[eclipse-ee4j/websocket-api#211].
|
||||
Tomcat, Undertow, and WebSphere provide their own API alternatives that
|
||||
make it possible to do this, and it is also possible with Jetty. We are hopeful
|
||||
that more servers will do the same.
|
||||
Such strategies currently exist for Tomcat, Jetty, GlassFish, WebLogic, WebSphere, and Undertow
|
||||
(and WildFly). As of Jakarta WebSocket 2.1, a standard request upgrade strategy is available
|
||||
which Spring chooses on Jakarta EE 10 based web containers such as Tomcat 10.1 and Jetty 12.
|
||||
|
||||
A secondary consideration is that Servlet containers with JSR-356 support are expected
|
||||
to perform a `ServletContainerInitializer` (SCI) scan that can slow down application
|
||||
@@ -627,7 +618,7 @@ response. By default, the Spring Security Java configuration sets it to `DENY`.
|
||||
In 3.2, the Spring Security XML namespace does not set that header by default
|
||||
but can be configured to do so. In the future, it may set it by default.
|
||||
|
||||
See {doc-spring-security}/features/exploits/headers.html#headers-default[Default Security Headers]
|
||||
See {docs-spring-security}/features/exploits/headers.html#headers-default[Default Security Headers]
|
||||
of the Spring Security documentation for details on how to configure the
|
||||
setting of the `X-Frame-Options` header. You can also see
|
||||
https://github.com/spring-projects/spring-security/issues/2718[gh-2718]
|
||||
@@ -971,7 +962,7 @@ endpoints, over WebSocket with <<websocket-fallback>>, as the following example
|
||||
|
||||
@Override
|
||||
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||
registry.addEndpoint("/portfolio").withSockJS(); // <1>
|
||||
registry.addEndpoint("/portfolio").withSockJS(); // <1>
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1811,7 +1802,7 @@ its own implementation of `WebSocketMessageBrokerConfigurer` that is marked with
|
||||
=== Authorization
|
||||
|
||||
Spring Security provides
|
||||
{doc-spring-security}/servlet/integrations/websocket.html#websocket-authorization[WebSocket sub-protocol authorization]
|
||||
{docs-spring-security}/servlet/integrations/websocket.html#websocket-authorization[WebSocket sub-protocol authorization]
|
||||
that uses a `ChannelInterceptor` to authorize messages based on the user header in them.
|
||||
Also, Spring Session provides
|
||||
https://docs.spring.io/spring-session/reference/web-socket.html[WebSocket integration]
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.docs.core.aot.hints.importruntimehints;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.springframework.aot.hint.RuntimeHints;
|
||||
import org.springframework.aot.hint.RuntimeHintsRegistrar;
|
||||
import org.springframework.context.annotation.ImportRuntimeHints;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@ImportRuntimeHints(SpellCheckService.SpellCheckServiceRuntimeHints.class)
|
||||
public class SpellCheckService {
|
||||
|
||||
public void loadDictionary(Locale locale) {
|
||||
ClassPathResource resource = new ClassPathResource("dicts/" + locale.getLanguage() + ".txt");
|
||||
//...
|
||||
}
|
||||
|
||||
static class SpellCheckServiceRuntimeHints implements RuntimeHintsRegistrar {
|
||||
|
||||
@Override
|
||||
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
||||
hints.resources().registerPattern("dicts/*");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.docs.core.aot.hints.testing;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
public class SampleReflection {
|
||||
|
||||
private final Log logger = LogFactory.getLog(SampleReflection.class);
|
||||
|
||||
public void performReflection() {
|
||||
try {
|
||||
Class<?> springVersion = ClassUtils.forName("org.springframework.core.SpringVersion", null);
|
||||
Method getVersion = ClassUtils.getMethod(springVersion, "getVersion");
|
||||
String version = (String) getVersion.invoke(null);
|
||||
logger.info("Spring version:" + version);
|
||||
}
|
||||
catch (Exception exc) {
|
||||
logger.error("reflection failed", exc);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.docs.core.aot.hints.testing;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.aot.hint.ExecutableMode;
|
||||
import org.springframework.aot.hint.RuntimeHints;
|
||||
import org.springframework.aot.test.agent.EnabledIfRuntimeHintsAgent;
|
||||
import org.springframework.aot.test.agent.RuntimeHintsInvocations;
|
||||
import org.springframework.aot.test.agent.RuntimeHintsRecorder;
|
||||
import org.springframework.core.SpringVersion;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
// @EnabledIfRuntimeHintsAgent signals that the annotated test class or test
|
||||
// method is only enabled if the RuntimeHintsAgent is loaded on the current JVM.
|
||||
// It also tags tests with the "RuntimeHints" JUnit tag.
|
||||
@EnabledIfRuntimeHintsAgent
|
||||
class SampleReflectionRuntimeHintsTests {
|
||||
|
||||
@Test
|
||||
void shouldRegisterReflectionHints() {
|
||||
RuntimeHints runtimeHints = new RuntimeHints();
|
||||
// Call a RuntimeHintsRegistrar that contributes hints like:
|
||||
runtimeHints.reflection().registerType(SpringVersion.class, typeHint ->
|
||||
typeHint.withMethod("getVersion", List.of(), ExecutableMode.INVOKE));
|
||||
|
||||
// Invoke the relevant piece of code we want to test within a recording lambda
|
||||
RuntimeHintsInvocations invocations = RuntimeHintsRecorder.record(() -> {
|
||||
SampleReflection sample = new SampleReflection();
|
||||
sample.performReflection();
|
||||
});
|
||||
// assert that the recorded invocations are covered by the contributed hints
|
||||
assertThat(invocations).match(runtimeHints);
|
||||
}
|
||||
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.docs.core.aot.hints.testing;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.aot.hint.RuntimeHints;
|
||||
import org.springframework.aot.hint.RuntimeHintsRegistrar;
|
||||
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class SpellCheckServiceTests {
|
||||
|
||||
// tag::hintspredicates[]
|
||||
@Test
|
||||
void shouldRegisterResourceHints() {
|
||||
RuntimeHints hints = new RuntimeHints();
|
||||
new SpellCheckServiceRuntimeHints().registerHints(hints, getClass().getClassLoader());
|
||||
assertThat(RuntimeHintsPredicates.resource().forResource("dicts/en.txt"))
|
||||
.accepts(hints);
|
||||
}
|
||||
// end::hintspredicates[]
|
||||
|
||||
// Copied here because it is package private in SpellCheckService
|
||||
static class SpellCheckServiceRuntimeHints implements RuntimeHintsRegistrar {
|
||||
|
||||
@Override
|
||||
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
||||
hints.resources().registerPattern("dicts/*");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.docs.core.aot.refresh;
|
||||
|
||||
import org.springframework.aot.hint.RuntimeHints;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
public class AotProcessingSample {
|
||||
|
||||
public void createAotContext() {
|
||||
// tag::aotcontext[]
|
||||
RuntimeHints hints = new RuntimeHints();
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
context.register(MyApplication.class);
|
||||
context.refreshForAotProcessing(hints);
|
||||
// end::aotcontext[]
|
||||
}
|
||||
|
||||
// tag::myapplication[]
|
||||
@Configuration(proxyBeanMethods=false)
|
||||
@ComponentScan
|
||||
@Import({DataSourceConfiguration.class, ContainerConfiguration.class})
|
||||
public class MyApplication {
|
||||
}
|
||||
// end::myapplication[]
|
||||
|
||||
class DataSourceConfiguration {
|
||||
}
|
||||
|
||||
class ContainerConfiguration {
|
||||
}
|
||||
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.docs.integration.observability.config.conventions;
|
||||
|
||||
import io.micrometer.common.KeyValue;
|
||||
import io.micrometer.common.KeyValues;
|
||||
|
||||
import org.springframework.http.server.observation.ServerHttpObservationDocumentation;
|
||||
import org.springframework.http.server.observation.ServerRequestObservationContext;
|
||||
import org.springframework.http.server.observation.ServerRequestObservationConvention;
|
||||
|
||||
public class CustomServerRequestObservationConvention implements ServerRequestObservationConvention {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
// will be used as the metric name
|
||||
return "http.server.requests";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContextualName(ServerRequestObservationContext context) {
|
||||
// will be used for the trace name
|
||||
return "http " + context.getCarrier().getMethod().toLowerCase();
|
||||
}
|
||||
|
||||
@Override
|
||||
public KeyValues getLowCardinalityKeyValues(ServerRequestObservationContext context) {
|
||||
return KeyValues.of(method(context), status(context), exception(context));
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public KeyValues getHighCardinalityKeyValues(ServerRequestObservationContext context) {
|
||||
return KeyValues.of(httpUrl(context));
|
||||
}
|
||||
|
||||
private KeyValue method(ServerRequestObservationContext context) {
|
||||
// You should reuse as much as possible the corresponding ObservationDocumentation for key names
|
||||
return KeyValue.of(ServerHttpObservationDocumentation.LowCardinalityKeyNames.METHOD, context.getCarrier().getMethod());
|
||||
}
|
||||
|
||||
// @fold:on // status(), exception(), httpUrl()...
|
||||
private KeyValue status(ServerRequestObservationContext context) {
|
||||
return KeyValue.of(ServerHttpObservationDocumentation.LowCardinalityKeyNames.STATUS, String.valueOf(context.getResponse().getStatus()));
|
||||
}
|
||||
|
||||
private KeyValue exception(ServerRequestObservationContext context) {
|
||||
String exception = (context.getError() != null) ? context.getError().getClass().getSimpleName() : KeyValue.NONE_VALUE;
|
||||
return KeyValue.of(ServerHttpObservationDocumentation.LowCardinalityKeyNames.EXCEPTION, exception);
|
||||
}
|
||||
|
||||
private KeyValue httpUrl(ServerRequestObservationContext context) {
|
||||
return KeyValue.of(ServerHttpObservationDocumentation.HighCardinalityKeyNames.HTTP_URL, context.getCarrier().getRequestURI());
|
||||
}
|
||||
// @fold:off
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.docs.integration.observability.config.conventions;
|
||||
|
||||
import io.micrometer.common.KeyValue;
|
||||
import io.micrometer.common.KeyValues;
|
||||
|
||||
import org.springframework.http.server.observation.DefaultServerRequestObservationConvention;
|
||||
import org.springframework.http.server.observation.ServerRequestObservationContext;
|
||||
|
||||
public class ExtendedServerRequestObservationConvention extends DefaultServerRequestObservationConvention {
|
||||
|
||||
@Override
|
||||
public KeyValues getLowCardinalityKeyValues(ServerRequestObservationContext context) {
|
||||
// here, we just want to have an additional KeyValue to the observation, keeping the default values
|
||||
return super.getLowCardinalityKeyValues(context).and(custom(context));
|
||||
}
|
||||
|
||||
private KeyValue custom(ServerRequestObservationContext context) {
|
||||
return KeyValue.of("custom.method", context.getCarrier().getMethod());
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.docs.integration.observability.config.conventions;
|
||||
|
||||
|
||||
import io.micrometer.common.KeyValue;
|
||||
import io.micrometer.observation.Observation;
|
||||
import io.micrometer.observation.ObservationFilter;
|
||||
|
||||
import org.springframework.http.server.observation.ServerRequestObservationContext;
|
||||
|
||||
public class ServerRequestObservationFilter implements ObservationFilter {
|
||||
|
||||
@Override
|
||||
public Observation.Context map(Observation.Context context) {
|
||||
if (context instanceof ServerRequestObservationContext serverContext) {
|
||||
context.setName("custom.observation.name");
|
||||
context.addLowCardinalityKeyValue(KeyValue.of("project", "spring"));
|
||||
String customAttribute = (String) serverContext.getCarrier().getAttribute("customAttribute");
|
||||
context.addLowCardinalityKeyValue(KeyValue.of("custom.attribute", customAttribute));
|
||||
}
|
||||
return context;
|
||||
}
|
||||
}
|
||||
@@ -7,29 +7,29 @@ javaPlatform {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api(platform("com.fasterxml.jackson:jackson-bom:2.14.0"))
|
||||
api(platform("io.micrometer:micrometer-bom:1.10.0"))
|
||||
api(platform("com.fasterxml.jackson:jackson-bom:2.14.1"))
|
||||
api(platform("io.micrometer:micrometer-bom:1.10.2"))
|
||||
api(platform("io.netty:netty-bom:4.1.85.Final"))
|
||||
api(platform("io.netty:netty5-bom:5.0.0.Alpha5"))
|
||||
api(platform("io.projectreactor:reactor-bom:2022.0.0"))
|
||||
api(platform("io.projectreactor:reactor-bom:2022.0.1"))
|
||||
api(platform("io.rsocket:rsocket-bom:1.1.3"))
|
||||
api(platform("org.apache.groovy:groovy-bom:4.0.5"))
|
||||
api(platform("org.apache.groovy:groovy-bom:4.0.6"))
|
||||
api(platform("org.apache.logging.log4j:log4j-bom:2.19.0"))
|
||||
api(platform("org.eclipse.jetty:jetty-bom:11.0.12"))
|
||||
api(platform("org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.6.4"))
|
||||
api(platform("org.jetbrains.kotlinx:kotlinx-serialization-bom:1.4.0"))
|
||||
api(platform("org.junit:junit-bom:5.9.1"))
|
||||
api(platform("org.mockito:mockito-bom:4.8.1"))
|
||||
api(platform("org.mockito:mockito-bom:4.9.0"))
|
||||
|
||||
constraints {
|
||||
api("com.fasterxml.woodstox:woodstox-core:6.4.0")
|
||||
api("com.fasterxml:aalto-xml:1.3.1")
|
||||
api("com.github.ben-manes.caffeine:caffeine:3.1.1")
|
||||
api("com.fasterxml.woodstox:woodstox-core:6.4.0")
|
||||
api("com.github.ben-manes.caffeine:caffeine:3.1.2")
|
||||
api("com.github.librepdf:openpdf:1.3.30")
|
||||
api("com.google.code.findbugs:findbugs:3.0.1")
|
||||
api("com.google.code.findbugs:jsr305:3.0.2")
|
||||
api("com.google.code.gson:gson:2.9.1")
|
||||
api("com.google.protobuf:protobuf-java-util:3.21.5")
|
||||
api("com.google.code.gson:gson:2.10")
|
||||
api("com.google.protobuf:protobuf-java-util:3.21.11")
|
||||
api("com.googlecode.protobuf-java-format:protobuf-java-format:1.4")
|
||||
api("com.h2database:h2:2.1.214")
|
||||
api("com.jayway.jsonpath:json-path:2.7.0")
|
||||
@@ -45,7 +45,7 @@ dependencies {
|
||||
api("com.thoughtworks.xstream:xstream:1.4.19")
|
||||
api("commons-io:commons-io:2.11.0")
|
||||
api("de.bechte.junit:junit-hierarchicalcontextrunner:4.12.1")
|
||||
api("info.picocli:picocli:4.6.3")
|
||||
api("info.picocli:picocli:4.7.0")
|
||||
api("io.micrometer:context-propagation:1.0.0")
|
||||
api("io.mockk:mockk:1.12.1")
|
||||
api("io.projectreactor.netty:reactor-netty5-http:2.0.0-M3")
|
||||
@@ -87,7 +87,7 @@ dependencies {
|
||||
api("jaxen:jaxen:1.2.0")
|
||||
api("junit:junit:4.13.2")
|
||||
api("net.sf.jopt-simple:jopt-simple:5.0.4")
|
||||
api("net.sourceforge.htmlunit:htmlunit:2.66.0")
|
||||
api("net.sourceforge.htmlunit:htmlunit:2.67.0")
|
||||
api("org.apache-extras.beanshell:bsh:2.0b6")
|
||||
api("org.apache.activemq:activemq-broker:5.16.2")
|
||||
api("org.apache.activemq:activemq-kahadb-store:5.16.2")
|
||||
@@ -96,9 +96,9 @@ dependencies {
|
||||
api("org.apache.derby:derby:10.16.1.1")
|
||||
api("org.apache.derby:derbyclient:10.16.1.1")
|
||||
api("org.apache.derby:derbytools:10.16.1.1")
|
||||
api("org.apache.httpcomponents.client5:httpclient5:5.1.3")
|
||||
api("org.apache.httpcomponents.core5:httpcore5-reactive:5.1.3")
|
||||
api("org.apache.poi:poi-ooxml:5.2.2")
|
||||
api("org.apache.httpcomponents.client5:httpclient5:5.2")
|
||||
api("org.apache.httpcomponents.core5:httpcore5-reactive:5.2")
|
||||
api("org.apache.poi:poi-ooxml:5.2.3")
|
||||
api("org.apache.tomcat.embed:tomcat-embed-core:10.1.1")
|
||||
api("org.apache.tomcat.embed:tomcat-embed-websocket:10.1.1")
|
||||
api("org.apache.tomcat:tomcat-util:10.1.1")
|
||||
@@ -124,11 +124,11 @@ dependencies {
|
||||
api("org.glassfish:jakarta.el:4.0.2")
|
||||
api("org.graalvm.sdk:graal-sdk:22.3.0")
|
||||
api("org.hamcrest:hamcrest:2.2")
|
||||
api("org.hibernate:hibernate-core-jakarta:5.6.12.Final")
|
||||
api("org.hibernate:hibernate-core-jakarta:5.6.14.Final")
|
||||
api("org.hibernate:hibernate-validator:7.0.5.Final")
|
||||
api("org.hsqldb:hsqldb:2.7.0")
|
||||
api("org.hsqldb:hsqldb:2.7.1")
|
||||
api("org.javamoney:moneta:1.4.2")
|
||||
api("org.jruby:jruby:9.3.8.0")
|
||||
api("org.jruby:jruby:9.4.0.0")
|
||||
api("org.junit.support:testng-engine:1.0.4")
|
||||
api("org.mozilla:rhino:1.7.11")
|
||||
api("org.ogce:xpp3:1.1.6")
|
||||
@@ -137,12 +137,12 @@ dependencies {
|
||||
api("org.seleniumhq.selenium:htmlunit-driver:2.66.0")
|
||||
api("org.seleniumhq.selenium:selenium-java:3.141.59")
|
||||
api("org.skyscreamer:jsonassert:1.5.0")
|
||||
api("org.slf4j:slf4j-api:2.0.3")
|
||||
api("org.slf4j:slf4j-api:2.0.5")
|
||||
api("org.testng:testng:7.6.1")
|
||||
api("org.webjars:underscorejs:1.8.3")
|
||||
api("org.webjars:webjars-locator-core:0.48")
|
||||
api("org.webjars:webjars-locator-core:0.52")
|
||||
api("org.xmlunit:xmlunit-assertj:2.9.0")
|
||||
api("org.xmlunit:xmlunit-matchers:2.9.0")
|
||||
api("org.yaml:snakeyaml:1.30")
|
||||
api("org.yaml:snakeyaml:1.33")
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
version=6.0.0
|
||||
version=6.0.3
|
||||
|
||||
org.gradle.caching=true
|
||||
org.gradle.jvmargs=-Xmx2048m
|
||||
org.gradle.parallel=true
|
||||
|
||||
kotlinVersion=1.7.20
|
||||
kotlinVersion=1.7.21
|
||||
|
||||
kotlin.stdlib.default.dependency=false
|
||||
|
||||
@@ -8,8 +8,8 @@ apply plugin: 'me.champeau.jmh'
|
||||
apply from: "$rootDir/gradle/publications.gradle"
|
||||
|
||||
dependencies {
|
||||
jmh 'org.openjdk.jmh:jmh-core:1.32'
|
||||
jmh 'org.openjdk.jmh:jmh-generator-annprocess:1.32'
|
||||
jmh 'org.openjdk.jmh:jmh-core:1.36'
|
||||
jmh 'org.openjdk.jmh:jmh-generator-annprocess:1.36'
|
||||
jmh 'net.sf.jopt-simple:jopt-simple'
|
||||
}
|
||||
|
||||
|
||||
Vendored
BIN
Binary file not shown.
+2
-1
@@ -1,5 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
|
||||
networkTimeout=10000
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
@@ -80,10 +80,10 @@ do
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
@@ -143,12 +143,16 @@ fi
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
@@ -205,6 +209,12 @@ set -- \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
|
||||
Vendored
+9
-6
@@ -14,7 +14,7 @@
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@@ -25,7 +25,8 @@
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
@@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Integration tests for scoped proxy use in conjunction with aop: namespace.
|
||||
* Deemed an integration test because .web mocks and application contexts are required.
|
||||
* Deemed an integration test because web mocks and application contexts are required.
|
||||
*
|
||||
* @author Rob Harrop
|
||||
* @author Juergen Hoeller
|
||||
|
||||
+1
-1
@@ -61,7 +61,7 @@ class EnableCachingIntegrationTests {
|
||||
ctx.register(Config.class, AspectJCacheConfig.class);
|
||||
// this test is a bit fragile, but gets the job done, proving that an
|
||||
// attempt was made to look up the AJ aspect. It's due to classpath issues
|
||||
// in .integration-tests that it's not found.
|
||||
// in integration-tests that it's not found.
|
||||
assertThatException().isThrownBy(ctx::refresh)
|
||||
.withMessageContaining("AspectJCachingConfiguration");
|
||||
}
|
||||
|
||||
+1
-1
@@ -97,7 +97,7 @@ class EnableTransactionManagementIntegrationTests {
|
||||
ctx.register(Config.class, AspectJTxConfig.class);
|
||||
// this test is a bit fragile, but gets the job done, proving that an
|
||||
// attempt was made to look up the AJ aspect. It's due to classpath issues
|
||||
// in .integration-tests that it's not found.
|
||||
// in integration-tests that it's not found.
|
||||
assertThatException()
|
||||
.isThrownBy(ctx::refresh)
|
||||
.withMessageContaining("AspectJJtaTransactionManagementConfiguration");
|
||||
|
||||
+8
-8
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2021 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -132,17 +132,17 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov
|
||||
private static final int STEP_REFERENCE_PCUT_BINDING = 7;
|
||||
private static final int STEP_FINISHED = 8;
|
||||
|
||||
private static final Set<String> singleValuedAnnotationPcds = new HashSet<>();
|
||||
private static final Set<String> singleValuedAnnotationPcds = Set.of(
|
||||
"@this",
|
||||
"@target",
|
||||
"@within",
|
||||
"@withincode",
|
||||
"@annotation");
|
||||
|
||||
private static final Set<String> nonReferencePointcutTokens = new HashSet<>();
|
||||
|
||||
|
||||
static {
|
||||
singleValuedAnnotationPcds.add("@this");
|
||||
singleValuedAnnotationPcds.add("@target");
|
||||
singleValuedAnnotationPcds.add("@within");
|
||||
singleValuedAnnotationPcds.add("@withincode");
|
||||
singleValuedAnnotationPcds.add("@annotation");
|
||||
|
||||
Set<PointcutPrimitive> pointcutPrimitives = PointcutParser.getAllSupportedPointcutPrimitives();
|
||||
for (PointcutPrimitive primitive : pointcutPrimitives) {
|
||||
nonReferencePointcutTokens.add(primitive.getName());
|
||||
|
||||
+11
-16
@@ -21,7 +21,6 @@ import java.io.ObjectInputStream;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -85,21 +84,17 @@ import org.springframework.util.StringUtils;
|
||||
public class AspectJExpressionPointcut extends AbstractExpressionPointcut
|
||||
implements ClassFilter, IntroductionAwareMethodMatcher, BeanFactoryAware {
|
||||
|
||||
private static final Set<PointcutPrimitive> SUPPORTED_PRIMITIVES = new HashSet<>();
|
||||
|
||||
static {
|
||||
SUPPORTED_PRIMITIVES.add(PointcutPrimitive.EXECUTION);
|
||||
SUPPORTED_PRIMITIVES.add(PointcutPrimitive.ARGS);
|
||||
SUPPORTED_PRIMITIVES.add(PointcutPrimitive.REFERENCE);
|
||||
SUPPORTED_PRIMITIVES.add(PointcutPrimitive.THIS);
|
||||
SUPPORTED_PRIMITIVES.add(PointcutPrimitive.TARGET);
|
||||
SUPPORTED_PRIMITIVES.add(PointcutPrimitive.WITHIN);
|
||||
SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ANNOTATION);
|
||||
SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_WITHIN);
|
||||
SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ARGS);
|
||||
SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_TARGET);
|
||||
}
|
||||
|
||||
private static final Set<PointcutPrimitive> SUPPORTED_PRIMITIVES = Set.of(
|
||||
PointcutPrimitive.EXECUTION,
|
||||
PointcutPrimitive.ARGS,
|
||||
PointcutPrimitive.REFERENCE,
|
||||
PointcutPrimitive.THIS,
|
||||
PointcutPrimitive.TARGET,
|
||||
PointcutPrimitive.WITHIN,
|
||||
PointcutPrimitive.AT_ANNOTATION,
|
||||
PointcutPrimitive.AT_WITHIN,
|
||||
PointcutPrimitive.AT_ARGS,
|
||||
PointcutPrimitive.AT_TARGET);
|
||||
|
||||
private static final Log logger = LogFactory.getLog(AspectJExpressionPointcut.class);
|
||||
|
||||
|
||||
+15
-20
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2021 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -21,7 +21,6 @@ import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
@@ -163,24 +162,22 @@ public abstract class AbstractAspectJAdvisorFactory implements AspectJAdvisorFac
|
||||
|
||||
|
||||
/**
|
||||
* Class modelling an AspectJ annotation, exposing its type enumeration and
|
||||
* Class modeling an AspectJ annotation, exposing its type enumeration and
|
||||
* pointcut String.
|
||||
* @param <A> the annotation type
|
||||
*/
|
||||
protected static class AspectJAnnotation<A extends Annotation> {
|
||||
|
||||
private static final String[] EXPRESSION_ATTRIBUTES = new String[] {"pointcut", "value"};
|
||||
private static final String[] EXPRESSION_ATTRIBUTES = {"pointcut", "value"};
|
||||
|
||||
private static Map<Class<?>, AspectJAnnotationType> annotationTypeMap = new HashMap<>(8);
|
||||
|
||||
static {
|
||||
annotationTypeMap.put(Pointcut.class, AspectJAnnotationType.AtPointcut);
|
||||
annotationTypeMap.put(Around.class, AspectJAnnotationType.AtAround);
|
||||
annotationTypeMap.put(Before.class, AspectJAnnotationType.AtBefore);
|
||||
annotationTypeMap.put(After.class, AspectJAnnotationType.AtAfter);
|
||||
annotationTypeMap.put(AfterReturning.class, AspectJAnnotationType.AtAfterReturning);
|
||||
annotationTypeMap.put(AfterThrowing.class, AspectJAnnotationType.AtAfterThrowing);
|
||||
}
|
||||
private static final Map<Class<?>, AspectJAnnotationType> annotationTypeMap = Map.of(
|
||||
Pointcut.class, AspectJAnnotationType.AtPointcut, //
|
||||
Around.class, AspectJAnnotationType.AtAround, //
|
||||
Before.class, AspectJAnnotationType.AtBefore, //
|
||||
After.class, AspectJAnnotationType.AtAfter, //
|
||||
AfterReturning.class, AspectJAnnotationType.AtAfterReturning, //
|
||||
AfterThrowing.class, AspectJAnnotationType.AtAfterThrowing //
|
||||
);
|
||||
|
||||
private final A annotation;
|
||||
|
||||
@@ -196,7 +193,7 @@ public abstract class AbstractAspectJAdvisorFactory implements AspectJAdvisorFac
|
||||
try {
|
||||
this.pointcutExpression = resolveExpression(annotation);
|
||||
Object argNames = AnnotationUtils.getValue(annotation, "argNames");
|
||||
this.argumentNames = (argNames instanceof String ? (String) argNames : "");
|
||||
this.argumentNames = (argNames instanceof String names ? names : "");
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalArgumentException(annotation + " is not a valid AspectJ annotation", ex);
|
||||
@@ -214,13 +211,11 @@ public abstract class AbstractAspectJAdvisorFactory implements AspectJAdvisorFac
|
||||
private String resolveExpression(A annotation) {
|
||||
for (String attributeName : EXPRESSION_ATTRIBUTES) {
|
||||
Object val = AnnotationUtils.getValue(annotation, attributeName);
|
||||
if (val instanceof String str) {
|
||||
if (!str.isEmpty()) {
|
||||
return str;
|
||||
}
|
||||
if (val instanceof String str && !str.isEmpty()) {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Failed to resolve expression: " + annotation);
|
||||
throw new IllegalStateException("Failed to resolve expression in: " + annotation);
|
||||
}
|
||||
|
||||
public AspectJAnnotationType getAnnotationType() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2021 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2021 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
+3
-3
@@ -195,7 +195,7 @@ abstract class AbstractAspectJAdvisorFactoryTests {
|
||||
|
||||
Advised advised = (Advised) itb;
|
||||
// Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors
|
||||
assertThat(advised.getAdvisors().length).isEqualTo(4);
|
||||
assertThat(advised.getAdvisors()).hasSize(4);
|
||||
ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia =
|
||||
(ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
|
||||
assertThat(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue();
|
||||
@@ -231,7 +231,7 @@ abstract class AbstractAspectJAdvisorFactoryTests {
|
||||
|
||||
Advised advised = (Advised) itb;
|
||||
// Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors
|
||||
assertThat(advised.getAdvisors().length).isEqualTo(4);
|
||||
assertThat(advised.getAdvisors()).hasSize(4);
|
||||
ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia =
|
||||
(ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
|
||||
assertThat(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue();
|
||||
@@ -366,7 +366,7 @@ abstract class AbstractAspectJAdvisorFactoryTests {
|
||||
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
|
||||
CannotBeUnlocked.class).isEmpty()).isTrue();
|
||||
assertThat(AopUtils.findAdvisorsThatCanApply(getFixture().getAdvisors(
|
||||
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")), NotLockable.class).size()).isEqualTo(2);
|
||||
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")), NotLockable.class)).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.aop.support;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.beans.testfixture.beans.TestBean;
|
||||
import org.springframework.core.testfixture.io.SerializationTestUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Dmitriy Kopylenko
|
||||
* @author Chris Beams
|
||||
*/
|
||||
public abstract class AbstractRegexpMethodPointcutTests {
|
||||
|
||||
private AbstractRegexpMethodPointcut rpc;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
rpc = getRegexpMethodPointcut();
|
||||
}
|
||||
|
||||
protected abstract AbstractRegexpMethodPointcut getRegexpMethodPointcut();
|
||||
|
||||
@Test
|
||||
public void testNoPatternSupplied() throws Exception {
|
||||
noPatternSuppliedTests(rpc);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSerializationWithNoPatternSupplied() throws Exception {
|
||||
rpc = SerializationTestUtils.serializeAndDeserialize(rpc);
|
||||
noPatternSuppliedTests(rpc);
|
||||
}
|
||||
|
||||
protected void noPatternSuppliedTests(AbstractRegexpMethodPointcut rpc) throws Exception {
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isFalse();
|
||||
assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse();
|
||||
assertThat(rpc.getPatterns().length).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExactMatch() throws Exception {
|
||||
rpc.setPattern("java.lang.Object.hashCode");
|
||||
exactMatchTests(rpc);
|
||||
rpc = SerializationTestUtils.serializeAndDeserialize(rpc);
|
||||
exactMatchTests(rpc);
|
||||
}
|
||||
|
||||
protected void exactMatchTests(AbstractRegexpMethodPointcut rpc) throws Exception {
|
||||
// assumes rpc.setPattern("java.lang.Object.hashCode");
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue();
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isTrue();
|
||||
assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSpecificMatch() throws Exception {
|
||||
rpc.setPattern("java.lang.String.hashCode");
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue();
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWildcard() throws Exception {
|
||||
rpc.setPattern(".*Object.hashCode");
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isTrue();
|
||||
assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWildcardForOneClass() throws Exception {
|
||||
rpc.setPattern("java.lang.Object.*");
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue();
|
||||
assertThat(rpc.matches(Object.class.getMethod("wait"), String.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMatchesObjectClass() throws Exception {
|
||||
rpc.setPattern("java.lang.Object.*");
|
||||
assertThat(rpc.matches(Exception.class.getMethod("hashCode"), IOException.class)).isTrue();
|
||||
// Doesn't match a method from Throwable
|
||||
assertThat(rpc.matches(Exception.class.getMethod("getMessage"), Exception.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithExclusion() throws Exception {
|
||||
this.rpc.setPattern(".*get.*");
|
||||
this.rpc.setExcludedPattern(".*Age.*");
|
||||
assertThat(this.rpc.matches(TestBean.class.getMethod("getName"), TestBean.class)).isTrue();
|
||||
assertThat(this.rpc.matches(TestBean.class.getMethod("getAge"), TestBean.class)).isFalse();
|
||||
}
|
||||
|
||||
}
|
||||
+84
-5
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -16,14 +16,93 @@
|
||||
|
||||
package org.springframework.aop.support;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.beans.testfixture.beans.TestBean;
|
||||
import org.springframework.core.testfixture.io.SerializationTestUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Dmitriy Kopylenko
|
||||
* @author Chris Beams
|
||||
* @author Dmitriy Kopylenko
|
||||
*/
|
||||
public class JdkRegexpMethodPointcutTests extends AbstractRegexpMethodPointcutTests {
|
||||
class JdkRegexpMethodPointcutTests {
|
||||
|
||||
@Override
|
||||
protected AbstractRegexpMethodPointcut getRegexpMethodPointcut() {
|
||||
return new JdkRegexpMethodPointcut();
|
||||
private AbstractRegexpMethodPointcut rpc = new JdkRegexpMethodPointcut();
|
||||
|
||||
|
||||
@Test
|
||||
void noPatternSupplied() throws Exception {
|
||||
noPatternSuppliedTests(rpc);
|
||||
}
|
||||
|
||||
@Test
|
||||
void serializationWithNoPatternSupplied() throws Exception {
|
||||
rpc = SerializationTestUtils.serializeAndDeserialize(rpc);
|
||||
noPatternSuppliedTests(rpc);
|
||||
}
|
||||
|
||||
private void noPatternSuppliedTests(AbstractRegexpMethodPointcut rpc) throws Exception {
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isFalse();
|
||||
assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse();
|
||||
assertThat(rpc.getPatterns()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void exactMatch() throws Exception {
|
||||
rpc.setPattern("java.lang.Object.hashCode");
|
||||
exactMatchTests(rpc);
|
||||
rpc = SerializationTestUtils.serializeAndDeserialize(rpc);
|
||||
exactMatchTests(rpc);
|
||||
}
|
||||
|
||||
private void exactMatchTests(AbstractRegexpMethodPointcut rpc) throws Exception {
|
||||
// assumes rpc.setPattern("java.lang.Object.hashCode");
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue();
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isTrue();
|
||||
assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void specificMatch() throws Exception {
|
||||
rpc.setPattern("java.lang.String.hashCode");
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue();
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void wildcard() throws Exception {
|
||||
rpc.setPattern(".*Object.hashCode");
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isTrue();
|
||||
assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void wildcardForOneClass() throws Exception {
|
||||
rpc.setPattern("java.lang.Object.*");
|
||||
assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue();
|
||||
assertThat(rpc.matches(Object.class.getMethod("wait"), String.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesObjectClass() throws Exception {
|
||||
rpc.setPattern("java.lang.Object.*");
|
||||
assertThat(rpc.matches(Exception.class.getMethod("hashCode"), IOException.class)).isTrue();
|
||||
// Doesn't match a method from Throwable
|
||||
assertThat(rpc.matches(Exception.class.getMethod("getMessage"), Exception.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void withExclusion() throws Exception {
|
||||
this.rpc.setPattern(".*get.*");
|
||||
this.rpc.setExcludedPattern(".*Age.*");
|
||||
assertThat(this.rpc.matches(TestBean.class.getMethod("getName"), TestBean.class)).isTrue();
|
||||
assertThat(this.rpc.matches(TestBean.class.getMethod("getAge"), TestBean.class)).isFalse();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -11,10 +11,16 @@ sourceSets.test.java.srcDirs = files()
|
||||
compileAspectj {
|
||||
sourceCompatibility "17"
|
||||
targetCompatibility "17"
|
||||
ajcOptions {
|
||||
compilerArgs += "-parameters"
|
||||
}
|
||||
}
|
||||
compileTestAspectj {
|
||||
sourceCompatibility "17"
|
||||
targetCompatibility "17"
|
||||
ajcOptions {
|
||||
compilerArgs += "-parameters"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
@@ -61,7 +61,7 @@ import org.springframework.util.StringUtils;
|
||||
* <p>Mainly for internal use within the framework, but to some degree also
|
||||
* useful for application classes. Consider
|
||||
* <a href="https://commons.apache.org/proper/commons-beanutils/">Apache Commons BeanUtils</a>,
|
||||
* <a href="https://hotelsdotcom.github.io/bull/">BULL - Bean Utils Light Library</a>,
|
||||
* <a href="https://github.com/ExpediaGroup/bull">BULL - Bean Utils Light Library</a>,
|
||||
* or similar third-party frameworks for more comprehensive bean utilities.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2021 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
import java.beans.BeanDescriptor;
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.IntrospectionException;
|
||||
import java.beans.PropertyDescriptor;
|
||||
@@ -52,6 +53,10 @@ class SimpleBeanInfoFactory implements BeanInfoFactory, Ordered {
|
||||
PropertyDescriptorUtils.determineBasicProperties(beanClass);
|
||||
|
||||
return new SimpleBeanInfo() {
|
||||
@Override
|
||||
public BeanDescriptor getBeanDescriptor() {
|
||||
return new BeanDescriptor(beanClass);
|
||||
}
|
||||
@Override
|
||||
public PropertyDescriptor[] getPropertyDescriptors() {
|
||||
return pds.toArray(PropertyDescriptorUtils.EMPTY_PROPERTY_DESCRIPTOR_ARRAY);
|
||||
|
||||
+4
-4
@@ -25,7 +25,6 @@ import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Member;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
@@ -46,6 +45,7 @@ import org.springframework.aot.generate.GeneratedMethod;
|
||||
import org.springframework.aot.generate.GenerationContext;
|
||||
import org.springframework.aot.hint.ExecutableMode;
|
||||
import org.springframework.aot.hint.RuntimeHints;
|
||||
import org.springframework.aot.hint.support.ClassHintUtils;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.PropertyValues;
|
||||
@@ -1018,10 +1018,10 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
|
||||
|
||||
private void registerProxyIfNecessary(RuntimeHints runtimeHints, DependencyDescriptor dependencyDescriptor) {
|
||||
if (this.candidateResolver != null) {
|
||||
Class<?> proxyType =
|
||||
Class<?> proxyClass =
|
||||
this.candidateResolver.getLazyResolutionProxyClass(dependencyDescriptor, null);
|
||||
if (proxyType != null && Proxy.isProxyClass(proxyType)) {
|
||||
runtimeHints.proxies().registerJdkProxy(proxyType.getInterfaces());
|
||||
if (proxyClass != null) {
|
||||
ClassHintUtils.registerProxyIfNecessary(proxyClass, runtimeHints);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-8
@@ -134,10 +134,12 @@ class BeanDefinitionMethodGenerator {
|
||||
type.addJavadoc("Bean definitions for {@link $T}", topLevelClassName);
|
||||
type.addModifiers(Modifier.PUBLIC);
|
||||
});
|
||||
|
||||
List<String> names = target.simpleNames();
|
||||
if (names.size() == 1) {
|
||||
return generatedClass;
|
||||
}
|
||||
|
||||
List<String> namesToProcess = names.subList(1, names.size());
|
||||
ClassName currentTargetClassName = topLevelClassName;
|
||||
GeneratedClass tmp = generatedClass;
|
||||
@@ -148,8 +150,7 @@ class BeanDefinitionMethodGenerator {
|
||||
return tmp;
|
||||
}
|
||||
|
||||
private static GeneratedClass createInnerClass(GeneratedClass generatedClass,
|
||||
String name, ClassName target) {
|
||||
private static GeneratedClass createInnerClass(GeneratedClass generatedClass, String name, ClassName target) {
|
||||
return generatedClass.getOrAdd(name, type -> {
|
||||
type.addJavadoc("Bean definitions for {@link $T}", target);
|
||||
type.addModifiers(Modifier.PUBLIC, Modifier.STATIC);
|
||||
@@ -167,16 +168,16 @@ class BeanDefinitionMethodGenerator {
|
||||
return codeFragments;
|
||||
}
|
||||
|
||||
private GeneratedMethod generateBeanDefinitionMethod(
|
||||
GenerationContext generationContext, ClassName className,
|
||||
GeneratedMethods generatedMethods, BeanRegistrationCodeFragments codeFragments,
|
||||
Modifier modifier) {
|
||||
private GeneratedMethod generateBeanDefinitionMethod(GenerationContext generationContext,
|
||||
ClassName className, GeneratedMethods generatedMethods,
|
||||
BeanRegistrationCodeFragments codeFragments, Modifier modifier) {
|
||||
|
||||
BeanRegistrationCodeGenerator codeGenerator = new BeanRegistrationCodeGenerator(
|
||||
className, generatedMethods, this.registeredBean,
|
||||
this.constructorOrFactoryMethod, codeFragments);
|
||||
this.aotContributions.forEach(aotContribution -> aotContribution
|
||||
.applyTo(generationContext, codeGenerator));
|
||||
|
||||
this.aotContributions.forEach(aotContribution -> aotContribution.applyTo(generationContext, codeGenerator));
|
||||
|
||||
return generatedMethods.add("getBeanDefinition", method -> {
|
||||
method.addJavadoc("Get the $L definition for '$L'",
|
||||
(!this.registeredBean.isInnerBean()) ? "bean" : "inner-bean",
|
||||
|
||||
+6
-12
@@ -87,8 +87,7 @@ class BeanDefinitionMethodGeneratorFactory {
|
||||
* {@link BeanRegistrationAotProcessor} provided contributions.
|
||||
* @param registeredBean the registered bean
|
||||
* @param currentPropertyName the property name that this bean belongs to
|
||||
* @return a new {@link BeanDefinitionMethodGenerator} instance or
|
||||
* {@code null}
|
||||
* @return a new {@link BeanDefinitionMethodGenerator} instance or {@code null}
|
||||
*/
|
||||
@Nullable
|
||||
BeanDefinitionMethodGenerator getBeanDefinitionMethodGenerator(
|
||||
@@ -97,8 +96,7 @@ class BeanDefinitionMethodGeneratorFactory {
|
||||
if (isExcluded(registeredBean)) {
|
||||
return null;
|
||||
}
|
||||
List<BeanRegistrationAotContribution> contributions = getAotContributions(
|
||||
registeredBean);
|
||||
List<BeanRegistrationAotContribution> contributions = getAotContributions(registeredBean);
|
||||
return new BeanDefinitionMethodGenerator(this, registeredBean,
|
||||
currentPropertyName, contributions);
|
||||
}
|
||||
@@ -110,8 +108,7 @@ class BeanDefinitionMethodGeneratorFactory {
|
||||
* {@link BeanDefinitionMethodGenerator} will include all
|
||||
* {@link BeanRegistrationAotProcessor} provided contributions.
|
||||
* @param registeredBean the registered bean
|
||||
* @return a new {@link BeanDefinitionMethodGenerator} instance or
|
||||
* {@code null}
|
||||
* @return a new {@link BeanDefinitionMethodGenerator} instance or {@code null}
|
||||
*/
|
||||
@Nullable
|
||||
BeanDefinitionMethodGenerator getBeanDefinitionMethodGenerator(RegisteredBean registeredBean) {
|
||||
@@ -142,19 +139,16 @@ class BeanDefinitionMethodGeneratorFactory {
|
||||
}
|
||||
if (BeanRegistrationAotProcessor.class.isAssignableFrom(beanClass)) {
|
||||
BeanRegistrationAotProcessor processor = this.aotProcessors.findByBeanName(registeredBean.getBeanName());
|
||||
return (processor == null) || processor.isBeanExcludedFromAotProcessing();
|
||||
return (processor == null || processor.isBeanExcludedFromAotProcessing());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private List<BeanRegistrationAotContribution> getAotContributions(
|
||||
RegisteredBean registeredBean) {
|
||||
|
||||
private List<BeanRegistrationAotContribution> getAotContributions(RegisteredBean registeredBean) {
|
||||
String beanName = registeredBean.getBeanName();
|
||||
List<BeanRegistrationAotContribution> contributions = new ArrayList<>();
|
||||
for (BeanRegistrationAotProcessor aotProcessor : this.aotProcessors) {
|
||||
BeanRegistrationAotContribution contribution = aotProcessor
|
||||
.processAheadOfTime(registeredBean);
|
||||
BeanRegistrationAotContribution contribution = aotProcessor.processAheadOfTime(registeredBean);
|
||||
if (contribution != null) {
|
||||
logger.trace(LogMessage.format(
|
||||
"Adding bean registration AOT contribution %S from %S to '%S'",
|
||||
|
||||
+2
-2
@@ -155,7 +155,7 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
|
||||
public BeanInstanceSupplier<T> withGenerator(
|
||||
ThrowingBiFunction<RegisteredBean, AutowiredArguments, T> generator) {
|
||||
Assert.notNull(generator, "'generator' must not be null");
|
||||
return new BeanInstanceSupplier<T>(this.lookup, generator, this.shortcuts);
|
||||
return new BeanInstanceSupplier<>(this.lookup, generator, this.shortcuts);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -196,7 +196,7 @@ public final class BeanInstanceSupplier<T> extends AutowiredElementResolver impl
|
||||
* that uses the shortcuts
|
||||
*/
|
||||
public BeanInstanceSupplier<T> withShortcuts(String... beanNames) {
|
||||
return new BeanInstanceSupplier<T>(this.lookup, this.generator, beanNames);
|
||||
return new BeanInstanceSupplier<>(this.lookup, this.generator, beanNames);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+4
-6
@@ -64,8 +64,7 @@ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationC
|
||||
}
|
||||
|
||||
@Override
|
||||
public CodeBlock generateSetBeanDefinitionPropertiesCode(
|
||||
GenerationContext generationContext,
|
||||
public CodeBlock generateSetBeanDefinitionPropertiesCode(GenerationContext generationContext,
|
||||
BeanRegistrationCode beanRegistrationCode, RootBeanDefinition beanDefinition,
|
||||
Predicate<String> attributeFilter) {
|
||||
|
||||
@@ -74,8 +73,7 @@ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationC
|
||||
}
|
||||
|
||||
@Override
|
||||
public CodeBlock generateSetBeanInstanceSupplierCode(
|
||||
GenerationContext generationContext,
|
||||
public CodeBlock generateSetBeanInstanceSupplierCode(GenerationContext generationContext,
|
||||
BeanRegistrationCode beanRegistrationCode, CodeBlock instanceSupplierCode,
|
||||
List<MethodReference> postProcessors) {
|
||||
|
||||
@@ -85,8 +83,8 @@ public class BeanRegistrationCodeFragmentsDecorator implements BeanRegistrationC
|
||||
|
||||
@Override
|
||||
public CodeBlock generateInstanceSupplierCode(GenerationContext generationContext,
|
||||
BeanRegistrationCode beanRegistrationCode,
|
||||
Executable constructorOrFactoryMethod, boolean allowDirectSupplierShortcut) {
|
||||
BeanRegistrationCode beanRegistrationCode, Executable constructorOrFactoryMethod,
|
||||
boolean allowDirectSupplierShortcut) {
|
||||
|
||||
return this.delegate.generateInstanceSupplierCode(generationContext,
|
||||
beanRegistrationCode, constructorOrFactoryMethod, allowDirectSupplierShortcut);
|
||||
|
||||
+6
-2
@@ -22,6 +22,7 @@ import java.util.Map;
|
||||
import org.springframework.beans.factory.aot.BeanRegistrationsAotContribution.Registration;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.beans.factory.support.RegisteredBean;
|
||||
import org.springframework.lang.Nullable;
|
||||
|
||||
/**
|
||||
* {@link BeanFactoryInitializationAotProcessor} that contributes code to
|
||||
@@ -35,19 +36,22 @@ import org.springframework.beans.factory.support.RegisteredBean;
|
||||
class BeanRegistrationsAotProcessor implements BeanFactoryInitializationAotProcessor {
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public BeanRegistrationsAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
|
||||
BeanDefinitionMethodGeneratorFactory beanDefinitionMethodGeneratorFactory =
|
||||
new BeanDefinitionMethodGeneratorFactory(beanFactory);
|
||||
Map<String, Registration> registrations = new LinkedHashMap<>();
|
||||
|
||||
for (String beanName : beanFactory.getBeanDefinitionNames()) {
|
||||
RegisteredBean registeredBean = RegisteredBean.of(beanFactory, beanName);
|
||||
BeanDefinitionMethodGenerator beanDefinitionMethodGenerator = beanDefinitionMethodGeneratorFactory
|
||||
.getBeanDefinitionMethodGenerator(registeredBean);
|
||||
BeanDefinitionMethodGenerator beanDefinitionMethodGenerator =
|
||||
beanDefinitionMethodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean);
|
||||
if (beanDefinitionMethodGenerator != null) {
|
||||
registrations.put(beanName, new Registration(beanDefinitionMethodGenerator,
|
||||
beanFactory.getAliases(beanName)));
|
||||
}
|
||||
}
|
||||
|
||||
if (registrations.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
+46
-33
@@ -46,16 +46,16 @@ import org.springframework.util.function.ThrowingSupplier;
|
||||
* Internal code generator to create an {@link InstanceSupplier}, usually in
|
||||
* the form of a {@link BeanInstanceSupplier} that retains the executable
|
||||
* that is used to instantiate the bean.
|
||||
* <p>
|
||||
* Generated code is usually a method reference that generate the
|
||||
* {@link BeanInstanceSupplier}, but some shortcut can be used as well such
|
||||
* as:
|
||||
*
|
||||
* <p>Generated code is usually a method reference that generate the
|
||||
* {@link BeanInstanceSupplier}, but some shortcut can be used as well such as:
|
||||
* <pre class="code">
|
||||
* {@code InstanceSupplier.of(TheGeneratedClass::getMyBeanInstance);}
|
||||
* </pre>
|
||||
*
|
||||
* @author Phillip Webb
|
||||
* @author Stephane Nicoll
|
||||
* @author Juergen Hoeller
|
||||
* @since 6.0
|
||||
*/
|
||||
class InstanceSupplierCodeGenerator {
|
||||
@@ -90,9 +90,7 @@ class InstanceSupplierCodeGenerator {
|
||||
}
|
||||
|
||||
|
||||
CodeBlock generateCode(RegisteredBean registeredBean,
|
||||
Executable constructorOrFactoryMethod) {
|
||||
|
||||
CodeBlock generateCode(RegisteredBean registeredBean, Executable constructorOrFactoryMethod) {
|
||||
if (constructorOrFactoryMethod instanceof Constructor<?> constructor) {
|
||||
return generateCodeForConstructor(registeredBean, constructor);
|
||||
}
|
||||
@@ -108,6 +106,7 @@ class InstanceSupplierCodeGenerator {
|
||||
Class<?> beanClass = registeredBean.getBeanClass();
|
||||
Class<?> declaringClass = constructor.getDeclaringClass();
|
||||
boolean dependsOnBean = ClassUtils.isInnerClass(declaringClass);
|
||||
|
||||
Visibility accessVisibility = getAccessVisibility(registeredBean, constructor);
|
||||
if (accessVisibility != Visibility.PRIVATE) {
|
||||
return generateCodeForAccessibleConstructor(beanName, beanClass, constructor,
|
||||
@@ -121,6 +120,7 @@ class InstanceSupplierCodeGenerator {
|
||||
|
||||
this.generationContext.getRuntimeHints().reflection().registerConstructor(
|
||||
constructor, ExecutableMode.INTROSPECT);
|
||||
|
||||
if (!dependsOnBean && constructor.getParameterCount() == 0) {
|
||||
if (!this.allowDirectSupplierShortcut) {
|
||||
return CodeBlock.of("$T.using($T::new)", InstanceSupplier.class, declaringClass);
|
||||
@@ -130,6 +130,7 @@ class InstanceSupplierCodeGenerator {
|
||||
}
|
||||
return CodeBlock.of("$T.of($T::new)", ThrowingSupplier.class, declaringClass);
|
||||
}
|
||||
|
||||
GeneratedMethod generatedMethod = generateGetInstanceSupplierMethod(method ->
|
||||
buildGetInstanceMethodForConstructor(method, beanName, beanClass, constructor,
|
||||
declaringClass, dependsOnBean, PRIVATE_STATIC));
|
||||
@@ -141,6 +142,7 @@ class InstanceSupplierCodeGenerator {
|
||||
|
||||
this.generationContext.getRuntimeHints().reflection()
|
||||
.registerConstructor(constructor, ExecutableMode.INVOKE);
|
||||
|
||||
GeneratedMethod generatedMethod = generateGetInstanceSupplierMethod(method -> {
|
||||
method.addJavadoc("Get the bean instance supplier for '$L'.", beanName);
|
||||
method.addModifiers(PRIVATE_STATIC);
|
||||
@@ -148,6 +150,7 @@ class InstanceSupplierCodeGenerator {
|
||||
int parameterOffset = (!dependsOnBean) ? 0 : 1;
|
||||
method.addStatement(generateResolverForConstructor(beanClass, constructor, parameterOffset));
|
||||
});
|
||||
|
||||
return generateReturnStatement(generatedMethod);
|
||||
}
|
||||
|
||||
@@ -158,14 +161,17 @@ class InstanceSupplierCodeGenerator {
|
||||
method.addJavadoc("Get the bean instance supplier for '$L'.", beanName);
|
||||
method.addModifiers(modifiers);
|
||||
method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, beanClass));
|
||||
|
||||
int parameterOffset = (!dependsOnBean) ? 0 : 1;
|
||||
CodeBlock.Builder code = CodeBlock.builder();
|
||||
code.add(generateResolverForConstructor(beanClass, constructor, parameterOffset));
|
||||
boolean hasArguments = constructor.getParameterCount() > 0;
|
||||
|
||||
CodeBlock arguments = hasArguments ?
|
||||
new AutowiredArgumentsCodeGenerator(declaringClass, constructor)
|
||||
.generateCode(constructor.getParameterTypes(), parameterOffset)
|
||||
: NO_ARGS;
|
||||
|
||||
CodeBlock newInstance = generateNewInstanceCodeForConstructor(dependsOnBean, declaringClass, arguments);
|
||||
code.add(generateWithGeneratorCode(hasArguments, newInstance));
|
||||
method.addStatement(code.build());
|
||||
@@ -184,92 +190,99 @@ class InstanceSupplierCodeGenerator {
|
||||
if (!dependsOnBean) {
|
||||
return CodeBlock.of("new $T($L)", declaringClass, args);
|
||||
}
|
||||
|
||||
return CodeBlock.of("$L.getBeanFactory().getBean($T.class).new $L($L)",
|
||||
REGISTERED_BEAN_PARAMETER_NAME, declaringClass.getEnclosingClass(),
|
||||
declaringClass.getSimpleName(), args);
|
||||
}
|
||||
|
||||
private CodeBlock generateCodeForFactoryMethod(RegisteredBean registeredBean,
|
||||
Method factoryMethod) {
|
||||
|
||||
private CodeBlock generateCodeForFactoryMethod(RegisteredBean registeredBean, Method factoryMethod) {
|
||||
String beanName = registeredBean.getBeanName();
|
||||
Class<?> beanClass = registeredBean.getBeanClass();
|
||||
Class<?> declaringClass = ClassUtils
|
||||
.getUserClass(factoryMethod.getDeclaringClass());
|
||||
Class<?> declaringClass = ClassUtils.getUserClass(factoryMethod.getDeclaringClass());
|
||||
boolean dependsOnBean = !Modifier.isStatic(factoryMethod.getModifiers());
|
||||
|
||||
Visibility accessVisibility = getAccessVisibility(registeredBean, factoryMethod);
|
||||
if (accessVisibility != Visibility.PRIVATE) {
|
||||
return generateCodeForAccessibleFactoryMethod(
|
||||
beanName, beanClass, factoryMethod, declaringClass, dependsOnBean);
|
||||
beanName, factoryMethod, declaringClass, dependsOnBean);
|
||||
}
|
||||
return generateCodeForInaccessibleFactoryMethod(beanName, beanClass, factoryMethod, declaringClass);
|
||||
return generateCodeForInaccessibleFactoryMethod(beanName, factoryMethod, declaringClass);
|
||||
}
|
||||
|
||||
private CodeBlock generateCodeForAccessibleFactoryMethod(String beanName,
|
||||
Class<?> beanClass, Method factoryMethod, Class<?> declaringClass, boolean dependsOnBean) {
|
||||
Method factoryMethod, Class<?> declaringClass, boolean dependsOnBean) {
|
||||
|
||||
this.generationContext.getRuntimeHints().reflection().registerMethod(
|
||||
factoryMethod, ExecutableMode.INTROSPECT);
|
||||
|
||||
if (!dependsOnBean && factoryMethod.getParameterCount() == 0) {
|
||||
Class<?> suppliedType = ClassUtils.resolvePrimitiveIfNecessary(factoryMethod.getReturnType());
|
||||
CodeBlock.Builder code = CodeBlock.builder();
|
||||
code.add("$T.<$T>forFactoryMethod($T.class, $S)", BeanInstanceSupplier.class,
|
||||
beanClass, declaringClass, factoryMethod.getName());
|
||||
suppliedType, declaringClass, factoryMethod.getName());
|
||||
code.add(".withGenerator($T::$L)", declaringClass, factoryMethod.getName());
|
||||
return code.build();
|
||||
}
|
||||
|
||||
GeneratedMethod getInstanceMethod = generateGetInstanceSupplierMethod(method ->
|
||||
buildGetInstanceMethodForFactoryMethod(method, beanName, beanClass, factoryMethod,
|
||||
buildGetInstanceMethodForFactoryMethod(method, beanName, factoryMethod,
|
||||
declaringClass, dependsOnBean, PRIVATE_STATIC));
|
||||
return generateReturnStatement(getInstanceMethod);
|
||||
}
|
||||
|
||||
private CodeBlock generateCodeForInaccessibleFactoryMethod(String beanName, Class<?> beanClass,
|
||||
Method factoryMethod, Class<?> declaringClass) {
|
||||
private CodeBlock generateCodeForInaccessibleFactoryMethod(
|
||||
String beanName, Method factoryMethod, Class<?> declaringClass) {
|
||||
|
||||
this.generationContext.getRuntimeHints().reflection().registerMethod(factoryMethod, ExecutableMode.INVOKE);
|
||||
GeneratedMethod getInstanceMethod = generateGetInstanceSupplierMethod(method -> {
|
||||
Class<?> suppliedType = ClassUtils.resolvePrimitiveIfNecessary(factoryMethod.getReturnType());
|
||||
method.addJavadoc("Get the bean instance supplier for '$L'.", beanName);
|
||||
method.addModifiers(PRIVATE_STATIC);
|
||||
method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, beanClass));
|
||||
method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, suppliedType));
|
||||
method.addStatement(generateInstanceSupplierForFactoryMethod(
|
||||
beanClass, factoryMethod, declaringClass, factoryMethod.getName()));
|
||||
factoryMethod, suppliedType, declaringClass, factoryMethod.getName()));
|
||||
});
|
||||
return generateReturnStatement(getInstanceMethod);
|
||||
}
|
||||
|
||||
private void buildGetInstanceMethodForFactoryMethod(MethodSpec.Builder method,
|
||||
String beanName, Class<?> beanClass, Method factoryMethod, Class<?> declaringClass,
|
||||
String beanName, Method factoryMethod, Class<?> declaringClass,
|
||||
boolean dependsOnBean, javax.lang.model.element.Modifier... modifiers) {
|
||||
|
||||
String factoryMethodName = factoryMethod.getName();
|
||||
Class<?> suppliedType = ClassUtils.resolvePrimitiveIfNecessary(factoryMethod.getReturnType());
|
||||
|
||||
method.addJavadoc("Get the bean instance supplier for '$L'.", beanName);
|
||||
method.addModifiers(modifiers);
|
||||
method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, beanClass));
|
||||
method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, suppliedType));
|
||||
|
||||
CodeBlock.Builder code = CodeBlock.builder();
|
||||
code.add(generateInstanceSupplierForFactoryMethod(
|
||||
beanClass, factoryMethod, declaringClass, factoryMethodName));
|
||||
factoryMethod, suppliedType, declaringClass, factoryMethodName));
|
||||
|
||||
boolean hasArguments = factoryMethod.getParameterCount() > 0;
|
||||
CodeBlock arguments = hasArguments ?
|
||||
new AutowiredArgumentsCodeGenerator(declaringClass, factoryMethod)
|
||||
.generateCode(factoryMethod.getParameterTypes())
|
||||
: NO_ARGS;
|
||||
|
||||
CodeBlock newInstance = generateNewInstanceCodeForMethod(
|
||||
dependsOnBean, declaringClass, factoryMethodName, arguments);
|
||||
code.add(generateWithGeneratorCode(hasArguments, newInstance));
|
||||
method.addStatement(code.build());
|
||||
}
|
||||
|
||||
private CodeBlock generateInstanceSupplierForFactoryMethod(Class<?> beanClass,
|
||||
Method factoryMethod, Class<?> declaringClass, String factoryMethodName) {
|
||||
private CodeBlock generateInstanceSupplierForFactoryMethod(Method factoryMethod,
|
||||
Class<?> suppliedType, Class<?> declaringClass, String factoryMethodName) {
|
||||
|
||||
if (factoryMethod.getParameterCount() == 0) {
|
||||
return CodeBlock.of("return $T.<$T>forFactoryMethod($T.class, $S)",
|
||||
BeanInstanceSupplier.class, beanClass, declaringClass,
|
||||
factoryMethodName);
|
||||
BeanInstanceSupplier.class, suppliedType, declaringClass, factoryMethodName);
|
||||
}
|
||||
|
||||
CodeBlock parameterTypes = generateParameterTypesCode(factoryMethod.getParameterTypes(), 0);
|
||||
return CodeBlock.of("return $T.<$T>forFactoryMethod($T.class, $S, $L)",
|
||||
BeanInstanceSupplier.class, beanClass, declaringClass, factoryMethodName, parameterTypes);
|
||||
BeanInstanceSupplier.class, suppliedType, declaringClass, factoryMethodName, parameterTypes);
|
||||
}
|
||||
|
||||
private CodeBlock generateNewInstanceCodeForMethod(boolean dependsOnBean,
|
||||
@@ -288,9 +301,9 @@ class InstanceSupplierCodeGenerator {
|
||||
}
|
||||
|
||||
private CodeBlock generateWithGeneratorCode(boolean hasArguments, CodeBlock newInstance) {
|
||||
CodeBlock lambdaArguments = (hasArguments
|
||||
? CodeBlock.of("($L, $L)", REGISTERED_BEAN_PARAMETER_NAME, ARGS_PARAMETER_NAME)
|
||||
: CodeBlock.of("($L)", REGISTERED_BEAN_PARAMETER_NAME));
|
||||
CodeBlock lambdaArguments = (hasArguments ?
|
||||
CodeBlock.of("($L, $L)", REGISTERED_BEAN_PARAMETER_NAME, ARGS_PARAMETER_NAME) :
|
||||
CodeBlock.of("($L)", REGISTERED_BEAN_PARAMETER_NAME));
|
||||
Builder code = CodeBlock.builder();
|
||||
code.add("\n");
|
||||
code.indent().indent();
|
||||
|
||||
+20
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2021 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -360,6 +360,25 @@ public class ConstructorArgumentValues {
|
||||
return valueHolder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether at least one argument value refers to a name.
|
||||
* @since 6.0.3
|
||||
* @see ValueHolder#getName()
|
||||
*/
|
||||
public boolean containsNamedArgument() {
|
||||
for (ValueHolder valueHolder : this.indexedArgumentValues.values()) {
|
||||
if (valueHolder.getName() != null) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (ValueHolder valueHolder : this.genericArgumentValues) {
|
||||
if (valueHolder.getName() != null) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of argument values held in this instance,
|
||||
* counting both indexed and generic argument values.
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2021 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -143,7 +143,7 @@ public class TypedStringValue implements BeanMetadataElement {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether this typed String value carries a target type .
|
||||
* Return whether this typed String value carries a target type.
|
||||
*/
|
||||
public boolean hasTargetType() {
|
||||
return (this.targetType instanceof Class);
|
||||
|
||||
+3
-2
@@ -184,8 +184,9 @@ public abstract class YamlProcessor {
|
||||
protected Yaml createYaml() {
|
||||
LoaderOptions loaderOptions = new LoaderOptions();
|
||||
loaderOptions.setAllowDuplicateKeys(false);
|
||||
return new Yaml(new FilteringConstructor(loaderOptions), new Representer(),
|
||||
new DumperOptions(), loaderOptions);
|
||||
DumperOptions dumperOptions = new DumperOptions();
|
||||
return new Yaml(new FilteringConstructor(loaderOptions), new Representer(dumperOptions),
|
||||
dumperOptions, loaderOptions);
|
||||
}
|
||||
|
||||
private boolean process(MatchCallback callback, Yaml yaml, Resource resource) {
|
||||
|
||||
+20
-22
@@ -599,8 +599,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
|
||||
exposedObject = initializeBean(beanName, exposedObject, mbd);
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
|
||||
throw (BeanCreationException) ex;
|
||||
if (ex instanceof BeanCreationException bce && beanName.equals(bce.getBeanName())) {
|
||||
throw bce;
|
||||
}
|
||||
else {
|
||||
throw new BeanCreationException(mbd.getResourceDescription(), beanName, ex.getMessage(), ex);
|
||||
@@ -862,9 +862,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
|
||||
// declaration without instantiating the containing bean at all.
|
||||
BeanDefinition factoryBeanDefinition = getBeanDefinition(factoryBeanName);
|
||||
Class<?> factoryBeanClass;
|
||||
if (factoryBeanDefinition instanceof AbstractBeanDefinition &&
|
||||
((AbstractBeanDefinition) factoryBeanDefinition).hasBeanClass()) {
|
||||
factoryBeanClass = ((AbstractBeanDefinition) factoryBeanDefinition).getBeanClass();
|
||||
if (factoryBeanDefinition instanceof AbstractBeanDefinition abstractBeanDefinition &&
|
||||
abstractBeanDefinition.hasBeanClass()) {
|
||||
factoryBeanClass = abstractBeanDefinition.getBeanClass();
|
||||
}
|
||||
else {
|
||||
RootBeanDefinition fbmbd = getMergedBeanDefinition(factoryBeanName, factoryBeanDefinition);
|
||||
@@ -975,8 +975,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
|
||||
return (FactoryBean<?>) bw.getWrappedInstance();
|
||||
}
|
||||
Object beanInstance = getSingleton(beanName, false);
|
||||
if (beanInstance instanceof FactoryBean) {
|
||||
return (FactoryBean<?>) beanInstance;
|
||||
if (beanInstance instanceof FactoryBean<?> factoryBean) {
|
||||
return factoryBean;
|
||||
}
|
||||
if (isSingletonCurrentlyInCreation(beanName) ||
|
||||
(mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) {
|
||||
@@ -1389,11 +1389,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
|
||||
}
|
||||
pvs = newPvs;
|
||||
}
|
||||
|
||||
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
|
||||
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
|
||||
|
||||
if (hasInstAwareBpps) {
|
||||
if (hasInstantiationAwareBeanPostProcessors()) {
|
||||
if (pvs == null) {
|
||||
pvs = mbd.getPropertyValues();
|
||||
}
|
||||
@@ -1405,6 +1401,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
|
||||
pvs = pvsToUse;
|
||||
}
|
||||
}
|
||||
|
||||
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
|
||||
if (needsDepCheck) {
|
||||
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
|
||||
checkDependencies(beanName, mbd, filteredPds, pvs);
|
||||
@@ -1677,8 +1675,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
|
||||
}
|
||||
deepCopy.add(pv);
|
||||
}
|
||||
else if (convertible && originalValue instanceof TypedStringValue &&
|
||||
!((TypedStringValue) originalValue).isDynamic() &&
|
||||
else if (convertible && originalValue instanceof TypedStringValue typedStringValue &&
|
||||
!typedStringValue.isDynamic() &&
|
||||
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
|
||||
pv.setConvertedValue(convertedValue);
|
||||
deepCopy.add(pv);
|
||||
@@ -1709,8 +1707,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
|
||||
private Object convertForProperty(
|
||||
@Nullable Object value, String propertyName, BeanWrapper bw, TypeConverter converter) {
|
||||
|
||||
if (converter instanceof BeanWrapperImpl) {
|
||||
return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName);
|
||||
if (converter instanceof BeanWrapperImpl beanWrapper) {
|
||||
return beanWrapper.convertForProperty(value, propertyName);
|
||||
}
|
||||
else {
|
||||
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
|
||||
@@ -1761,17 +1759,17 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
|
||||
|
||||
private void invokeAwareMethods(String beanName, Object bean) {
|
||||
if (bean instanceof Aware) {
|
||||
if (bean instanceof BeanNameAware) {
|
||||
((BeanNameAware) bean).setBeanName(beanName);
|
||||
if (bean instanceof BeanNameAware beanNameAware) {
|
||||
beanNameAware.setBeanName(beanName);
|
||||
}
|
||||
if (bean instanceof BeanClassLoaderAware) {
|
||||
if (bean instanceof BeanClassLoaderAware beanClassLoaderAware) {
|
||||
ClassLoader bcl = getBeanClassLoader();
|
||||
if (bcl != null) {
|
||||
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
|
||||
beanClassLoaderAware.setBeanClassLoader(bcl);
|
||||
}
|
||||
}
|
||||
if (bean instanceof BeanFactoryAware) {
|
||||
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
|
||||
if (bean instanceof BeanFactoryAware beanFactoryAware) {
|
||||
beanFactoryAware.setBeanFactory(AbstractAutowireCapableBeanFactory.this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
-8
@@ -232,11 +232,14 @@ class ConstructorResolver {
|
||||
Class<?>[] paramTypes = candidate.getParameterTypes();
|
||||
if (resolvedValues != null) {
|
||||
try {
|
||||
String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
|
||||
if (paramNames == null) {
|
||||
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
|
||||
if (pnd != null) {
|
||||
paramNames = pnd.getParameterNames(candidate);
|
||||
String[] paramNames = null;
|
||||
if (resolvedValues.containsNamedArgument()) {
|
||||
paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
|
||||
if (paramNames == null) {
|
||||
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
|
||||
if (pnd != null) {
|
||||
paramNames = pnd.getParameterNames(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
|
||||
@@ -536,9 +539,11 @@ class ConstructorResolver {
|
||||
// Resolved constructor arguments: type conversion and/or autowiring necessary.
|
||||
try {
|
||||
String[] paramNames = null;
|
||||
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
|
||||
if (pnd != null) {
|
||||
paramNames = pnd.getParameterNames(candidate);
|
||||
if (resolvedValues != null && resolvedValues.containsNamedArgument()) {
|
||||
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
|
||||
if (pnd != null) {
|
||||
paramNames = pnd.getParameterNames(candidate);
|
||||
}
|
||||
}
|
||||
argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw,
|
||||
paramTypes, paramNames, candidate, autowiring, candidates.size() == 1);
|
||||
|
||||
+5
-5
@@ -1342,11 +1342,11 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
|
||||
Class<?> type = descriptor.getDependencyType();
|
||||
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
|
||||
if (value != null) {
|
||||
if (value instanceof String) {
|
||||
String strVal = resolveEmbeddedValue((String) value);
|
||||
if (value instanceof String strValue) {
|
||||
String resolvedValue = resolveEmbeddedValue(strValue);
|
||||
BeanDefinition bd = (beanName != null && containsBean(beanName) ?
|
||||
getMergedBeanDefinition(beanName) : null);
|
||||
value = evaluateBeanDefinitionString(strVal, bd);
|
||||
value = evaluateBeanDefinitionString(resolvedValue, bd);
|
||||
}
|
||||
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
|
||||
try {
|
||||
@@ -2125,11 +2125,11 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
|
||||
return resolveStream(true);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
private Stream<Object> resolveStream(boolean ordered) {
|
||||
DependencyDescriptor descriptorToUse = new StreamDependencyDescriptor(this.descriptor, ordered);
|
||||
Object result = doResolveDependency(descriptorToUse, this.beanName, null, null);
|
||||
return (result instanceof Stream ? (Stream<Object>) result : Stream.of(result));
|
||||
return (result instanceof Stream stream ? stream : Stream.of(result));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -75,7 +75,7 @@ public interface InstanceSupplier<T> extends ThrowingSupplier<T> {
|
||||
default <V> InstanceSupplier<V> andThen(
|
||||
ThrowingBiFunction<RegisteredBean, ? super T, ? extends V> after) {
|
||||
Assert.notNull(after, "'after' function must not be null");
|
||||
return new InstanceSupplier<V>() {
|
||||
return new InstanceSupplier<>() {
|
||||
|
||||
@Override
|
||||
public V get(RegisteredBean registeredBean) throws Exception {
|
||||
@@ -119,7 +119,7 @@ public interface InstanceSupplier<T> extends ThrowingSupplier<T> {
|
||||
&& instanceSupplier.getFactoryMethod() == factoryMethod) {
|
||||
return instanceSupplier;
|
||||
}
|
||||
return new InstanceSupplier<T>() {
|
||||
return new InstanceSupplier<>() {
|
||||
|
||||
@Override
|
||||
public T get(RegisteredBean registeredBean) throws Exception {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user