Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Spring find annotated classes

farenda 2015-08-24 0

Problem:

How to find annotated classes using Spring and read metadata from them? Sometimes you may want to attach metadata to your classes using custom annotations. Here’s an example how you can leverage Spring‘s classpath scanning mechanism to do that.

Solution:

If you use Spring annotations like @Component, @Repository or @Service, then Spring will find such classes, but will make them Spring beans.

Good news is that Spring classpath scanning mechanism is configurable and available in any Spring application. To use custom annotations we have to create an instance of ClassPathScanningCandidateComponentProvider and set appropriate filter – here its AnnotationTypeFilter. It returns BeanDefinitions that contains found class names from which we can get detailed information. The following example makes it clear.

We create our custom annotation that allows us to attach some metatdata:

package com.farenda.java.lang;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// Make the annotation available at runtime:
@Retention(RetentionPolicy.RUNTIME)
// Allow to use only on types:
@Target(ElementType.TYPE)
public @interface Findable {

    /**
     * User friendly name of annotated class.
     */
    String name();
}

Sample classes annotated with the custom annotation:

package com.farenda.java.lang;

@Findable(name = "Find me")
public class FirstAnnotatedClass {
}
package com.farenda.java.lang;

@Findable(name = "Find me too")
public class SecondAnnotatedClass {
}

The Java code below is using ClassPathScanningCandidateComponentProvider to scan classes in com.farenda.java.lang package. The class is provided by spring-context project. Here’s relevant Maven dependency:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.2.0.RELEASE</version>
</dependency>

And the code:

package com.farenda.java.lang;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;

public class SpringClassScanner {

    public static void main(String[] args) throws Exception {
        System.out.println("Finding annotated classes using Spring:");
        new SpringClassScanner().findAnnotatedClasses("com.farenda.java.lang");
    }

    public void findAnnotatedClasses(String scanPackage) {
        ClassPathScanningCandidateComponentProvider provider = createComponentScanner();
        for (BeanDefinition beanDef : provider.findCandidateComponents(scanPackage)) {
            printMetadata(beanDef);
        }
    }

    private ClassPathScanningCandidateComponentProvider createComponentScanner() {
        // Don't pull default filters (@Component, etc.):
        ClassPathScanningCandidateComponentProvider provider
                = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AnnotationTypeFilter(Findable.class));
        return provider;
    }

    private void printMetadata(BeanDefinition beanDef) {
        try {
            Class<?> cl = Class.forName(beanDef.getBeanClassName());
            Findable findable = cl.getAnnotation(Findable.class);
            System.out.printf("Found class: %s, with meta name: %s%n",
                    cl.getSimpleName(), findable.name());
        } catch (Exception e) {
            System.err.println("Got exception: " + e.getMessage());
        }
    }
}

The code is straightforward. The hardest thing is to type and read very long names of Spring classes. ;-)

And here’s the output of running the code:

Finding annotated classes using Spring:
Found class: SecondAnnotatedClass, with meta name: Find me too
Found class: FirstAnnotatedClass, with meta name: Find me

This sort of scanning is very good fit for applications that already use Spring Framework. In the next posts we’ll see solutions for projects that don’t use Spring.

Share with the World!
Categories Spring Framework Tags java, java-lang, spring
Previous: Java reflection annotated fields/methods
Next: Java find annotated classes

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok