Java Code Examples for org.springframework.beans.factory.ListableBeanFactory#getBean()

The following examples show how to use org.springframework.beans.factory.ListableBeanFactory#getBean() . 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: EntityManagerFactoryUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Find an EntityManagerFactory with the given name in the given
 * Spring application context (represented as ListableBeanFactory).
 * <p>The specified unit name will be matched against the configured
 * persistence unit, provided that a discovered EntityManagerFactory
 * implements the {@link EntityManagerFactoryInfo} interface. If not,
 * the persistence unit name will be matched against the Spring bean name,
 * assuming that the EntityManagerFactory bean names follow that convention.
 * <p>If no unit name has been given, this method will search for a default
 * EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}.
 * @param beanFactory the ListableBeanFactory to search
 * @param unitName the name of the persistence unit (may be {@code null} or empty,
 * in which case a single bean of type EntityManagerFactory will be searched for)
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 * @see EntityManagerFactoryInfo#getPersistenceUnitName()
 */
public static EntityManagerFactory findEntityManagerFactory(
		ListableBeanFactory beanFactory, @Nullable String unitName) throws NoSuchBeanDefinitionException {

	Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
	if (StringUtils.hasLength(unitName)) {
		// See whether we can find an EntityManagerFactory with matching persistence unit name.
		String[] candidateNames =
				BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, EntityManagerFactory.class);
		for (String candidateName : candidateNames) {
			EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName);
			if (emf instanceof EntityManagerFactoryInfo &&
					unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) {
				return emf;
			}
		}
		// No matching persistence unit found - simply take the EntityManagerFactory
		// with the persistence unit name as bean name (by convention).
		return beanFactory.getBean(unitName, EntityManagerFactory.class);
	}
	else {
		// Find unique EntityManagerFactory bean in the context, falling back to parent contexts.
		return beanFactory.getBean(EntityManagerFactory.class);
	}
}
 
Example 2
Source File: SchedulerAccessorBean.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected Scheduler findScheduler(String schedulerName) throws SchedulerException {
	if (this.beanFactory instanceof ListableBeanFactory) {
		ListableBeanFactory lbf = (ListableBeanFactory) this.beanFactory;
		String[] beanNames = lbf.getBeanNamesForType(Scheduler.class);
		for (String beanName : beanNames) {
			Scheduler schedulerBean = (Scheduler) lbf.getBean(beanName);
			if (schedulerName.equals(schedulerBean.getSchedulerName())) {
				return schedulerBean;
			}
		}
	}
	Scheduler schedulerInRepo = SchedulerRepository.getInstance().lookup(schedulerName);
	if (schedulerInRepo == null) {
		throw new IllegalStateException("No Scheduler named '" + schedulerName + "' found");
	}
	return schedulerInRepo;
}
 
Example 3
Source File: BeanFactoryAnnotationUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier
 * (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier).
 * @param bf the factory to get the target bean from
 * @param beanType the type of bean to retrieve
 * @param qualifier the qualifier for selecting between multiple bean matches
 * @return the matching bean of type {@code T} (never {@code null})
 */
private static <T> T qualifiedBeanOfType(ListableBeanFactory bf, Class<T> beanType, String qualifier) {
	String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
	String matchingBean = null;
	for (String beanName : candidateBeans) {
		if (isQualifierMatch(qualifier::equals, beanName, bf)) {
			if (matchingBean != null) {
				throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName);
			}
			matchingBean = beanName;
		}
	}
	if (matchingBean != null) {
		return bf.getBean(matchingBean, beanType);
	}
	else if (bf.containsBean(qualifier)) {
		// Fallback: target bean at least found by bean name - probably a manually registered singleton.
		return bf.getBean(qualifier, beanType);
	}
	else {
		throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
				" bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!");
	}
}
 
