Java Code Examples for org.springframework.beans.factory.support.BeanDefinitionRegistry#getBeanDefinitionNames()

The following examples show how to use org.springframework.beans.factory.support.BeanDefinitionRegistry#getBeanDefinitionNames() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TeiidBeanDefinitionPostProcessor.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    ArrayList<String> datasources = new ArrayList<String>();
    BeanDefinition datasourceBeanDefinition = registry.getBeanDefinition("dataSource");
    for (String beanName : registry.getBeanDefinitionNames()) {
        if (beanName.startsWith("org.springframework") || beanName.contentEquals("dataSource")) {
            continue;
        }
        final BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
        if (isMatch(beanDefinition, beanName)) {
            datasources.add(beanName);
        }
    }
    logger.info("Found data sources: " + datasources);
    datasourceBeanDefinition.setDependsOn(datasources.toArray(new String[datasources.size()]));
}
 
Example 2
Source File: XxlConfFactory.java    From xxl-conf with GNU General Public License v3.0 6 votes vote down vote up
/**
 * register beanDefinition If Not Exists
 *
 * @param registry
 * @param beanClass
 * @param beanName
 * @return
 */
public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, Class<?> beanClass, String beanName) {

	// default bean name
	if (beanName == null) {
		beanName = beanClass.getName();
	}

	if (registry.containsBeanDefinition(beanName)) {	// avoid beanName repeat
		return false;
	}

	String[] beanNameArr = registry.getBeanDefinitionNames();
	for (String beanNameItem : beanNameArr) {
		BeanDefinition beanDefinition = registry.getBeanDefinition(beanNameItem);
		if (Objects.equals(beanDefinition.getBeanClassName(), beanClass.getName())) {	// avoid className repeat
			return false;
		}
	}

	BeanDefinition annotationProcessor = BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition();
	registry.registerBeanDefinition(beanName, annotationProcessor);
	return true;
}
 
Example 3
Source File: SeimiCrawlerBeanRegistar.java    From SeimiCrawler with Apache License 2.0 6 votes vote down vote up
private boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, Class<?> beanClass, Object... args) {
    if (registry.containsBeanDefinition(beanClass.getName())) {
        return false;
    }
    String[] candidates = registry.getBeanDefinitionNames();
    for (String candidate : candidates) {
        BeanDefinition beanDefinition = registry.getBeanDefinition(candidate);
        if (Objects.equals(beanDefinition.getBeanClassName(), beanClass.getName())) {
            return false;
        }
    }
    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(beanClass);
    if (args != null && args.length > 0) {
        for (Object arg : args) {
            beanDefinitionBuilder.addConstructorArgValue(arg);
        }
    }
    BeanDefinition annotationProcessor = beanDefinitionBuilder.getBeanDefinition();
    registry.registerBeanDefinition(beanClass.getName(), annotationProcessor);
    return true;
}
 
Example 4
Source File: GenericScope.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
		throws BeansException {
	for (String name : registry.getBeanDefinitionNames()) {
		BeanDefinition definition = registry.getBeanDefinition(name);
		if (definition instanceof RootBeanDefinition) {
			RootBeanDefinition root = (RootBeanDefinition) definition;
			if (root.getDecoratedDefinition() != null && root.hasBeanClass()
					&& root.getBeanClass() == ScopedProxyFactoryBean.class) {
				if (getName().equals(root.getDecoratedDefinition().getBeanDefinition()
						.getScope())) {
					root.setBeanClass(LockedScopedProxyFactoryBean.class);
					root.getConstructorArgumentValues().addGenericArgumentValue(this);
					// surprising that a scoped proxy bean definition is not already
					// marked as synthetic?
					root.setSynthetic(true);
				}
			}
		}
	}
}
 
Example 5
Source File: RefreshAutoConfiguration.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
		throws BeansException {
	bindEnvironmentIfNeeded(registry);
	for (String name : registry.getBeanDefinitionNames()) {
		BeanDefinition definition = registry.getBeanDefinition(name);
		if (isApplicable(registry, name, definition)) {
			BeanDefinitionHolder holder = new BeanDefinitionHolder(definition,
					name);
			BeanDefinitionHolder proxy = ScopedProxyUtils
					.createScopedProxy(holder, registry, true);
			definition.setScope("refresh");
			if (registry.containsBeanDefinition(proxy.getBeanName())) {
				registry.removeBeanDefinition(proxy.getBeanName());
			}
			registry.registerBeanDefinition(proxy.getBeanName(),
					proxy.getBeanDefinition());
		}
	}
}
 
Example 6
Source File: DependsOnDefinitionPostProcessor.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
/**
 * dependsOn操作
 */
protected void doDependsOn(BeanDefinitionRegistry registry) {
    if (onDependsOn.compareAndSet(false, true)) {
        Set<BeanDefinition> consumers = new HashSet<>();
        Set<BeanDefinition> consumerGroups = new HashSet<>();
        Set<BeanDefinition> providers = new HashSet<>();
        Set<String> contextNames = new HashSet<>();
        String[] names = registry.getBeanDefinitionNames();
        for (String name : names) {
            BeanDefinition definition = registry.getBeanDefinition(name);
            String beanClassName = definition.getBeanClassName();
            if (ConsumerBean.class.getName().equals(beanClassName)) {
                consumers.add(definition);
            } else if (ProviderBean.class.getName().equals(beanClassName)) {
                providers.add(definition);
            } else if (ConsumerGroupBean.class.getName().equals(beanClassName)) {
                consumerGroups.add(definition);
            } else if (GlobalParameterBean.class.getName().equals(beanClassName)) {
                contextNames.add(name);
            }
        }
        String[] dependOnNames = contextNames.toArray(new String[0]);
        consumers.forEach(definition -> definition.setDependsOn(dependOnNames));
        consumerGroups.forEach(definition -> definition.setDependsOn(dependOnNames));
        providers.forEach(definition -> definition.setDependsOn(dependOnNames));
    }
}
 
Example 7
Source File: DapengComponentScanRegistrar.java    From dapeng-soa with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    for(String name: registry.getBeanDefinitionNames()){
        BeanDefinition definition = registry.getBeanDefinition(name);
        if(definition instanceof AnnotatedBeanDefinition){
            AnnotationMetadata metadata = ((AnnotatedBeanDefinition) definition).getMetadata();
            if(metadata.hasAnnotation(DapengService.class.getName()) ||
                metadata.hasMetaAnnotation(DapengService.class.getName())){

                Map<String, Object> annotationAtts = metadata.getAnnotationAttributes(DapengService.class.getName());

                if (annotationAtts.containsKey("service")) {
                    char[] realServiceNameAsChars = ((Class)annotationAtts.get("service")).getSimpleName().toCharArray();
                    realServiceNameAsChars[0] += 32;
                    String realServiceName = String.valueOf(realServiceNameAsChars);
                    ConstructorArgumentValues paras = new ConstructorArgumentValues();
                    paras.addIndexedArgumentValue(0, new RuntimeBeanReference(realServiceName));
                    paras.addIndexedArgumentValue(1, realServiceName);

                    RootBeanDefinition serviceDef = new RootBeanDefinition(SoaProcessorFactory.class, paras, null);
                    serviceDef.setScope(BeanDefinition.SCOPE_SINGLETON);
                    serviceDef.setTargetType(SoaServiceDefinition.class);

                    registry.registerBeanDefinition(realServiceName + "-definition", serviceDef);
                }
            }
        }
    }
}
 
Example 8
Source File: DoradoAutoConfiguration.java    From dorado with Apache License 2.0 5 votes vote down vote up
private String[] getSpringBootAppScanPackages() {
	BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext;

	Set<String> packages = new HashSet<>();
	String[] names = registry.getBeanDefinitionNames();
	for (String name : names) {
		BeanDefinition definition = registry.getBeanDefinition(name);
		if (definition instanceof AnnotatedBeanDefinition) {
			AnnotatedBeanDefinition annotatedDefinition = (AnnotatedBeanDefinition) definition;
			addComponentScanningPackages(packages, annotatedDefinition.getMetadata());
		}
	}
	return packages.toArray(new String[] {});
}
 
Example 9
Source File: AnnotatedBeanDefinitionRegistryUtils.java    From spring-context-support with Apache License 2.0 5 votes vote down vote up
/**
 * Is present bean that was registered by the specified {@link Annotation annotated} {@link Class class}
 *
 * @param registry       {@link BeanDefinitionRegistry}
 * @param annotatedClass the {@link Annotation annotated} {@link Class class}
 * @return if present, return <code>true</code>, or <code>false</code>
 * @since 1.0.3
 */
public static boolean isPresentBean(BeanDefinitionRegistry registry, Class<?> annotatedClass) {

    boolean present = false;

    String[] beanNames = registry.getBeanDefinitionNames();

    ClassLoader classLoader = annotatedClass.getClassLoader();

    for (String beanName : beanNames) {
        BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
        if (beanDefinition instanceof AnnotatedBeanDefinition) {
            AnnotationMetadata annotationMetadata = ((AnnotatedBeanDefinition) beanDefinition).getMetadata();
            String className = annotationMetadata.getClassName();
            Class<?> targetClass = resolveClassName(className, classLoader);
            present = nullSafeEquals(targetClass, annotatedClass);
            if (present) {
                if (logger.isDebugEnabled()) {
                    logger.debug(format("The annotatedClass[class : %s , bean name : %s] was present in registry[%s]",
                            className, beanName, registry));
                }
                break;
            }
        }
    }

    return present;
}
 
Example 10
Source File: SpringValueDefinitionProcessor.java    From apollo with Apache License 2.0 5 votes vote down vote up
private void processPropertyValues(BeanDefinitionRegistry beanRegistry) {
  if (!PROPERTY_VALUES_PROCESSED_BEAN_FACTORIES.add(beanRegistry)) {
    // already initialized
    return;
  }

  if (!beanName2SpringValueDefinitions.containsKey(beanRegistry)) {
    beanName2SpringValueDefinitions.put(beanRegistry, LinkedListMultimap.<String, SpringValueDefinition>create());
  }

  Multimap<String, SpringValueDefinition> springValueDefinitions = beanName2SpringValueDefinitions.get(beanRegistry);

  String[] beanNames = beanRegistry.getBeanDefinitionNames();
  for (String beanName : beanNames) {
    BeanDefinition beanDefinition = beanRegistry.getBeanDefinition(beanName);
    MutablePropertyValues mutablePropertyValues = beanDefinition.getPropertyValues();
    List<PropertyValue> propertyValues = mutablePropertyValues.getPropertyValueList();
    for (PropertyValue propertyValue : propertyValues) {
      Object value = propertyValue.getValue();
      if (!(value instanceof TypedStringValue)) {
        continue;
      }
      String placeholder = ((TypedStringValue) value).getValue();
      Set<String> keys = placeholderHelper.extractPlaceholderKeys(placeholder);

      if (keys.isEmpty()) {
        continue;
      }

      for (String key : keys) {
        springValueDefinitions.put(beanName, new SpringValueDefinition(key, placeholder, propertyValue.getName()));
      }
    }
  }
}
 
Example 11
Source File: ZebraMapperScannerConfigurer.java    From Zebra with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @since 1.0.2
 */
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
	if (this.processPropertyPlaceHolders) {
		processPropertyPlaceHolders();
	}
	String[] beanDefinitionNames = registry.getBeanDefinitionNames();
	for (String beanDefinitionName : beanDefinitionNames) {
		BeanDefinition beanDefinition = registry.getBeanDefinition(beanDefinitionName);
		String beanClassName = beanDefinition.getBeanClassName();
		if (SqlSessionFactoryBean.class.getName().equals(beanClassName)) {
			beanDefinition.setBeanClassName(FixedSqlSessionFactoryBean.class.getName());
		}
	}

	ZebraClassPathMapperScanner scanner = new ZebraClassPathMapperScanner(registry);
	scanner.setAddToConfig(this.addToConfig);
	scanner.setAnnotationClass(this.annotationClass);
	scanner.setMarkerInterface(this.markerInterface);
	scanner.setSqlSessionFactory(this.sqlSessionFactory);
	scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
	scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
	scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
	scanner.setResourceLoader(this.applicationContext);
	scanner.setBeanNameGenerator(this.nameGenerator);
	scanner.registerFilters();
	scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage,
	      ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}
 
Example 12
Source File: StatefulFactory.java    From statefulj with Apache License 2.0 5 votes vote down vote up
/**
 * Iterate thru all beans and fetch the StatefulControllers
 *
 * @param reg
 * @return
 * @throws ClassNotFoundException
 */
private void mapControllerAndEntityClasses(
		BeanDefinitionRegistry reg,
		Map<String, Class<?>> controllerToEntityMapping,
		Map<Class<?>, String> entityToRepositoryMapping,
		Map<Class<?>, Set<String>> entityToControllerMappings) throws ClassNotFoundException {

	// Loop thru the bean registry
	//
	for(String bfName : reg.getBeanDefinitionNames()) {

		BeanDefinition bf = reg.getBeanDefinition(bfName);

		if (bf.isAbstract()) {
			logger.debug("Skipping abstract bean " + bfName);
			continue;
		}

		Class<?> clazz = getClassFromBeanDefinition(bf, reg);

		if (clazz == null) {
			logger.debug("Unable to resolve class for bean " + bfName);
			continue;
		}

		// If it's a StatefulController, map controller to the entity and the entity to the controller
		//
		if (ReflectionUtils.isAnnotationPresent(clazz, StatefulController.class)) {
			mapEntityWithController(controllerToEntityMapping, entityToControllerMappings, bfName, clazz);
		}

		// Else, if the Bean is a Repository, then map the
		// Entity associated with the Repo to the PersistenceSupport object
		//
		else if (RepositoryFactoryBeanSupport.class.isAssignableFrom(clazz)) {
			mapEntityToRepository(entityToRepositoryMapping, bfName, bf);
		}
	}
}