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

The following examples show how to use org.springframework.beans.factory.support.BeanDefinitionRegistry#getBeanDefinition() . 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: StatefulFactoryTest.java    From statefulj with Apache License 2.0 6 votes vote down vote up
@Test
public void testMemoryPersistor() throws ClassNotFoundException {
	BeanDefinitionRegistry registry = new MockBeanDefinitionRegistryImpl();
	
	BeanDefinition memoryController = BeanDefinitionBuilder
			.genericBeanDefinition(MemoryController.class)
			.getBeanDefinition();

	registry.registerBeanDefinition("memoryController", memoryController);

	ReferenceFactory refFactory = new ReferenceFactoryImpl("memoryController");
	StatefulFactory factory = new StatefulFactory();
	
	factory.postProcessBeanDefinitionRegistry(registry);
	
	BeanDefinition fsm = registry.getBeanDefinition(refFactory.getFSMId());
	assertNotNull(fsm);

	BeanDefinition persister = registry.getBeanDefinition(refFactory.getPersisterId());
	assertNotNull(persister);
	assertEquals(MemoryPersisterImpl.class.getName(), persister.getBeanClassName());

	BeanDefinition harness = registry.getBeanDefinition(refFactory.getFSMHarnessId());
	assertNull(harness);
}
 
Example 2
Source File: AopConfigUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, Object source) {
	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
		BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
		if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
			int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
			int requiredPriority = findPriorityForClass(cls);
			if (currentPriority < requiredPriority) {
				apcDefinition.setBeanClassName(cls.getName());
			}
		}
		return null;
	}
	RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
	beanDefinition.setSource(source);
	beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
	beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
	registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
	return beanDefinition;
}
 
Example 3
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 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: AbstractCacheManagerAndProviderFacadeParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Parses the given XML element containing the properties of the cache manager
 * to register in the given registry of bean definitions.
 * 
 * @param element
 *          the XML element to parse
 * @param registry
 *          the registry of bean definitions
 * 
 * @see AbstractCacheProviderFacadeParser#doParse(String, Element,
 *      BeanDefinitionRegistry)
 */
protected final void doParse(String cacheProviderFacadeId, Element element,
    BeanDefinitionRegistry registry) {
  String id = "cacheManager";
  Class clazz = getCacheManagerClass();
  RootBeanDefinition cacheManager = new RootBeanDefinition(clazz);
  MutablePropertyValues cacheManagerProperties = new MutablePropertyValues();
  cacheManager.setPropertyValues(cacheManagerProperties);

  PropertyValue configLocation = parseConfigLocationProperty(element);
  cacheManagerProperties.addPropertyValue(configLocation);
  registry.registerBeanDefinition(id, cacheManager);

  BeanDefinition cacheProviderFacade = registry
      .getBeanDefinition(cacheProviderFacadeId);
  cacheProviderFacade.getPropertyValues().addPropertyValue("cacheManager",
      new RuntimeBeanReference(id));
}
 
Example 6
Source File: RegionTemplateAutoConfiguration.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Bean
BeanFactoryPostProcessor regionTemplateBeanFactoryPostProcessor() {

	return beanFactory -> {

		if (beanFactory instanceof BeanDefinitionRegistry) {

			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

			List<String> beanDefinitionNames =
				Arrays.asList(ArrayUtils.nullSafeArray(registry.getBeanDefinitionNames(), String.class));

			Set<String> userRegionTemplateNames = new HashSet<>();

			for (String beanName : beanDefinitionNames) {

				String regionTemplateBeanName = toRegionTemplateBeanName(beanName);

				if (!beanDefinitionNames.contains(regionTemplateBeanName)) {

					BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);

					Class<?> resolvedBeanType = resolveBeanClass(beanDefinition, registry).orElse(null);

					if (isRegionBeanDefinition(resolvedBeanType)) {
						register(newGemfireTemplateBeanDefinition(beanName), regionTemplateBeanName, registry);
					}
					else if (isGemfireTemplateBeanDefinition(resolvedBeanType)) {
						userRegionTemplateNames.add(beanName);
					}
					else if (isBeanWithGemfireTemplateDependency(beanFactory, beanDefinition)) {
						SpringUtils.addDependsOn(beanDefinition, GemfireConstants.DEFAULT_GEMFIRE_CACHE_NAME);
					}
				}
			}

			setAutoConfiguredRegionTemplateDependencies(registry, userRegionTemplateNames);
		}
	};
}
 
Example 7
Source File: StateHandlerAnnotationBeanFactoryPostProcessor.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
private boolean beanAlreadyConfigured(BeanDefinitionRegistry registry, String beanName, Class clz) {
	if (registry.isBeanNameInUse(beanName)) {
		BeanDefinition bDef = registry.getBeanDefinition(beanName);
		if (bDef.getBeanClassName().equals(clz.getName())) {
			return true; // so the beans already registered, and of the right type. so we assume the user is overriding our configuration
		} else {
			throw new IllegalStateException("The bean name '" + beanName + "' is reserved.");
		}
	}
	return false;
}
 
Example 8
Source File: WebAdminComponentScanRegistrar.java    From wallride with Apache License 2.0 5 votes vote down vote up
private void updateWebAdminComponentScanBeanPostProcessor(BeanDefinitionRegistry registry, Set<String> packagesToScan) {
	BeanDefinition definition = registry.getBeanDefinition(BEAN_NAME);
	ConstructorArgumentValues.ValueHolder constructorArguments = definition.getConstructorArgumentValues()
			.getGenericArgumentValue(String[].class);
	Set<String> mergedPackages = new LinkedHashSet<>();
	mergedPackages.addAll(Arrays.asList((String[]) constructorArguments.getValue()));
	mergedPackages.addAll(packagesToScan);
	constructorArguments.setValue(toArray(mergedPackages));
}
 
Example 9
Source File: StatefulFactoryTest.java    From statefulj with Apache License 2.0 5 votes vote down vote up
@Test
public void testFSMConstructionWithNonDefaultRetry() throws ClassNotFoundException, NoSuchMethodException, SecurityException {
	
	BeanDefinitionRegistry registry = new MockBeanDefinitionRegistryImpl();
	
	BeanDefinition userRepo = BeanDefinitionBuilder
			.genericBeanDefinition(MockRepositoryFactoryBeanSupport.class)
			.getBeanDefinition();
	userRepo.getPropertyValues().add("repositoryInterface", UserRepository.class.getName());

	registry.registerBeanDefinition("userRepo", userRepo);

	BeanDefinition noRetryController = BeanDefinitionBuilder
			.genericBeanDefinition(NoRetryController.class)
			.getBeanDefinition();

	registry.registerBeanDefinition("noRetryController", noRetryController);

	ReferenceFactory refFactory = new ReferenceFactoryImpl("noRetryController");

	StatefulFactory factory = new StatefulFactory();
	
	factory.postProcessBeanDefinitionRegistry(registry);

	BeanDefinition fsm = registry.getBeanDefinition(refFactory.getFSMId());
	assertNotNull(fsm);
	assertEquals(1, fsm.getConstructorArgumentValues().getArgumentValue(2, Integer.class).getValue());
	assertEquals(1, fsm.getConstructorArgumentValues().getArgumentValue(3, Integer.class).getValue());
}
 
Example 10
Source File: CachingListenerValidatorImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @see CachingListenerValidator#validate(Object, int, ParserContext)
 */
public void validate(Object cachingListener, int index,
    ParserContext parserContext) throws IllegalStateException {
  BeanDefinitionRegistry registry = parserContext.getRegistry();
  BeanDefinition beanDefinition = null;

  if (cachingListener instanceof RuntimeBeanReference) {
    String beanName = ((RuntimeBeanReference) cachingListener).getBeanName();
    beanDefinition = registry.getBeanDefinition(beanName);

  } else if (cachingListener instanceof BeanDefinitionHolder) {
    beanDefinition = ((BeanDefinitionHolder) cachingListener)
        .getBeanDefinition();
  } else {
    throw new IllegalStateException("The caching listener reference/holder ["
        + index + "] should be an instance of <"
        + RuntimeBeanReference.class.getName() + "> or <"
        + BeanDefinitionHolder.class.getName() + ">");
  }

  Class expectedClass = CachingListener.class;
  Class actualClass = resolveBeanClass(beanDefinition);

  if (!expectedClass.isAssignableFrom(actualClass)) {
    throw new IllegalStateException("The caching listener [" + index
        + "] should be an instance of <" + expectedClass.getName() + ">");
  }
}
 
Example 11
Source File: MongoPersister.java    From statefulj with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanDefinitionRegistry(
		BeanDefinitionRegistry registry) throws BeansException {

	if (this.mongoTemplate == null) {

		if (this.repoId != null) {

			// Fetch the MongoTemplate Bean Id
			//
			BeanDefinition repo = registry.getBeanDefinition(this.repoId);
			this.templateId = ((BeanReference)repo.getPropertyValues().get("mongoOperations")).getBeanName();
		}

		// Check to make sure we have a reference to the MongoTemplate
		//
		if (this.templateId == null) {
			throw new RuntimeException("Unable to obtain a reference to a MongoTemplate");
		}
	}


	// Add in CascadeSupport
	//
	BeanDefinition mongoCascadeSupportBean = BeanDefinitionBuilder
			.genericBeanDefinition(MongoCascadeSupport.class)
			.getBeanDefinition();
	ConstructorArgumentValues args = mongoCascadeSupportBean.getConstructorArgumentValues();
	args.addIndexedArgumentValue(0, this);
	registry.registerBeanDefinition(Long.toString((new Random()).nextLong()), mongoCascadeSupportBean);
}
 
Example 12
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 13
Source File: ConsumerRegistrar.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
protected void checkMessageListener(OMSMessageListener messageListenerAnnotation, String bean) {
    BeanDefinitionRegistry beanDefinitionRegistry = (BeanDefinitionRegistry) beanFactory;
    BeanDefinition listenerBeanDefinition = beanDefinitionRegistry.getBeanDefinition(bean);
    Class<?> listenerClass;
    try {
        listenerClass = Class.forName(listenerBeanDefinition.getBeanClassName());
    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException(String.format("listener class not found, className: %s",
                listenerBeanDefinition.getBeanClassName()), e);
    }
    if (!MessageListener.class.isAssignableFrom(listenerClass) && !BatchMessageListener.class.isAssignableFrom(listenerClass)) {
        throw new IllegalArgumentException(String.format("%s type error, need MessageListener or BatchMessageListener", listenerClass));
    }
}
 
Example 14
Source File: ConfigurerImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void initWildcardDefinitionMap() {
    if (null != appContexts) {
        for (ApplicationContext appContext : appContexts) {
            for (String n : appContext.getBeanDefinitionNames()) {
                if (isWildcardBeanName(n)) {
                    AutowireCapableBeanFactory bf = appContext.getAutowireCapableBeanFactory();
                    BeanDefinitionRegistry bdr = (BeanDefinitionRegistry) bf;
                    BeanDefinition bd = bdr.getBeanDefinition(n);
                    String className = bd.getBeanClassName();
                    if (null != className) {
                        final String name = n.charAt(0) != '*' ? n
                                : "." + n.replaceAll("\\.", "\\."); //old wildcard
                        try {
                            Matcher matcher = Pattern.compile(name).matcher("");
                            List<MatcherHolder> m = wildCardBeanDefinitions.get(className);
                            if (m == null) {
                                m = new ArrayList<>();
                                wildCardBeanDefinitions.put(className, m);
                            }
                            MatcherHolder holder = new MatcherHolder(n, matcher);
                            m.add(holder);
                        } catch (PatternSyntaxException npe) {
                            //not a valid patter, we'll ignore
                        }
                    } else {
                        LogUtils.log(LOG, Level.WARNING, "WILDCARD_BEAN_ID_WITH_NO_CLASS_MSG", n);
                    }
                }
            }
        }
    }
}
 
Example 15
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);
		}
	}
}
 
Example 16
Source File: BootBeanNameGenerator.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected String buildDefaultBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
	String beanName = buildDefaultBeanName(definition);
	if(registry.containsBeanDefinition(beanName)){
		BeanDefinition bd = registry.getBeanDefinition(beanName);
		if(!bd.getBeanClassName().equals(definition.getBeanClassName())){
			beanName = definition.getBeanClassName();
		}
	}
	return beanName;
}
 
Example 17
Source File: AopConfigUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
static void forceAutoProxyCreatorToExposeProxy(BeanDefinitionRegistry registry) {
	if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
		BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
		definition.getPropertyValues().add("exposeProxy", Boolean.TRUE);
	}
}
 
Example 18
Source File: AopConfigUtils.java    From java-technology-stack with MIT License 4 votes vote down vote up
public static void forceAutoProxyCreatorToExposeProxy(BeanDefinitionRegistry registry) {
	if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
		BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
		definition.getPropertyValues().add("exposeProxy", Boolean.TRUE);
	}
}
 
Example 19
Source File: AopConfigUtils.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) {
	if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
		BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
		definition.getPropertyValues().add("proxyTargetClass", Boolean.TRUE);
	}
}
 
Example 20
Source File: StatefulFactoryTest.java    From statefulj with Apache License 2.0 2 votes vote down vote up
@Test
public void testFSMConstruction() throws ClassNotFoundException, NoSuchMethodException, SecurityException {
	
	BeanDefinitionRegistry registry = new MockBeanDefinitionRegistryImpl();
	
	BeanDefinition userRepo = BeanDefinitionBuilder
			.genericBeanDefinition(MockRepositoryFactoryBeanSupport.class)
			.getBeanDefinition();
	userRepo.getPropertyValues().add("repositoryInterface", UserRepository.class.getName());

	registry.registerBeanDefinition("userRepo", userRepo);

	BeanDefinition userController = BeanDefinitionBuilder
			.genericBeanDefinition(UserController.class)
			.getBeanDefinition();

	registry.registerBeanDefinition("userController", userController);

	ReferenceFactory refFactory = new ReferenceFactoryImpl("userController");
	StatefulFactory factory = new StatefulFactory();
	
	factory.postProcessBeanDefinitionRegistry(registry);
	
	BeanDefinition userControllerMVCProxy = registry.getBeanDefinition(refFactory.getBinderId("mock"));
	
	assertNotNull(userControllerMVCProxy);
	
	Class<?> proxyClass = Class.forName(userControllerMVCProxy.getBeanClassName());
	
	assertNotNull(proxyClass);
	
	assertEquals(MockProxy.class, proxyClass);
	
	// Verify that FIVE_STATE is blocking
	//
	BeanDefinition stateFive = registry.getBeanDefinition(refFactory.getStateId(UserController.FIVE_STATE));
	
	assertEquals(true, stateFive.getConstructorArgumentValues().getArgumentValue(2, Boolean.class).getValue());
	
	BeanDefinition fsm = registry.getBeanDefinition(refFactory.getFSMId());
	assertNotNull(fsm);
	assertEquals(20, fsm.getConstructorArgumentValues().getArgumentValue(2, Integer.class).getValue());
	assertEquals(250, fsm.getConstructorArgumentValues().getArgumentValue(3, Integer.class).getValue());
}