找到包名 - Spring 引导库

find package name - Spring Boot library

我正在制作一个与 Spring Boot.这个库定义了一些可以在方法中使用的注释。

如何找到(在运行时)正在使用该库的应用程序包?
我需要这个来扫描带注释的方法。

你可以实施BeanFactoryPostProcessor:
1. 使用 ConfigurableListableBeanFactory you can iterate over BeanDefinition
2.确定bean的class是否有你的注解
3.从bean的class名称

获取包

示例:

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Set<String> packages = findAnnotationUsagePackages(MyAnnotation.class, beanFactory);
        ...
    }

    private Set<String> findAnnotationUsagePackages(Class<? extends Annotation> annotationClass,
                                                    ConfigurableListableBeanFactory beanFactory) {
        Set<String> annotationUsagePackages = new HashSet<>();

        for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) {
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);

            if (beanDefinition instanceof ScannedGenericBeanDefinition) {
                ScannedGenericBeanDefinition genericBeanDefinition = (ScannedGenericBeanDefinition) beanDefinition;

                if (AnnotationUtils.isCandidateClass(genericBeanDefinition.getBeanClass(), annotationClass)) {
                    String beanClassName = genericBeanDefinition.getBeanClassName();

                    if (beanClassName != null) {
                        annotationUsagePackages.add(ClassUtils.getPackageName(beanClassName));

                    }
                }
            }
        }
        return annotationUsagePackages;
    }

}

关于AnnotationUtils.isCandidateClass()

Determine whether the given class is a candidate for carrying the specified annotation (at type, method or field level)

另外关注AbstractBeanDefinition.getBeanClass():

Throws: IllegalStateException - if the bean definition does not define a bean class, or a specified bean class name has not been resolved into an actual Class yet

P.S。您还可以在 AnnotationUtils.isCandidateClass 条件块

中收集 类 或元信息