Spring 包扫描

这是入口

public class BeanScannerConfigurer implements BeanFactoryPostProcessor, ApplicationListener<ContextRefreshedEvent> {
    private Scanner scanner;

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        scanner = new Scanner((BeanDefinitionRegistry) beanFactory);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            scanner.setResourceLoader(event.getApplicationContext());
            scanner.scan("com.hieip");
        }
    }
}
这是扫描器主体

public final class Scanner extends ClassPathBeanDefinitionScanner {
    public Scanner(BeanDefinitionRegistry registry) {
        super(registry);
    }

    public void registerDefaultFilters() {
        this.addIncludeFilter(new AnnotationTypeFilter(Component.class));
    }

    public Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Assert.notEmpty(basePackages, "At least one base package must be specified");
        Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
        for (String basePackage : basePackages) {
            Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
            for (BeanDefinition candidate : candidates) {
//                candidate.hasAttribute()
                //todo 实现是否属于该注解
                Class<?> clazz = null;
                String beanClassName = candidate.getBeanClassName();
                try {
                    clazz = Class.forName(beanClassName);//反射生成对象
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                Method[] methods = clazz.getMethods();//获取方法
                for (Method method: methods
                     ) {
                    Annotation annotation = method.getAnnotation(AuthAnnotation.class);//获取权限注解
                    if(null!=annotation){//判断是否有注解
                        String beanName = beanClassName.substring(beanClassName.lastIndexOf(".")+1);
                        beanDefinitions.add(new BeanDefinitionHolder(candidate,beanName));//生成返回对象
                    }
                }
            }
        }
        return beanDefinitions;
    }

    public boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return super.isCandidateComponent(beanDefinition) && beanDefinition.getMetadata()
                .hasAnnotation(Service.class.getName());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值