org.springframework.beans.factory.ListableBeanFactory#getBean ( )源码实例Demo

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

/**
 * 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);
	}
}
 
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;
}
 
/**
 * 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!");
	}
}
 
/**
 * 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);
	}
}
 
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;
}
 
/**
 * 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!");
	}
}
 
源代码7 项目: lams   文件: SchedulerAccessorBean.java
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;
}
 
源代码8 项目: lams   文件: EntityManagerFactoryUtils.java
/**
 * 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);
	}
}
 
/**
 * 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);
	}
}
 
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;
}
 
源代码11 项目: haven-platform   文件: JobsManagerImpl.java
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();
}
 
源代码12 项目: brpc-java   文件: SpringBootAnnotationResolver.java
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);
}
 
/**
 * 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()))
        );
    }
}
 
源代码14 项目: spring-context-support   文件: BeanUtils.java
/**
 * 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;

}
 
源代码15 项目: onetwo   文件: SpringUtils.java
/****
 * 
 * @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);
}
 
/**
 * @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.");
}