Example 4
Source File: EntityManagerFactoryUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Find an EntityManagerFactory with the given name in the given
 * Spring application context (represented as ListableBeanFactory).
 * <p>The specified unit name will be matched against the configured
 * persistence unit, provided that a discovered EntityManagerFactory
 * implements the {@link EntityManagerFactoryInfo} interface. If not,
 * the persistence unit name will be matched against the Spring bean name,
 * assuming that the EntityManagerFactory bean names follow that convention.
 * <p>If no unit name has been given, this method will search for a default
 * EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}.
 * @param beanFactory the ListableBeanFactory to search
 * @param unitName the name of the persistence unit (may be {@code null} or empty,
 * in which case a single bean of type EntityManagerFactory will be searched for)
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 * @see EntityManagerFactoryInfo#getPersistenceUnitName()
 */
public static EntityManagerFactory findEntityManagerFactory(
		ListableBeanFactory beanFactory, @Nullable String unitName) throws NoSuchBeanDefinitionException {

	Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
	if (StringUtils.hasLength(unitName)) {
		// See whether we can find an EntityManagerFactory with matching persistence unit name.
		String[] candidateNames =
				BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, EntityManagerFactory.class);
		for (String candidateName : candidateNames) {
			EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName);
			if (emf instanceof EntityManagerFactoryInfo &&
					unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) {
				return emf;
			}
		}
		// No matching persistence unit found - simply take the EntityManagerFactory
		// with the persistence unit name as bean name (by convention).
		return beanFactory.getBean(unitName, EntityManagerFactory.class);
	}
	else {
		// Find unique EntityManagerFactory bean in the context, falling back to parent contexts.
		return beanFactory.getBean(EntityManagerFactory.class);
	}
}
 
Example 5
Source File: SchedulerAccessorBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
protected Scheduler findScheduler(String schedulerName) throws SchedulerException {
	if (this.beanFactory instanceof ListableBeanFactory) {
		ListableBeanFactory lbf = (ListableBeanFactory) this.beanFactory;
		String[] beanNames = lbf.getBeanNamesForType(Scheduler.class);
		for (String beanName : beanNames) {
			Scheduler schedulerBean = (Scheduler) lbf.getBean(beanName);
			if (schedulerName.equals(schedulerBean.getSchedulerName())) {
				return schedulerBean;
			}
		}
	}
	Scheduler schedulerInRepo = SchedulerRepository.getInstance().lookup(schedulerName);
	if (schedulerInRepo == null) {
		throw new IllegalStateException("No Scheduler named '" + schedulerName + "' found");
	}
	return schedulerInRepo;
}
 
Example 6
Source File: BeanFactoryAnnotationUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier
 * (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier).
 * @param bf the factory to get the target bean from
 * @param beanType the type of bean to retrieve
 * @param qualifier the qualifier for selecting between multiple bean matches
 * @return the matching bean of type {@code T} (never {@code null})
 */
private static <T> T qualifiedBeanOfType(ListableBeanFactory bf, Class<T> beanType, String qualifier) {
	String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
	String matchingBean = null;
	for (String beanName : candidateBeans) {
		if (isQualifierMatch(qualifier::equals, beanName, bf)) {
			if (matchingBean != null) {
				throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName);
			}
			matchingBean = beanName;
		}
	}
	if (matchingBean != null) {
		return bf.getBean(matchingBean, beanType);
	}
	else if (bf.containsBean(qualifier)) {
		// Fallback: target bean at least found by bean name - probably a manually registered singleton.
		return bf.getBean(qualifier, beanType);
	}
	else {
		throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
				" bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!");
	}
}
 
Example 7
Source File: SchedulerAccessorBean.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected Scheduler findScheduler(String schedulerName) throws SchedulerException {
	if (this.beanFactory instanceof ListableBeanFactory) {
		ListableBeanFactory lbf = (ListableBeanFactory) this.beanFactory;
		String[] beanNames = lbf.getBeanNamesForType(Scheduler.class);
		for (String beanName : beanNames) {
			Scheduler schedulerBean = (Scheduler) lbf.getBean(beanName);
			if (schedulerName.equals(schedulerBean.getSchedulerName())) {
				return schedulerBean;
			}
		}
	}
	Scheduler schedulerInRepo = SchedulerRepository.getInstance().lookup(schedulerName);
	if (schedulerInRepo == null) {
		throw new IllegalStateException("No Scheduler named '" + schedulerName + "' found");
	}
	return schedulerInRepo;
}
 
