Prior to this commit, ObjectToObjectConverter considered the return
type of non-static `to[targetType.simpleName]()` methods but did not
consider the return type of static `valueOf(sourceType)`,
`of(sourceType)`, and `from(sourceType)` methods.
This led to scenarios in which `canConvert()` returned `true`, but a
subsequent `convert()` invocation resulted in a
ConverterNotFoundException, which violates the contract of the
converter.
This commit addresses this issue by taking into account the return type
of a static valueOf/of/from factory method when determining if the
ObjectToObjectConverter supports a particular conversion. Whereas the
existing check in `determineToMethod()` ensures that the method return
type is assignable to the `targetType`, the new check in
`determineFactoryMethod()` leniently ensures that the method return
type and `targetType` are "related" (i.e., reside in the same type
hierarchy).
Closes gh-28609
Support reflection-based serialization of parameters annotated
with @RequestBody and return values annotated with @ResponseBody.
It leverages a new BindingReflectionHintsRegistrar class that
is designed to register transitively the types usually needed
for binding and reflection-based serialization on fields,
constructors and properties. Generics are taken in account
as well.
Closes gh-28518
The `RuntimeHints` API allows to describe hints for the reflection,
proxies and resources behavior at runtime. The need for a particular
behavior can be covered by several types of hints, at different levels.
This knowledge can be important in several cases:
* before contributing additional hints, infrastructure can check if an
existing hint already covers the behavior
* this can be used in test suites and test infrastructure
This commit adds a new RuntimeHintsPredicates that generates `Predicate`
instances for testing `RuntimeHints` against a desired runtime behavior
for reflection, resources or proxies.
Closes gh-28555
Update `ApplicationContextAotGenerator` so that it can generate class
names based on a `target` class and using the ID of the application
context. Prior to this commit, the generated class name was always
`__.BeanFactoryRegistrations`.
Closes gh-28565
To avoid unnecessary eager initialization of DataSize.PATTERN, this
commit initializes it lazily in the first invocation of DataSize.parse
by moving PATTERN to a private static nested class.
Closes gh-28560
This commit adds a central utility to figure out if the application
must run with Ahead-Of-Time optimizations. This is mandatory for running
in a native image but can be selected on the JVM using the
"spring.aot.enabled" property.
This commit also introduces a utility that can be used to initialize a
context with generated artifacts. This represents the runtime
counterpart of ApplicationContextAotGenerator.
Closes gh-28474
Prior to this commit, the hints conditions were only supported for the
`TypeHint` case. GraalVM generally expanded this concept to all hints
and we should do the same.
Right now, only the `typeReachable` condition is available but we should
design for possible future additions.
This commit introduces a new `ConditionalHint` contract implemented by
all hints compatible with this approach. The condition information is
also used in all configuration writers as a result.
Closes gh-28126
This commit makes sure that CoroutinesUtils::invokeSuspendingFunction
treats Reactive Publisher instances the same as Kotlin Flows, i.e.
it flatmaps them.
Closes gh-27011
Attempting to name a variable in an "instanceof pattern" the same as
a field results in a Checkstyle violation similar to the following if
the "instanceof pattern matching" is located within a constructor.
Reference to instance variable 'document' needs "this.". [RequireThis]
See gh-28188
Update `RuntimeHintsUtils` to skip `@Reflective` annotations when
checking for `@AliasFor`. Since the `@Reflective` annotation is only
used at AOT processing time, we shouldn't need a hint for it.
See gh-28528
Prior to this commit, searching for classpath resources using the
"classpath*:" resource prefix did not find all applicable resources for
applications deployed as modules -- for example, when test classes and
resources are patched into the application module automatically by
Maven Surefire.
This affected component scanning -- for example, via [@]ComponentScan --
and PathMatchingResourcePatternResolver.getResources(String) in
general.
This commit addresses this by introducing first-class support for
scanning the module path when PathMatchingResourcePatternResolver's
getResources(String) method is invoked with a location pattern using
the "classpath*:" resource prefix. Specifically, getResources(String)
first searches all modules in the boot layer, excluding system modules.
It then searches the classpath using the existing Classloader-based
algorithm and returns the combined results.
Closes gh-28506
UrlResource constructors throw checked exceptions which makes it
difficult to use them in java.util.Stream and java.util.Optional APIs
or other scenarios when a checked IOException is undesirable.
To support such use cases, this commit introduces `from(URI)` and
`from(String)` factory methods in UrlResource that throw
UncheckedIOExceptions.
Closes gh-28501
This commit improves registerAnnotation to also registers the meta
annotation sources, if any. Without them, the annotation could not
be fully resolved.
See gh-28497
This commit adds a `@Reflective` annotation that can be used to declare
that the annotated element requires reflection at runtime. By default,
the annotated element is exposed but this can be customized by
specifying a dedicated `ReflectiveProcessor`.
Closes gh-28469
This commit adds a utility that takes care of registering the necessary
hints to make an annotation visible at runtime. The core framework may
create a JDK proxy if necessary, which requires specific handling.
Closes gh-28497
This commit forces the resolution of all declared constructors when
registering `RuntimeHints` for Spring factories. Resolving constructors
can throw additional `NoClassDefFoundError` at runtime and during native
image compilation, if a type exposed by the constructor is missing from
the current classloader.
See gh-27955
Update `SpringFactoriesLoader` so that `null` is never used for the
cache key. Prior to this commit, calling `forDefaultResourceLocation`
with `null` and `ClassUtils.getDefaultClassLoader()` would provide
different `SpringFactoriesLoader` instances rather than making use
of a single shared cached instance.
See gh-28416
Add `GeneratedMethods` and `GeneratedMethod` support classes which
can be used during code generation to generation additional methods
that will ultimately be included in a `JavaFile`.
See gh-28414
Add a `GeneratedFiles` interface that can be used to add generated
source, class and resource files. An in-memory implementation is
provided for testing and a filesystem implementation is provided
to actually save the files to disk.
See gh-28414
Add 'Throwable' variants of the `Consumer`, `Function`, `BiFunction` and
`Supplier` interfaces that wrap checked exceptions or allow calls to be
made that throw them.
Closes gh-28417
Update `SpringFactoriesLoader` so that it can load files from
arbitrary locations. An instance of the loader class itself is now
returned from static factory methods that accept different
locations.
The recent `ArgumentResolver` and `FailureHandler` `loadFactories`
variants are now no longer available as static methods. They are
still available as instance methods.
The `loadFactories` static method remains to provide
back-compatibility with Spring Framework 5.x
See gh-28416
This commit adds a `getName` to `TypeReference` that provides a way to
generate the reflection target name of a type. This typically handle
primitives (omitting the `java.lang` packages) and arrays.
Closes gh-28347
Prior to this commit, we could only contribute `RuntimeHints` through
two mechanisms:
* `AotContributingBeanFactoryPostProcessor`, consdering the entire
`BeanFactory` and designed for contributing both code and hints.
* `AotContributingBeanPostProcessor`, consdering beans one by one, but
also designed for contributing both code and hints.
There are cases where libraries and applications want to contribute
`RuntimeHints` only, in a more static fashion: a dependency being
present, or a piece of infrastructure being considered by the
application context are good enough signals to contribute hints about
resources or reflection.
This commit adds the `RuntimeHintsRegistrar` contract for these cases.
Implementations can be declared as `spring.factories` and they will be
processed as soon as they're detected on the classpath. They can also be
declared with `@ImportRuntimeHints` and they will be processed if the
annotated bean definition is considered in the application context.
This annotation should be mainly used on configuration classes and on
bean methods.
```
@Configuration
@ImportRuntimeHints(CustomRuntimeHintsRegistrar.class)
public class MyConfiguration {
@Bean
@ImportRuntimeHints(OtherRuntimeHintsRegistrar.class)
public MyBean myBean() {
//...
}
}
```
Closes gh-28160
Previously, Graal failed to build a native image as DataSize was
unintentionally initialized at build time. This commit workarounds the
faulty assumption by flagging it as safe to initialize at build-time.
Closes gh-28328
This commit updates BasicJsonWriter to handle TypeReferences and
generate an appropriate format for a class name. Specifically, an
inner class should be separated by a dollar sign, not a dot.
Closes gh-28312
Prior to this commit, the `AntPathMatcher` would inconsistently match
pattern with trailing slashes if they contain `"**"` within their
pattern.
For example `"/en/test/"` would match `"/**/test"`, but it would not
match `"/*/test"` (as it should).
This commit fixes this behavior for better consistency.
Fixes gh-27506
Since SerializationUtils#deserialize is based on Java's serialization
mechanism, it can be the source of Remote Code Execution (RCE)
vulnerabilities.
Closes gh-28075
This commit removes the deprecated TYPE_HIERARCHY_AND_ENCLOSING_CLASSES
search strategy from the MergedAnnotations model.
As a direct replacement for the TYPE_HIERARCHY_AND_ENCLOSING_CLASSES
search strategy, users can use the new fluent search API as follows.
MergedAnnotations mergedAnnotations =
MergedAnnotations.search(TYPE_HIERARCHY)
.withEnclosingClasses(clazz -> true) // always search enclosing classes
.from(MyClass.class);
Note, however, that users are highly encouraged to use
ClassUtils::isInnerClass, ClassUtils::isStaticClass, or a custom
predicate other than `clazz -> true`.
Closes gh-28080
Due to the deprecation of the TYPE_HIERARCHY_AND_ENCLOSING_CLASSES
search strategy (see gh-28079), this commit introduces a way for users
to provide a Predicate<Class<?>> that is used to decide when the
enclosing class for the class supplied to the predicate should be
searched.
This gives the user complete control over the "enclosing classes"
aspect of the search algorithm in MergedAnnotations.
- To achieve the same behavior as TYPE_HIERARCHY_AND_ENCLOSING_CLASSES,
a user can provide `clazz -> true` as the predicate.
- To limit the enclosing class search to inner classes, a user can
provide `ClassUtils::isInnerClass` as the predicate.
- To limit the enclosing class search to static nested classes, a user
can provide `ClassUtils::isStaticClass` as the predicate.
- For more advanced use cases, the user can provide a custom predicate.
For example, the following performs a search on MyInnerClass within the
entire type hierarchy and enclosing class hierarchy of that class.
MergedAnnotations mergedAnnotations =
MergedAnnotations.search(TYPE_HIERARCHY)
.withEnclosingClasses(ClassUtils::isInnerClass)
.from(MyInnerClass.class);
In addition, TestContextAnnotationUtils in spring-test has been
revised to use this new feature where feasible.
Closes gh-28207
Prior to this commit, searching for merged annotations on an
AnnotatedElement in the MergedAnnotations model was only supported via
various overloaded from(...) factory methods. In addition, it was not
possible to provide a custom AnnotationFilter without providing an
instance of RepeatableContainers.
This commit introduces a fluent API for searches in MergedAnnotations
to address these issues and improve the programming model for users of
MergedAnnotations.
To begin a search, invoke MergedAnnotations.search(SearchStrategy) with
the desired search strategy. Optional configuration can then be
provided via one of the with(...) methods. To perform a search, invoke
from(AnnotatedElement), supplying the element from which to begin the
search -- for example, a Class or a Method.
For example, the following performs a search on MyClass within the
entire type hierarchy of that class while ignoring repeatable
annotations.
MergedAnnotations mergedAnnotations =
MergedAnnotations.search(SearchStrategy.TYPE_HIERARCHY)
.withRepeatableContainers(RepeatableContainers.none())
.from(MyClass.class);
To reuse search configuration to perform the same type of search on
multiple elements, you can save the Search instance as demonstrated in
the following example.
Search search = MergedAnnotations.search(SearchStrategy.TYPE_HIERARCHY)
.withRepeatableContainers(RepeatableContainers.none());
MergedAnnotations mergedAnnotations = search.from(MyClass.class);
// do something with the MergedAnnotations for MyClass
mergedAnnotations = search.from(AnotherClass.class);
// do something with the MergedAnnotations for AnotherClass
In addition, this fluent search API paves the way for introducing
support for a predicate that controls the search on enclosing classes
(gh-28207) and subsequently for completely removing the
TYPE_HIERARCHY_AND_ENCLOSING_CLASSES search strategy (gh-28080).
Closes gh-28208
The impetus for this is to be able to use ClassUtils::isStaticClass
or the existing ClassUtils::isInnerClass as a method reference for
class-based predicates that need to differentiate between static
nested types and inner classes.
See gh-28207
This commit removes Spring's custom NestedIOException and replaces its
usage with the standard IOException which has supported a root cause
since Java 6.
Closes gh-28198
With a Java 8 baseline in place for quite some time now, it no longer
makes sense to refer to features such as annotations as "Java 5
annotations".
This commit also removes old `Tiger*Tests` classes, thereby avoiding
duplicate execution of various tests.
This commit deprecates the TYPE_HIERARCHY_AND_ENCLOSING_CLASSES search
strategy for MergedAnnotations in 6.0 M3, allowing consumers of 6.0
milestones and release candidates to provide feedback before
potentially completely removing the search strategy or providing an
alternate mechanism for achieving the same goal prior to 6.0 GA.
Closes gh-28079
See gh-28080
This commit adds a warning to the Javadoc for the
TYPE_HIERARCHY_AND_ENCLOSING_CLASSES search strategy in
MergedAnnotations with regard to the scope of the search
algorithm.
See gh-28079
This commit implements 4 package private Json serializers
for JavaSerializationHints, ProxyHints, ReflectionHints
and ResourceHints to serialize GraalVM native JSON configuration
as documented in
https://www.graalvm.org/22.0/reference-manual/native-image/BuildConfiguration/.
It exposes the related functionality via
NativeConfigurationGenerator which allows to generate the
relevant files on the filesystem via the
FileNativeConfigurationGenerator implementation.
The generated *-config.json files have been validated working
with GraalVM 22.0.
Closes gh-27991
Add an additional `FactoryInstantiationFailureHandler` strategy
interface to `SpringFactoriesLoader` to allows instantiation
failures to be handled on a per-factory bases.
For example, to log trace messages for only factories that can't
be created the following can be used:
FactoryInstantiationFailureHandler.logging(logger);
If no `FactoryInstantiationFailureHandler` instance is supplied
then `FactoryInstantiationFailureHandler.throwing()` is used
which provides back-compatible behavior by throwing an
`IllegalArgumentException`.
See gh-28057
Co-authored-by: Madhura Bhave <bhavem@vmware.com>
Co-authored-by: Andy Wilkinson <wilkinsona@vmware.com>
Update `SpringFactoriesLoader` so that factory implementation classes
can have a constructor with arguments that are resolved dynamically.
Arguments are resolved using a `ArgumentResolver` interface that is
passed to the `loadFactories` method. This strategy interface is
intentionally simple and only allows resolution based on the argument
type. A number of convenience methods are provided to allow resolvers
to be built. For example:
ArgumentResolver.of(String.class, "tests")
.and(Integer.class, 123);
Factory implementation classes must have a non-ambiguous constructor
in order to be instantiated. The `SpringFactoriesLoader` uses the same
algorithm as `BeanUtils.getResolvableConstructor`.
See gh-28057
Co-authored-by: Madhura Bhave <bhavem@vmware.com>
Co-authored-by: Andy Wilkinson <wilkinsona@vmware.com>
This commit fixes the algorithm used to analyze a generic parameter. If
a type in the generic signature is protected, the type is return rather
than the full signature. This makes sure that the appropriate package
is used. Previously, it would have incorrectly used the type of the
raw class.
Using a generic type for such a use case is wrong, and ProtectedElement
has been updated to expose a `Class` rather than a `ResolvableType`.
See gh-28030
This commit adds an infrastructure for code that generate types with the
need to write to another package if privileged access is required. An
abstraction around types where methods can be easily added is also
available as part of this commit.
Closes gh-28149