org.springframework.beans.factory.support.BeanNameGenerator源码实例Demo

类org.springframework.beans.factory.support.BeanNameGenerator源码实例Demo

下面列出了org.springframework.beans.factory.support.BeanNameGenerator 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * 默认注册
 * @param pluginId 插件id
 * @param suffixName bean 后缀名称
 * @param aClass 注册的类
 * @param consumer 自定义处理AnnotatedGenericBeanDefinition
 * @return 注册的bean名称
 */
public String register(String pluginId, String suffixName, Class<?> aClass,
                       Consumer<AnnotatedGenericBeanDefinition> consumer) {
    AnnotatedGenericBeanDefinition beanDefinition = new
            AnnotatedGenericBeanDefinition(aClass);

    BeanNameGenerator beanNameGenerator =
            new PluginAnnotationBeanNameGenerator(suffixName);
    String beanName = beanNameGenerator.generateBeanName(beanDefinition, applicationContext);
    if(PluginInfoContainer.existRegisterBeanName((beanName))){
        String error = MessageFormat.format("Bean name {0} already exist of {1}",
                beanName, aClass.getName());
        logger.error(error);
        return null;
    }
    if(consumer != null){
        consumer.accept(beanDefinition);
    }
    applicationContext.registerBeanDefinition(beanName, beanDefinition);
    PluginInfoContainer.addRegisterBeanName(pluginId, beanName);
    return beanName;
}
 
private void registerBeanDefinitions(BeanDefinitionRegistry registry, String[] basePackages) {

        ExposingClassPathBeanDefinitionScanner scanner = new ExposingClassPathBeanDefinitionScanner(registry, false,
                getEnvironment(), getResourceLoader());

        BeanNameGenerator beanNameGenerator = resolveAnnotatedBeanNameGenerator(registry);
        // Set the BeanNameGenerator
        scanner.setBeanNameGenerator(beanNameGenerator);
        // Add the AnnotationTypeFilter for annotationTypes
        for (Class<? extends Annotation> supportedAnnotationType : getSupportedAnnotationTypes()) {
            scanner.addIncludeFilter(new AnnotationTypeFilter(supportedAnnotationType));
        }
        // Register the primary BeanDefinitions
        Map<String, AnnotatedBeanDefinition> primaryBeanDefinitions = registerPrimaryBeanDefinitions(scanner, basePackages);
        // Register the secondary BeanDefinitions
        registerSecondaryBeanDefinitions(scanner, primaryBeanDefinitions, basePackages);
    }
 
private ApplicationContext createContext(ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setBeanNameGenerator(new BeanNameGenerator() {
		@Override
		public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
			return definition.getScope();
		}
	});
	scanner.setScopedProxyMode(scopedProxyMode);

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.refresh();
	return context;
}
 
/**
 * Create a new {@link ConfigurationClassParser} instance that will be used
 * to populate the set of configuration classes.
 */
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
		ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

	this.metadataReaderFactory = metadataReaderFactory;
	this.problemReporter = problemReporter;
	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.registry = registry;
	this.componentScanParser = new ComponentScanAnnotationParser(
			environment, resourceLoader, componentScanBeanNameGenerator, registry);
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
public ComponentScanAnnotationParser(Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator beanNameGenerator, BeanDefinitionRegistry registry) {

	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.beanNameGenerator = beanNameGenerator;
	this.registry = registry;
}
 
protected void parseBeanNameGenerator(Element element, ClassPathBeanDefinitionScanner scanner) {
	if (element.hasAttribute(NAME_GENERATOR_ATTRIBUTE)) {
		BeanNameGenerator beanNameGenerator = (BeanNameGenerator) instantiateUserDefinedStrategy(
				element.getAttribute(NAME_GENERATOR_ATTRIBUTE), BeanNameGenerator.class,
				scanner.getResourceLoader().getClassLoader());
		scanner.setBeanNameGenerator(beanNameGenerator);
	}
}
 
/**
 * Create a new {@link ConfigurationClassBeanDefinitionReader} instance
 * that will be used to populate the given {@link BeanDefinitionRegistry}.
 */
ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
		ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator,
		ImportRegistry importRegistry) {

	this.registry = registry;
	this.sourceExtractor = sourceExtractor;
	this.resourceLoader = resourceLoader;
	this.environment = environment;
	this.importBeanNameGenerator = importBeanNameGenerator;
	this.importRegistry = importRegistry;
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
@Override
public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception {
    if(!mybatisExist()){
        return;
    }
    List<Class<?>> groupClasses = pluginRegistryInfo.getGroupClasses(PluginMapperGroup.KEY);
    if(groupClasses == null || groupClasses.isEmpty()){
        return;
    }
    BasePlugin basePlugin = pluginRegistryInfo.getBasePlugin();
    String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId();
    Set<String> beanNames = new HashSet<>();
    for (Class<?> groupClass : groupClasses) {
        if (groupClass == null) {
            continue;
        }
        BeanNameGenerator beanNameGenerator = new PluginAnnotationBeanNameGenerator(basePlugin.getWrapper().getPluginId());
        AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(groupClass);
        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
        abd.setScope(scopeMetadata.getScopeName());
        String beanName = beanNameGenerator.generateBeanName(abd, applicationContext);
        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
        AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
        BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, applicationContext);
        mybatisInjectWrapper.processBeanDefinitions(definitionHolder, groupClass);
        beanNames.add(beanName);
        PluginInfoContainer.addRegisterBeanName(pluginId, beanName);
    }
    pluginRegistryInfo.addProcessorInfo(KEY, beanNames);
}
 
/**
 * Create a new {@link ConfigurationClassParser} instance that will be used
 * to populate the set of configuration classes.
 */
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
		ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

	this.metadataReaderFactory = metadataReaderFactory;
	this.problemReporter = problemReporter;
	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.registry = registry;
	this.componentScanParser = new ComponentScanAnnotationParser(
			environment, resourceLoader, componentScanBeanNameGenerator, registry);
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
public ComponentScanAnnotationParser(Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator beanNameGenerator, BeanDefinitionRegistry registry) {

	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.beanNameGenerator = beanNameGenerator;
	this.registry = registry;
}
 
protected void parseBeanNameGenerator(Element element, ClassPathBeanDefinitionScanner scanner) {
	if (element.hasAttribute(NAME_GENERATOR_ATTRIBUTE)) {
		BeanNameGenerator beanNameGenerator = (BeanNameGenerator) instantiateUserDefinedStrategy(
				element.getAttribute(NAME_GENERATOR_ATTRIBUTE), BeanNameGenerator.class,
				scanner.getResourceLoader().getClassLoader());
		scanner.setBeanNameGenerator(beanNameGenerator);
	}
}
 
/**
 * Create a new {@link ConfigurationClassBeanDefinitionReader} instance
 * that will be used to populate the given {@link BeanDefinitionRegistry}.
 */
ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
		ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator,
		ImportRegistry importRegistry) {

	this.registry = registry;
	this.sourceExtractor = sourceExtractor;
	this.resourceLoader = resourceLoader;
	this.environment = environment;
	this.importBeanNameGenerator = importBeanNameGenerator;
	this.importRegistry = importRegistry;
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
源代码13 项目: lams   文件: ConfigurationClassParser.java
/**
 * Create a new {@link ConfigurationClassParser} instance that will be used
 * to populate the set of configuration classes.
 */
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
		ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

	this.metadataReaderFactory = metadataReaderFactory;
	this.problemReporter = problemReporter;
	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.registry = registry;
	this.componentScanParser = new ComponentScanAnnotationParser(
			environment, resourceLoader, componentScanBeanNameGenerator, registry);
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
源代码14 项目: lams   文件: ComponentScanAnnotationParser.java
public ComponentScanAnnotationParser(Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator beanNameGenerator, BeanDefinitionRegistry registry) {

	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.beanNameGenerator = beanNameGenerator;
	this.registry = registry;
}
 
源代码15 项目: lams   文件: ComponentScanBeanDefinitionParser.java
protected void parseBeanNameGenerator(Element element, ClassPathBeanDefinitionScanner scanner) {
	if (element.hasAttribute(NAME_GENERATOR_ATTRIBUTE)) {
		BeanNameGenerator beanNameGenerator = (BeanNameGenerator) instantiateUserDefinedStrategy(
				element.getAttribute(NAME_GENERATOR_ATTRIBUTE), BeanNameGenerator.class,
				scanner.getResourceLoader().getClassLoader());
		scanner.setBeanNameGenerator(beanNameGenerator);
	}
}
 
/**
 * Create a new {@link ConfigurationClassBeanDefinitionReader} instance that will be used
 * to populate the given {@link BeanDefinitionRegistry}.
 */
ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
		ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator,
		ImportRegistry importRegistry) {

	this.registry = registry;
	this.sourceExtractor = sourceExtractor;
	this.resourceLoader = resourceLoader;
	this.environment = environment;
	this.importBeanNameGenerator = importBeanNameGenerator;
	this.importRegistry = importRegistry;
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
/**
 * Create a new {@link ConfigurationClassParser} instance that will be used
 * to populate the set of configuration classes.
 */
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
		ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
		BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

	this.metadataReaderFactory = metadataReaderFactory;
	this.problemReporter = problemReporter;
	this.environment = environment;
	this.resourceLoader = resourceLoader;
	this.registry = registry;
	this.componentScanParser = new ComponentScanAnnotationParser(
			resourceLoader, environment, componentScanBeanNameGenerator, registry);
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
public ComponentScanAnnotationParser(ResourceLoader resourceLoader, Environment environment,
		BeanNameGenerator beanNameGenerator, BeanDefinitionRegistry registry) {

	this.resourceLoader = resourceLoader;
	this.environment = environment;
	this.beanNameGenerator = beanNameGenerator;
	this.registry = registry;
}
 
protected void parseBeanNameGenerator(Element element, ClassPathBeanDefinitionScanner scanner) {
	if (element.hasAttribute(NAME_GENERATOR_ATTRIBUTE)) {
		BeanNameGenerator beanNameGenerator = (BeanNameGenerator) instantiateUserDefinedStrategy(
				element.getAttribute(NAME_GENERATOR_ATTRIBUTE), BeanNameGenerator.class,
				scanner.getResourceLoader().getClassLoader());
		scanner.setBeanNameGenerator(beanNameGenerator);
	}
}
 
/**
 * Create a new {@link ConfigurationClassBeanDefinitionReader} instance that will be used
 * to populate the given {@link BeanDefinitionRegistry}.
 */
ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
		ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator,
		ImportRegistry importRegistry) {

	this.registry = registry;
	this.sourceExtractor = sourceExtractor;
	this.resourceLoader = resourceLoader;
	this.environment = environment;
	this.importBeanNameGenerator = importBeanNameGenerator;
	this.importRegistry = importRegistry;
	this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
 
private ClassPathBeanDefinitionScannerAgent(ClassPathBeanDefinitionScanner scanner) {
    this.scanner = scanner;

    this.registry = scanner.getRegistry();
    this.scopeMetadataResolver = (ScopeMetadataResolver) ReflectionHelper.get(scanner, "scopeMetadataResolver");
    this.beanNameGenerator = (BeanNameGenerator) ReflectionHelper.get(scanner, "beanNameGenerator");
}
 
/**
     * Registers Beans whose classes was annotated {@link Service} 注册类为带注释服务的bean
     *
     * @param packagesToScan The base packages to scan
     * @param registry       {@link BeanDefinitionRegistry}
     */
    private void registerServiceBeans(Set<String> packagesToScan, BeanDefinitionRegistry registry) {

//        创建dubbo服务类bean定义扫描器
        DubboClassPathBeanDefinitionScanner scanner =
                new DubboClassPathBeanDefinitionScanner(registry, environment, resourceLoader);

//        解析beanName解析器=》
        BeanNameGenerator beanNameGenerator = resolveBeanNameGenerator(registry);

        scanner.setBeanNameGenerator(beanNameGenerator);

//        扫描直接@Service
        scanner.addIncludeFilter(new AnnotationTypeFilter(Service.class));

        for (String packageToScan : packagesToScan) {

            // Registers @Service Bean first 扫描@Service注解的bean=》
            scanner.scan(packageToScan);

            // Finds all BeanDefinitionHolders of @Service whether @ComponentScan scans or not. 查找@ComponentScan指定的包路径下带有@Service的bean的bean定义=》
            Set<BeanDefinitionHolder> beanDefinitionHolders =
                    findServiceBeanDefinitionHolders(scanner, packageToScan, registry, beanNameGenerator);

            if (!CollectionUtils.isEmpty(beanDefinitionHolders)) {

                for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
//                    注册service bean=》
                    registerServiceBean(beanDefinitionHolder, registry, scanner);
                }

                if (logger.isInfoEnabled()) {
                    logger.info(beanDefinitionHolders.size() + " annotated Dubbo's @Service Components { " +
                            beanDefinitionHolders +
                            " } were scanned under package[" + packageToScan + "]");
                }

            } else {

                if (logger.isWarnEnabled()) {
                    logger.warn("No Spring Bean annotating Dubbo's @Service was found under package["
                            + packageToScan + "]");
                }

            }

        }

    }
 
/**
 * Finds a {@link Set} of {@link BeanDefinitionHolder BeanDefinitionHolders} whose bean type annotated
 * {@link Service} Annotation.找到一组beandefinitionholder,其bean类型注释了服务注释。
 *
 * @param scanner       {@link ClassPathBeanDefinitionScanner}
 * @param packageToScan pachage to scan
 * @param registry      {@link BeanDefinitionRegistry}
 * @return non-null
 * @since 2.5.8
 */
private Set<BeanDefinitionHolder> findServiceBeanDefinitionHolders(
        ClassPathBeanDefinitionScanner scanner, String packageToScan, BeanDefinitionRegistry registry,
        BeanNameGenerator beanNameGenerator) {

    Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(packageToScan);

    Set<BeanDefinitionHolder> beanDefinitionHolders = new LinkedHashSet<BeanDefinitionHolder>(beanDefinitions.size());

    for (BeanDefinition beanDefinition : beanDefinitions) {

        String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry);
        BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName);
        beanDefinitionHolders.add(beanDefinitionHolder);

    }

    return beanDefinitionHolders;

}
 
/**
 * Set the BeanNameGenerator to use for detected bean classes.
 * <p>The default is a {@link AnnotationBeanNameGenerator}.
 */
public void setBeanNameGenerator(@Nullable BeanNameGenerator beanNameGenerator) {
	this.beanNameGenerator =
			(beanNameGenerator != null ? beanNameGenerator : AnnotationBeanNameGenerator.INSTANCE);
}
 
/**
 * Set the BeanNameGenerator to use for detected bean classes.
 * <p>Default is a {@link AnnotationBeanNameGenerator}.
 */
public void setBeanNameGenerator(@Nullable BeanNameGenerator beanNameGenerator) {
	this.beanNameGenerator =
			(beanNameGenerator != null ? beanNameGenerator : AnnotationBeanNameGenerator.INSTANCE);
}
 
/**
 * Return the custom {@link BeanNameGenerator} for use with {@link AnnotatedBeanDefinitionReader}
 * and/or {@link ClassPathBeanDefinitionScanner}, if any.
 */
@Nullable
protected BeanNameGenerator getBeanNameGenerator() {
	return this.beanNameGenerator;
}
 
/**
 * Register a {@link org.springframework.beans.factory.config.BeanDefinition} for
 * any classes specified by {@link #register(Class...)} and scan any packages
 * specified by {@link #scan(String...)}.
 * <p>For any values specified by {@link #setConfigLocation(String)} or
 * {@link #setConfigLocations(String[])}, attempt first to load each location as a
 * class, registering a {@code BeanDefinition} if class loading is successful,
 * and if class loading fails (i.e. a {@code ClassNotFoundException} is raised),
 * assume the value is a package and attempt to scan it for annotated classes.
 * <p>Enables the default set of annotation configuration post processors, such that
 * {@code @Autowired}, {@code @Required}, and associated annotations can be used.
 * <p>Configuration class bean definitions are registered with generated bean
 * definition names unless the {@code value} attribute is provided to the stereotype
 * annotation.
 * @param beanFactory the bean factory to load bean definitions into
 * @see #register(Class...)
 * @see #scan(String...)
 * @see #setConfigLocation(String)
 * @see #setConfigLocations(String[])
 * @see AnnotatedBeanDefinitionReader
 * @see ClassPathBeanDefinitionScanner
 */
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
	AnnotatedBeanDefinitionReader reader = getAnnotatedBeanDefinitionReader(beanFactory);
	ClassPathBeanDefinitionScanner scanner = getClassPathBeanDefinitionScanner(beanFactory);

	BeanNameGenerator beanNameGenerator = getBeanNameGenerator();
	if (beanNameGenerator != null) {
		reader.setBeanNameGenerator(beanNameGenerator);
		scanner.setBeanNameGenerator(beanNameGenerator);
		beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
	}

	ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();
	if (scopeMetadataResolver != null) {
		reader.setScopeMetadataResolver(scopeMetadataResolver);
		scanner.setScopeMetadataResolver(scopeMetadataResolver);
	}

	if (!this.annotatedClasses.isEmpty()) {
		if (logger.isDebugEnabled()) {
			logger.debug("Registering annotated classes: [" +
					StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
		}
		reader.register(ClassUtils.toClassArray(this.annotatedClasses));
	}

	if (!this.basePackages.isEmpty()) {
		if (logger.isDebugEnabled()) {
			logger.debug("Scanning base packages: [" +
					StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
		}
		scanner.scan(StringUtils.toStringArray(this.basePackages));
	}

	String[] configLocations = getConfigLocations();
	if (configLocations != null) {
		for (String configLocation : configLocations) {
			try {
				Class<?> clazz = ClassUtils.forName(configLocation, getClassLoader());
				if (logger.isTraceEnabled()) {
					logger.trace("Registering [" + configLocation + "]");
				}
				reader.register(clazz);
			}
			catch (ClassNotFoundException ex) {
				if (logger.isTraceEnabled()) {
					logger.trace("Could not load class for config location [" + configLocation +
							"] - trying package scan. " + ex);
				}
				int count = scanner.scan(configLocation);
				if (count == 0 && logger.isDebugEnabled()) {
					logger.debug("No annotated classes found for specified class/package [" + configLocation + "]");
				}
			}
		}
	}
}
 
/**
 * Finds a {@link Set} of {@link BeanDefinitionHolder BeanDefinitionHolders} whose bean type annotated
 * {@link Service} Annotation.
 *
 * @param scanner       {@link ClassPathBeanDefinitionScanner}
 * @param packageToScan pachage to scan
 * @param registry      {@link BeanDefinitionRegistry}
 * @return non-null
 * @since 2.5.8
 */
private Set<BeanDefinitionHolder> findServiceBeanDefinitionHolders(
        ClassPathBeanDefinitionScanner scanner, String packageToScan, BeanDefinitionRegistry registry,
        BeanNameGenerator beanNameGenerator) {

    Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(packageToScan);

    Set<BeanDefinitionHolder> beanDefinitionHolders = new LinkedHashSet<BeanDefinitionHolder>(beanDefinitions.size());

    for (BeanDefinition beanDefinition : beanDefinitions) {

        String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry);
        BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName);
        beanDefinitionHolders.add(beanDefinitionHolder);

    }

    return beanDefinitionHolders;

}
 
