Fredrik Rambris
Fredrik Rambris

Reputation: 356

How do I get the annotated class from a Condition

I have implemented a Condition that checks if the AnnotatedTypeMetadata supplied in matches is an instance of AnnotationMetadataReadingVisitor and then checks if cron.[className.makePretty()] is set in config. This has allowed me to do stuff like:

@Condition(TaskConditional.class)
public class DoImportantStuffTask {
  @Scheduled(cron = "${cron.do-important-stuff}")
  public void run() {
  ...

and have that only be instanciated when 'cron.do-important-stuff' is set in config. The condition also checks if cron.enabled is true and if cron.host is set and equal to current hostname.

The documentation for Spring 5.2 states:

As of Spring Framework 5.2, this class has been replaced by SimpleAnnotationMetadataReadingVisitor for internal use within the framework, but there is no public replacement for AnnotationMetadataReadingVisitor

Is there a way to still get the name of the annotated class (DoImportantStuffTask.class) in my condition's match method with Spring 5.2?

Upvotes: 0

Views: 1053

Answers (1)

Fredrik Rambris
Fredrik Rambris

Reputation: 356

You now can get the source of the annotations with getAnnotations() in AnnotatedTypeMetadata. And thus to get the class name I did

String annotatedClasss = md.getAnnotations().stream()
    .map(a -> a.getSource().toString())
    .distinct()
    .findAny();

Upvotes: 5

Related Questions