Java Code Examples for org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBeanNamesForType()

The following examples show how to use org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBeanNamesForType() . 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: DefaultLifecycleProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Retrieve all applicable Lifecycle beans: all singletons that have already been created,
 * as well as all SmartLifecycle beans (even if they are marked as lazy-init).
 * @return the Map of applicable beans, with bean names as keys and bean instances as values
 */
protected Map<String, Lifecycle> getLifecycleBeans() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	Map<String, Lifecycle> beans = new LinkedHashMap<>();
	String[] beanNames = beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
	for (String beanName : beanNames) {
		String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName);
		boolean isFactoryBean = beanFactory.isFactoryBean(beanNameToRegister);
		String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
		if ((beanFactory.containsSingleton(beanNameToRegister) &&
				(!isFactoryBean || matchesBeanType(Lifecycle.class, beanNameToCheck, beanFactory))) ||
				matchesBeanType(SmartLifecycle.class, beanNameToCheck, beanFactory)) {
			Object bean = beanFactory.getBean(beanNameToCheck);
			if (bean != this && bean instanceof Lifecycle) {
				beans.put(beanNameToRegister, (Lifecycle) bean);
			}
		}
	}
	return beans;
}
 
Example 2
Source File: DefaultLifecycleProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Retrieve all applicable Lifecycle beans: all singletons that have already been created,
 * as well as all SmartLifecycle beans (even if they are marked as lazy-init).
 * @return the Map of applicable beans, with bean names as keys and bean instances as values
 */
protected Map<String, Lifecycle> getLifecycleBeans() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	Map<String, Lifecycle> beans = new LinkedHashMap<>();
	String[] beanNames = beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
	for (String beanName : beanNames) {
		String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName);
		boolean isFactoryBean = beanFactory.isFactoryBean(beanNameToRegister);
		String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
		if ((beanFactory.containsSingleton(beanNameToRegister) &&
				(!isFactoryBean || matchesBeanType(Lifecycle.class, beanNameToCheck, beanFactory))) ||
				matchesBeanType(SmartLifecycle.class, beanNameToCheck, beanFactory)) {
			Object bean = beanFactory.getBean(beanNameToCheck);
			if (bean != this && bean instanceof Lifecycle) {
				beans.put(beanNameToRegister, (Lifecycle) bean);
			}
		}
	}
	return beans;
}
 
Example 3
Source File: ConfigurationPropertiesBeans.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext)
		throws BeansException {
	this.applicationContext = applicationContext;
	if (applicationContext
			.getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) {
		this.beanFactory = (ConfigurableListableBeanFactory) applicationContext
				.getAutowireCapableBeanFactory();
	}
	if (applicationContext.getParent() != null && applicationContext.getParent()
			.getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) {
		ConfigurableListableBeanFactory listable = (ConfigurableListableBeanFactory) applicationContext
				.getParent().getAutowireCapableBeanFactory();
		String[] names = listable
				.getBeanNamesForType(ConfigurationPropertiesBeans.class);
		if (names.length == 1) {
			this.parent = (ConfigurationPropertiesBeans) listable.getBean(names[0]);
			this.beans.putAll(this.parent.beans);
		}
	}
}
 
Example 4
Source File: AbstractApplicationContext.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Finish the initialization of this context's bean factory,
 * initializing all remaining singleton beans.
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// Initialize conversion service for this context.
	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
		beanFactory.setConversionService(
				beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
	}

	// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
	for (String weaverAwareName : weaverAwareNames) {
		getBean(weaverAwareName);
	}

	// Stop using the temporary ClassLoader for type matching.
	beanFactory.setTempClassLoader(null);

	// Allow for caching all bean definition metadata, not expecting further changes.
	beanFactory.freezeConfiguration();

	// Instantiate all remaining (non-lazy-init) singletons.
	beanFactory.preInstantiateSingletons();
}
 
Example 5
Source File: EasyMockReplacer.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * Replace Bean definition with a EasyMock Proxy 
 * @param clazz clazz to replace
 * @param factory factory to replace on
 */
private void replaceBean(Class<?> clazz, 
		ConfigurableListableBeanFactory factory) {
	
	Object  mock = EasyMock.createMock(clazz);
	String[] names = factory.getBeanNamesForType(clazz);
	for (String name : names) {
		log.info("Registering bean " 
				+ name + " with mock " + clazz.getName());
		factory.registerSingleton(name, mock);
	}
}
 
Example 6
Source File: AbstractApplicationContext.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Finish the initialization of this context's bean factory,
 * initializing all remaining singleton beans.
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// Initialize conversion service for this context.
	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
		beanFactory.setConversionService(
				beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
	}

	// Register a default embedded value resolver if no bean post-processor
	// (such as a PropertyPlaceholderConfigurer bean) registered any before:
	// at this point, primarily for resolution in annotation attribute values.
	if (!beanFactory.hasEmbeddedValueResolver()) {
		beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
	}

	// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
	for (String weaverAwareName : weaverAwareNames) {
		getBean(weaverAwareName);
	}

	// Stop using the temporary ClassLoader for type matching.
	beanFactory.setTempClassLoader(null);

	// Allow for caching all bean definition metadata, not expecting further changes.
	beanFactory.freezeConfiguration();

	// Instantiate all remaining (non-lazy-init) singletons.
	beanFactory.preInstantiateSingletons();
}
 
Example 7
Source File: SakaiApplicationContext.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Add bean-created post processors.
 * @param beanFactory
 */
public void invokePostProcessorCreators(ConfigurableListableBeanFactory beanFactory) {
	String[] postProcessorCreatorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessorCreator.class, false, false);
	for (int i = 0; i < postProcessorCreatorNames.length; i++) {
		BeanFactoryPostProcessorCreator postProcessorCreator = (BeanFactoryPostProcessorCreator)beanFactory.getBean(postProcessorCreatorNames[i]);
		for (BeanFactoryPostProcessor beanFactoryPostProcessor : postProcessorCreator.getBeanFactoryPostProcessors()) {
			addBeanFactoryPostProcessor(beanFactoryPostProcessor);
		}
	}
}
 
Example 8
Source File: DomainTransactionInterceptorInjector.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException {
    for (String name : beanFactory.getBeanNamesForType(TransactionInterceptor.class, false, false)) {
        BeanDefinition bd = beanFactory.getBeanDefinition(name);
        bd.setBeanClassName(DomainTransactionInterceptor.class.getName());
        bd.setFactoryBeanName(null);
        bd.setFactoryMethodName(null);
    }
}
 
Example 9
Source File: CoreSpringFactory.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * @param beanName
 *            The bean name to check for. Be sure the bean does exist, otherwise an NoSuchBeanDefinitionException will be thrown
 * @return The bean
 * @throws RuntimeException
 *             when more than one bean of the same type is registered.
 */
public static <T> T getBean(Class<T> beanType) {
    // log.info("beanType=" + beanType);
    // log.info("beanType.getInterfaces()=" + beanType.getInterfaces());

    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(CoreSpringFactory.servletContext);
    Map<String, T> m = context.getBeansOfType(beanType);
    if (m.size() > 1) {
        // with following code it is possible to configure multiple implementations for an interface (e.g. adapted spring config files for testing)
        // and to give it preference by setting primary="true" in <bean> definition tag.
        if (context instanceof XmlWebApplicationContext) {
            ConfigurableListableBeanFactory clbf = ((XmlWebApplicationContext) context).getBeanFactory();
            String[] beanNames = clbf.getBeanNamesForType(beanType);
            for (String beanName : beanNames) {
                BeanDefinition bd = clbf.getBeanDefinition(beanName);
                if (bd.isPrimary()) {
                    return context.getBean(beanName, beanType);
                }
            }
        }

        // more than one bean found -> exception
        throw new OLATRuntimeException("found more than one bean for: " + beanType + ". Calling this method should only find one bean!", null);
    } else if (m.size() == 1) {
        return m.values().iterator().next();
    }

    // fallback for beans named like the fully qualified path (legacy)
    Object o = context.getBean(beanType.getName());
    beanNamesCalledFromSource.add(beanType.getName());
    return (T) o;
}
 
Example 10
Source File: SakaiApplicationContext.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Add bean-created post processors.
 * @param beanFactory
 */
public void invokePostProcessorCreators(ConfigurableListableBeanFactory beanFactory) {
	String[] postProcessorCreatorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessorCreator.class, false, false);
	for (int i = 0; i < postProcessorCreatorNames.length; i++) {
		BeanFactoryPostProcessorCreator postProcessorCreator = (BeanFactoryPostProcessorCreator)beanFactory.getBean(postProcessorCreatorNames[i]);
		for (BeanFactoryPostProcessor beanFactoryPostProcessor : postProcessorCreator.getBeanFactoryPostProcessors()) {
			addBeanFactoryPostProcessor(beanFactoryPostProcessor);
		}
	}
}
 
Example 11
Source File: DoNotExecuteMongeezPostProcessor.java    From mongeez-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String[] mongeezBeanNames = beanFactory.getBeanNamesForType(Mongeez.class);
    Assert.state(mongeezBeanNames.length == 1);
    BeanDefinition beanDefinition = beanFactory.getBeanDefinition(mongeezBeanNames[0]);
    Assert.state(beanDefinition instanceof RootBeanDefinition);
    ((RootBeanDefinition) beanDefinition).setInitMethodName(null);
}
 
Example 12
Source File: MyBeanFactoryPostProcessor.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	System.out.println("[BeanFactoryPostProcessor] BeanFactoryPostProcessor call postProcessBeanFactory");
	String[] beanNamesForType = beanFactory.getBeanNamesForType(Person.class);
	for (String name : beanNamesForType) {
		BeanDefinition bd = beanFactory.getBeanDefinition(name);
		bd.getPropertyValues().addPropertyValue("phone", "110");
	}
}
 
Example 13
Source File: BeanDependencyManager.java    From jetcache with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String[] autoInitBeanNames = beanFactory.getBeanNamesForType(AbstractCacheAutoInit.class, false, false);
    if (autoInitBeanNames != null) {
        BeanDefinition bd = beanFactory.getBeanDefinition(JetCacheAutoConfiguration.GLOBAL_CACHE_CONFIG_NAME);
        String[] dependsOn = bd.getDependsOn();
        if (dependsOn == null) {
            dependsOn = new String[0];
        }
        int oldLen = dependsOn.length;
        dependsOn = Arrays.copyOf(dependsOn, dependsOn.length + autoInitBeanNames.length);
        System.arraycopy(autoInitBeanNames,0, dependsOn, oldLen, autoInitBeanNames.length);
        bd.setDependsOn(dependsOn);
    }
}
 
Example 14
Source File: AbstractApplicationContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Finish the initialization of this context's bean factory,
 * initializing all remaining singleton beans.
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// Initialize conversion service for this context.
	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
		beanFactory.setConversionService(
				beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
	}

	// Register a default embedded value resolver if no bean post-processor
	// (such as a PropertyPlaceholderConfigurer bean) registered any before:
	// at this point, primarily for resolution in annotation attribute values.
	if (!beanFactory.hasEmbeddedValueResolver()) {
		beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
			@Override
			public String resolveStringValue(String strVal) {
				return getEnvironment().resolvePlaceholders(strVal);
			}
		});
	}

	// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
	for (String weaverAwareName : weaverAwareNames) {
		getBean(weaverAwareName);
	}

	// Stop using the temporary ClassLoader for type matching.
	beanFactory.setTempClassLoader(null);

	// Allow for caching all bean definition metadata, not expecting further changes.
	beanFactory.freezeConfiguration();

	// Instantiate all remaining (non-lazy-init) singletons.
	beanFactory.preInstantiateSingletons();
}
 
Example 15
Source File: EmbeddedPostgresContextCustomizerFactory.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
protected static BeanDefinitionHolder getFlywayBeanDefinition(ConfigurableListableBeanFactory beanFactory) {
    String[] beanNames = beanFactory.getBeanNamesForType(Flyway.class, true, false);

    if (beanNames.length == 1) {
        String beanName = beanNames[0];
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
        return new BeanDefinitionHolder(beanDefinition, beanName);
    }

    return null;
}
 
Example 16
Source File: KubernetesReconcilerProcessor.java    From java with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
    throws BeansException {
  SharedInformerFactory sharedInformerFactory = beanFactory.getBean(SharedInformerFactory.class);
  String[] names = beanFactory.getBeanNamesForType(Reconciler.class);
  for (String name : names) {
    Reconciler reconciler = (Reconciler) beanFactory.getBean(name);
    KubernetesReconciler kubernetesReconciler =
        reconciler.getClass().getAnnotation(KubernetesReconciler.class);
    String reconcilerName = kubernetesReconciler.value();
    Controller controller = buildController(sharedInformerFactory, reconciler);
    beanFactory.registerSingleton(reconcilerName, controller);
  }
}
 
Example 17
Source File: NarayanaBeanFactoryPostProcessor.java    From narayana-spring-boot with Apache License 2.0 5 votes vote down vote up
private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory, String type) {
    try {
        return beanFactory.getBeanNamesForType(Class.forName(type), true, false);
    } catch (ClassNotFoundException | NoClassDefFoundError ignored) {
    }
    return NO_BEANS;
}
 
Example 18
Source File: NarayanaBeanFactoryPostProcessor.java    From narayana-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String[] transactionManagers = beanFactory.getBeanNamesForType(TransactionManager.class, true, false);
    String[] recoveryManagerServices = beanFactory.getBeanNamesForType(RecoveryManagerService.class, true, false);
    addBeanDependencies(beanFactory, transactionManagers, "javax.sql.DataSource");
    addBeanDependencies(beanFactory, recoveryManagerServices, "javax.sql.DataSource");
    addBeanDependencies(beanFactory, transactionManagers, "javax.jms.ConnectionFactory");
    addBeanDependencies(beanFactory, recoveryManagerServices, "javax.jms.ConnectionFactory");
}
 
Example 19
Source File: AbstractApplicationContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Finish the initialization of this context's bean factory,
 * initializing all remaining singleton beans.
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// Initialize conversion service for this context.
	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
		beanFactory.setConversionService(
				beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
	}

	// Register a default embedded value resolver if no bean post-processor
	// (such as a PropertyPlaceholderConfigurer bean) registered any before:
	// at this point, primarily for resolution in annotation attribute values.
	if (!beanFactory.hasEmbeddedValueResolver()) {
		beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
	}

	// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
	for (String weaverAwareName : weaverAwareNames) {
		getBean(weaverAwareName);
	}

	// Stop using the temporary ClassLoader for type matching.
	beanFactory.setTempClassLoader(null);

	// Allow for caching all bean definition metadata, not expecting further changes.
	beanFactory.freezeConfiguration();

	// Instantiate all remaining (non-lazy-init) singletons.
	beanFactory.preInstantiateSingletons();
}
 
Example 20
Source File: EarlyInitializationIntegrationTest.java    From embedded-database-spring-test with Apache License 2.0 4 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    beanFactory.getBeanNamesForType(DataSource.class, true, true);
}