这是入口
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()); } }