Example 8
Source File: EntityManagerFactoryUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Find an EntityManagerFactory with the given name in the given
 * Spring application context (represented as ListableBeanFactory).
 * <p>The specified unit name will be matched against the configured
 * persistence unit, provided that a discovered EntityManagerFactory
 * implements the {@link EntityManagerFactoryInfo} interface. If not,
 * the persistence unit name will be matched against the Spring bean name,
 * assuming that the EntityManagerFactory bean names follow that convention.
 * <p>If no unit name has been given, this method will search for a default
 * EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}.
 * @param beanFactory the ListableBeanFactory to search
 * @param unitName the name of the persistence unit (may be {@code null} or empty,
 * in which case a single bean of type EntityManagerFactory will be searched for)
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 * @see EntityManagerFactoryInfo#getPersistenceUnitName()
 */
public static EntityManagerFactory findEntityManagerFactory(
		ListableBeanFactory beanFactory, String unitName) throws NoSuchBeanDefinitionException {

	Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
	if (StringUtils.hasLength(unitName)) {
		// See whether we can find an EntityManagerFactory with matching persistence unit name.
		String[] candidateNames =
				BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, EntityManagerFactory.class);
		for (String candidateName : candidateNames) {
			EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName);
			if (emf instanceof EntityManagerFactoryInfo) {
				if (unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) {
					return emf;
				}
			}
		}
		// No matching persistence unit found - simply take the EntityManagerFactory
		// with the persistence unit name as bean name (by convention).
		return beanFactory.getBean(unitName, EntityManagerFactory.class);
	}
	else {
		// Find unique EntityManagerFactory bean in the context, falling back to parent contexts.
		return beanFactory.getBean(EntityManagerFactory.class);
	}
}
 
Example 9
Source File: EntityManagerFactoryUtils.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Find an EntityManagerFactory with the given name in the given
 * Spring application context (represented as ListableBeanFactory).
 * <p>The specified unit name will be matched against the configured
 * persistence unit, provided that a discovered EntityManagerFactory
 * implements the {@link EntityManagerFactoryInfo} interface. If not,
 * the persistence unit name will be matched against the Spring bean name,
 * assuming that the EntityManagerFactory bean names follow that convention.
 * <p>If no unit name has been given, this method will search for a default
 * EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}.
 * @param beanFactory the ListableBeanFactory to search
 * @param unitName the name of the persistence unit (may be {@code null} or empty,
 * in which case a single bean of type EntityManagerFactory will be searched for)
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 * @see EntityManagerFactoryInfo#getPersistenceUnitName()
 */
public static EntityManagerFactory findEntityManagerFactory(
		ListableBeanFactory beanFactory, String unitName) throws NoSuchBeanDefinitionException {

	Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
	if (StringUtils.hasLength(unitName)) {
		// See whether we can find an EntityManagerFactory with matching persistence unit name.
		String[] candidateNames =
				BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, EntityManagerFactory.class);
		for (String candidateName : candidateNames) {
			EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName);
			if (emf instanceof EntityManagerFactoryInfo) {
				if (unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) {
					return emf;
				}
			}
		}
		// No matching persistence unit found - simply take the EntityManagerFactory
		// with the persistence unit name as bean name (by convention).
		return beanFactory.getBean(unitName, EntityManagerFactory.class);
	}
	else {
		// Find unique EntityManagerFactory bean in the context, falling back to parent contexts.
		return beanFactory.getBean(EntityManagerFactory.class);
	}
}
 
Example 10
Source File: SchedulerAccessorBean.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
protected Scheduler findScheduler(String schedulerName) throws SchedulerException {
	if (this.beanFactory instanceof ListableBeanFactory) {
		ListableBeanFactory lbf = (ListableBeanFactory) this.beanFactory;
		String[] beanNames = lbf.getBeanNamesForType(Scheduler.class);
		for (String beanName : beanNames) {
			Scheduler schedulerBean = (Scheduler) lbf.getBean(beanName);
			if (schedulerName.equals(schedulerBean.getSchedulerName())) {
				return schedulerBean;
			}
		}
	}
	Scheduler schedulerInRepo = SchedulerRepository.getInstance().lookup(schedulerName);
	if (schedulerInRepo == null) {
		throw new IllegalStateException("No Scheduler named '" + schedulerName + "' found");
	}
	return schedulerInRepo;
}
 
Example 11
Source File: JobsManagerImpl.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private Map<String, JobFactory> loadFactories(ListableBeanFactory beanFactory) {
    ImmutableMap.Builder<String, JobFactory> mb = ImmutableMap.builder();
    //load factory beans
    String[] factoryNames = beanFactory.getBeanNamesForType(JobFactory.class);
    for(String factoryName: factoryNames) {
        JobFactory factory = beanFactory.getBean(factoryName, JobFactory.class);
        if(factory == this) {
            // we do not want to load self
            continue;
        }
        Set<String> types = factory.getTypes();
        for(String type: types) {
            mb.put(type, factory);
        }
    }
    //load job beans
    String[] jobNames = beanFactory.getBeanNamesForAnnotation(JobBean.class);
    for(String jobName: jobNames) {
        Class<?> jobType = beanFactory.getType(jobName);
        JobDescription jd = descFactory.getFor(jobName);
        mb.put(jobName, new JobFactoryForBean(this, jobName, jobType, jd));
    }
    return mb.build();
}
 
Example 12
Source File: SpringBootAnnotationResolver.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
private BrpcConfig getServiceConfig(ListableBeanFactory beanFactory, Class<?> serviceInterface) {
    if (brpcProperties == null) {
        brpcProperties = beanFactory.getBean(BrpcProperties.class);
        if (brpcProperties == null) {
            throw new RuntimeException("bean of BrpcProperties is null");
        }
    }
    return brpcProperties.getServiceConfig(serviceInterface);
}
 
Example 13
Source File: DubboConfigBeanDefinitionConflictApplicationListener.java    From dubbo-spring-boot-project with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve the unique {@link ApplicationConfig} Bean
 * @param registry {@link BeanDefinitionRegistry} instance
 * @param beanFactory {@link ConfigurableListableBeanFactory} instance
 * @see EnableDubboConfig
 */
private void resolveUniqueApplicationConfigBean(BeanDefinitionRegistry registry, ListableBeanFactory beanFactory) {

    String[] beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class);

    if (beansNames.length < 2) { // If the number of ApplicationConfig beans is less than two, return immediately.
        return;
    }

    Environment environment = beanFactory.getBean(ENVIRONMENT_BEAN_NAME, Environment.class);

    // Remove ApplicationConfig Beans that are configured by "dubbo.application.*"
    Stream.of(beansNames)
            .filter(beansName -> isConfiguredApplicationConfigBeanName(environment, beansName))
            .forEach(registry::removeBeanDefinition);

    beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class);

    if (beansNames.length > 1) {
        throw new IllegalStateException(String.format("There are more than one instances of %s, whose bean definitions : %s",
                ApplicationConfig.class.getSimpleName(),
                Stream.of(beansNames)
                        .map(registry::getBeanDefinition)
                        .collect(Collectors.toList()))
        );
    }
}
 
Example 14
Source File: BeanUtils.java    From spring-context-support with Apache License 2.0 5 votes vote down vote up
/**
 * Get Optional Bean by {@link Class} including ancestors(BeanFactory).
 *
 * @param beanFactory        {@link ListableBeanFactory}
 * @param beanClass          The  {@link Class} of Bean
 * @param includingAncestors including ancestors or not
 * @param <T>                The  {@link Class} of Bean
 * @return Bean object if found , or return <code>null</code>.
 * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
 * @see org.springframework.beans.factory.BeanFactoryUtils#beanOfTypeIncludingAncestors(ListableBeanFactory, Class)
 */
public static <T> T getOptionalBean(ListableBeanFactory beanFactory, Class<T> beanClass,
                                    boolean includingAncestors) throws BeansException {

    String[] beanNames = getBeanNames(beanFactory, beanClass, includingAncestors);

    if (ObjectUtils.isEmpty(beanNames)) {
        if (logger.isDebugEnabled()) {
            logger.debug("The bean [ class : " + beanClass.getName() + " ] can't be found ");
        }
        return null;
    }

    T bean = null;

    try {

        bean = includingAncestors ?
                beanOfTypeIncludingAncestors(beanFactory, beanClass) :
                beanFactory.getBean(beanClass);

    } catch (Exception e) {

        if (logger.isErrorEnabled()) {
            logger.error(e.getMessage(), e);
        }

    }

    return bean;

}
 
Example 15
Source File: SpringUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
/****
 * 
 * @author wayshall
 * @param beanFactory
 * @param annoClass
 * @param consumer
 * @return 如果找到指定注解的bean,则返回true,否则返回false
 */
public static boolean scanAnnotation(ListableBeanFactory beanFactory, Class<? extends Annotation> annoClass, BiConsumer<Object, Class<?>> consumer){
	String[] beanNames = beanFactory.getBeanNamesForAnnotation(annoClass);
	for(String beanName : beanNames){
		Object bean = beanFactory.getBean(beanName);
		Class<?> beanClass = SpringUtils.getTargetClass(bean);
		consumer.accept(bean, beanClass);
	}
	return ArrayUtils.isNotEmpty(beanNames);
}
 
Example 16
Source File: VaultReactiveBootstrapConfiguration.java    From spring-cloud-vault with Apache License 2.0 4 votes vote down vote up
/**
 * @param beanFactory the {@link BeanFactory}.
 * @return the {@link VaultTokenSupplier} for reactive Vault session management
 * adapting {@link ClientAuthentication} that also implement
 * {@link AuthenticationStepsFactory}.
 * @see AuthenticationStepsFactory
 */
@Bean
@ConditionalOnMissingBean(name = "vaultTokenSupplier")
@ConditionalOnAuthentication
public VaultTokenSupplier vaultTokenSupplier(ListableBeanFactory beanFactory) {

	Assert.notNull(beanFactory, "BeanFactory must not be null");

	String[] authStepsFactories = beanFactory
			.getBeanNamesForType(AuthenticationStepsFactory.class);

	if (!ObjectUtils.isEmpty(authStepsFactories)) {

		AuthenticationStepsFactory factory = beanFactory
				.getBean(AuthenticationStepsFactory.class);
		return createAuthenticationStepsOperator(factory);
	}

	String[] clientAuthentications = beanFactory
			.getBeanNamesForType(ClientAuthentication.class);

	if (!ObjectUtils.isEmpty(clientAuthentications)) {

		ClientAuthentication clientAuthentication = beanFactory
				.getBean(ClientAuthentication.class);

		if (clientAuthentication instanceof TokenAuthentication) {

			TokenAuthentication authentication = (TokenAuthentication) clientAuthentication;
			return () -> Mono.just(authentication.login());
		}

		if (clientAuthentication instanceof AuthenticationStepsFactory) {
			return createAuthenticationStepsOperator(
					(AuthenticationStepsFactory) clientAuthentication);
		}

		throw new IllegalStateException(String.format(
				"Cannot construct VaultTokenSupplier from %s. "
						+ "ClientAuthentication must implement AuthenticationStepsFactory or be TokenAuthentication",
				clientAuthentication));
	}

	throw new IllegalStateException(
			"Cannot construct VaultTokenSupplier. Please configure VaultTokenSupplier bean named vaultTokenSupplier.");
}