Created
March 5, 2019 20:06
-
-
Save fredlahde/4877c458cbf6de19f9fe4adc2c159e7c to your computer and use it in GitHub Desktop.
Java Annotation Scanning
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package de.fredlahde.demoannotationprocessor; | |
import org.springframework.beans.factory.config.BeanDefinition; | |
import org.springframework.boot.CommandLineRunner; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; | |
import org.springframework.core.type.filter.AnnotationTypeFilter; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
@Retention(RetentionPolicy.RUNTIME) | |
@interface Bar { | |
String getBar(); | |
} | |
@SpringBootApplication | |
public class DemoAnnotationProcessorApplication { | |
public static void main(String[] args) { | |
SpringApplication.run(DemoAnnotationProcessorApplication.class, args); | |
} | |
@Bean | |
public CommandLineRunner clr() { | |
return args -> { | |
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); | |
provider.addIncludeFilter(new AnnotationTypeFilter(Bar.class)); | |
for (BeanDefinition bd : provider.findCandidateComponents("de.fredlahde")) { | |
//noinspection unchecked | |
Class<? extends Bar> cls = (Class<? extends Bar>) getClass().getClassLoader().loadClass(bd.getBeanClassName()); | |
String val = cls.getAnnotation(Bar.class).getBar(); | |
System.out.println(val); | |
} | |
}; | |
} | |
} | |
@Bar(getBar = "foobar") | |
class Foo { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment