(1)继承 SpringFactoryImportSelector,模仿 EnableDiscoveryClientImportSelector(类注解)
(2)实现 BeanPostProcessor,spring所有的bean都过这个接口
(3)实现 ApplicationListener
(4)可以使用 AOP
这里定义一个方法注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface 自定义注解类 {
}
@Component
public class 扫描类 implements ApplicationListener<ApplicationEvent> {
private static final AtomicBoolean START = new AtomicBoolean(false);
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) { // 应用刷新
// 对自定义注解的处理,只进行一次
if (START.compareAndSet(false, true)) {
// 关键代码 try-catch
try {
annotationDetector();
}
catch (Exception e) {
// ignore
}
}
}
}
}
<!-- 注解抓取工具包 -->
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</dependency>
private void annotationDetector() {
//扫描方法注解和类注解(可以添加其他类型的注解)
ConfigurationBuilder builder = new ConfigurationBuilder().useParallelExecutor()
.setUrls(ClasspathHelper.forClassLoader())
.setScanners(new MethodAnnotationsScanner(), new TypeAnnotationsScanner());
Reflections reflections = new Reflections(builder);
Set<Method> methods = reflections.getMethodsAnnotatedWith(自定义注解类.class);
for (Method method : methods) {
annotationFilter(method);
}
}
private void annotationFilter(Method method) {
Class<?> declaringClass = method.getDeclaringClass();
String className = declaringClass.getName();
String methodName = method.getName();
Annotation[] methodAnnotations = method.getAnnotations();
for (Annotation annotation : methodAnnotations) {
if (annotation.annotationType().equals(自定义注解类.class)) {
// 对自定义注解进行解析
}
}
}
https://www.cnblogs.com/bigben0123/p/7779357.html