/**
 * Return the custom {@link BeanNameGenerator} for use with {@link AnnotatedBeanDefinitionReader}
 * and/or {@link ClassPathBeanDefinitionScanner}, if any.
 */
@Nullable
protected BeanNameGenerator getBeanNameGenerator() {
	return this.beanNameGenerator;
}
 
/**
 * Register a {@link org.springframework.beans.factory.config.BeanDefinition} for
 * any classes specified by {@link #register(Class...)} and scan any packages
 * specified by {@link #scan(String...)}.
 * <p>For any values specified by {@link #setConfigLocation(String)} or
 * {@link #setConfigLocations(String[])}, attempt first to load each location as a
 * class, registering a {@code BeanDefinition} if class loading is successful,
 * and if class loading fails (i.e. a {@code ClassNotFoundException} is raised),
 * assume the value is a package and attempt to scan it for annotated classes.
 * <p>Enables the default set of annotation configuration post processors, such that
 * {@code @Autowired}, {@code @Required}, and associated annotations can be used.
 * <p>Configuration class bean definitions are registered with generated bean
 * definition names unless the {@code value} attribute is provided to the stereotype
 * annotation.
 * @param beanFactory the bean factory to load bean definitions into
 * @see #register(Class...)
 * @see #scan(String...)
 * @see #setConfigLocation(String)
 * @see #setConfigLocations(String[])
 * @see AnnotatedBeanDefinitionReader
 * @see ClassPathBeanDefinitionScanner
 */
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
	AnnotatedBeanDefinitionReader reader = getAnnotatedBeanDefinitionReader(beanFactory);
	ClassPathBeanDefinitionScanner scanner = getClassPathBeanDefinitionScanner(beanFactory);

	BeanNameGenerator beanNameGenerator = getBeanNameGenerator();
	if (beanNameGenerator != null) {
		reader.setBeanNameGenerator(beanNameGenerator);
		scanner.setBeanNameGenerator(beanNameGenerator);
		beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
	}

	ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();
	if (scopeMetadataResolver != null) {
		reader.setScopeMetadataResolver(scopeMetadataResolver);
		scanner.setScopeMetadataResolver(scopeMetadataResolver);
	}

	if (!this.annotatedClasses.isEmpty()) {
		if (logger.isDebugEnabled()) {
			logger.debug("Registering annotated classes: [" +
					StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
		}
		reader.register(ClassUtils.toClassArray(this.annotatedClasses));
	}

	if (!this.basePackages.isEmpty()) {
		if (logger.isDebugEnabled()) {
			logger.debug("Scanning base packages: [" +
					StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
		}
		scanner.scan(StringUtils.toStringArray(this.basePackages));
	}

	String[] configLocations = getConfigLocations();
	if (configLocations != null) {
		for (String configLocation : configLocations) {
			try {
				Class<?> clazz = ClassUtils.forName(configLocation, getClassLoader());
				if (logger.isTraceEnabled()) {
					logger.trace("Registering [" + configLocation + "]");
				}
				reader.register(clazz);
			}
			catch (ClassNotFoundException ex) {
				if (logger.isTraceEnabled()) {
					logger.trace("Could not load class for config location [" + configLocation +
							"] - trying package scan. " + ex);
				}
				int count = scanner.scan(configLocation);
				if (count == 0 && logger.isDebugEnabled()) {
					logger.debug("No annotated classes found for specified class/package [" + configLocation + "]");
				}
			}
		}
	}
}
 
源代码评论
动弹
沙发等你来抢
 类方法
 同包方法