Interface MergedAnnotations

All Superinterfaces:

public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>>
Provides access to a collection of merged annotations, usually obtained from a source such as a Class or Method.

Each merged annotation represents a view where the attribute values may be "merged" from different source values, typically:

  • Explicit and Implicit @AliasFor declarations on one or more attributes within the annotation
  • Explicit @AliasFor declarations for a meta-annotation
  • Convention based attribute aliases for a meta-annotation
  • From a meta-annotation declaration

For example, a @PostMapping annotation might be defined as follows:

 @RequestMapping(method = RequestMethod.POST)
 public @interface PostMapping {

     @AliasFor(attribute = "path")
     String[] value() default {};

     @AliasFor(attribute = "value")
     String[] path() default {};

If a method is annotated with @PostMapping("/home") it will contain merged annotations for both @PostMapping and the meta-annotation @RequestMapping. The merged view of the @RequestMapping annotation will contain the following attributes:

Name Value Source
value "/home" Declared in @PostMapping
path "/home" Explicit @AliasFor
method RequestMethod.POST Declared in meta-annotation

MergedAnnotations can be obtained from any Java AnnotatedElement. They may also be used for sources that don't use reflection (such as those that directly parse bytecode).

Different search strategies can be used to locate related source elements that contain the annotations to be aggregated. For example, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY will search both superclasses and implemented interfaces.

From a MergedAnnotations instance you can either get a single annotation, or stream all annotations or just those that match a specific type. You can also quickly tell if an annotation is present.

Here are some typical examples:

 // is an annotation present or meta-present?

 // get the merged "value" attribute of ExampleAnnotation (either directly or
 // meta-present)

 // get all meta-annotations but no directly present annotations;

 // get all ExampleAnnotation declarations (including any meta-annotations) and
 // print the merged "value" attributes
     .map(mergedAnnotation -> mergedAnnotation.getString("value"))

NOTE: The MergedAnnotations API and its underlying model have been designed for composable annotations in Spring's common component model, with a focus on attribute aliasing and meta-annotation relationships. There is no support for retrieving plain Java annotations with this API; please use standard Java reflection or Spring's AnnotationUtils for simple annotation retrieval purposes.

Phillip Webb, Sam Brannen
See Also: