org.springframework.beans.factory.ListableBeanFactory Java Examples

The following examples show how to use org.springframework.beans.factory.ListableBeanFactory. 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: MeterRegistryPostProcessor.java    From foremast with Apache License 2.0 6 votes vote down vote up
private MeterRegistryConfigurer getConfigurer() {
    if (this.configurer == null) {
        Collection<MeterBinder> meterBinders = Collections.emptyList();
        Collection<MeterFilter> meterFilters = Collections.emptyList();
        Collection<MeterRegistryCustomizer<?>> meterRegistryCustomizers = Collections.emptyList();
        MetricsProperties properties = beanFactory.getBean(MetricsProperties.class);
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory)beanFactory;
            meterBinders = listableBeanFactory.getBeansOfType(MeterBinder.class).values();
            meterFilters = listableBeanFactory.getBeansOfType(MeterFilter.class).values();
            Map<String, MeterRegistryCustomizer> map = listableBeanFactory.getBeansOfType(MeterRegistryCustomizer.class);
            meterRegistryCustomizers = new ArrayList<>();
            for(MeterRegistryCustomizer c : map.values()) {
                meterRegistryCustomizers.add(c);
            }
        }
        this.configurer = new MeterRegistryConfigurer(
                meterBinders,
                meterFilters,
                meterRegistryCustomizers, properties.isUseGlobalRegistry());
    }
    return this.configurer;
}
 
Example #2
Source File: NotifyManager.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Notifica un evento ai corrispondenti servizi osservatori.
 * @param event L'evento da notificare.
 */
protected void notify(ApsEvent event) {
	ListableBeanFactory factory = (ListableBeanFactory) this._beanFactory;
	String[] defNames = factory.getBeanNamesForType(event.getObserverInterface());
	for (int i=0; i<defNames.length; i++) {
		Object observer = null;
		try {
			observer = this._beanFactory.getBean(defNames[i]);
		} catch (Throwable t) {
			observer = null;
		}
		if (observer != null) {
			((ObserverService) observer).update(event);
			_logger.debug("The event {} was notified to the {} service", event.getClass().getName(), observer.getClass().getName());
		}
	}
	_logger.debug("The {} has been notified", event.getClass().getName());
}
 
Example #3
Source File: OrderServiceClient.java    From jpetstore-kubernetes with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	if (args.length == 0 || "".equals(args[0])) {
		System.out.println(
				"You need to specify an order ID and optionally a number of calls, e.g. for order ID 1000: " +
				"'client 1000' for a single call per service or 'client 1000 10' for 10 calls each");
	}
	else {
		int orderId = Integer.parseInt(args[0]);
		int nrOfCalls = 1;
		if (args.length > 1 && !"".equals(args[1])) {
			nrOfCalls = Integer.parseInt(args[1]);
		}
		ListableBeanFactory beanFactory = new FileSystemXmlApplicationContext(CLIENT_CONTEXT_CONFIG_LOCATION);
		OrderServiceClient client = new OrderServiceClient(beanFactory);
		client.invokeOrderServices(orderId, nrOfCalls);
	}
}
 
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: ConfigurationClassProcessingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void configWithFactoryBeanReturnType() {
	ListableBeanFactory factory = initBeanFactory(ConfigWithNonSpecificReturnTypes.class);
	assertEquals(List.class, factory.getType("factoryBean"));
	assertTrue(factory.isTypeMatch("factoryBean", List.class));
	assertEquals(FactoryBean.class, factory.getType("&factoryBean"));
	assertTrue(factory.isTypeMatch("&factoryBean", FactoryBean.class));
	assertFalse(factory.isTypeMatch("&factoryBean", BeanClassLoaderAware.class));
	assertFalse(factory.isTypeMatch("&factoryBean", ListFactoryBean.class));
	assertTrue(factory.getBean("factoryBean") instanceof List);

	String[] beanNames = factory.getBeanNamesForType(FactoryBean.class);
	assertEquals(1, beanNames.length);
	assertEquals("&factoryBean", beanNames[0]);

	beanNames = factory.getBeanNamesForType(BeanClassLoaderAware.class);
	assertEquals(1, beanNames.length);
	assertEquals("&factoryBean", beanNames[0]);

	beanNames = factory.getBeanNamesForType(ListFactoryBean.class);
	assertEquals(1, beanNames.length);
	assertEquals("&factoryBean", beanNames[0]);

	beanNames = factory.getBeanNamesForType(List.class);
	assertEquals("factoryBean", beanNames[0]);
}
 
Example #6
Source File: OrderServiceClient.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void main(String[] args) {
	if (args.length == 0 || "".equals(args[0])) {
		System.out.println(
				"You need to specify an order ID and optionally a number of calls, e.g. for order ID 1000: " +
				"'client 1000' for a single call per service or 'client 1000 10' for 10 calls each");
	}
	else {
		int orderId = Integer.parseInt(args[0]);
		int nrOfCalls = 1;
		if (args.length > 1 && !"".equals(args[1])) {
			nrOfCalls = Integer.parseInt(args[1]);
		}
		ListableBeanFactory beanFactory = new FileSystemXmlApplicationContext(CLIENT_CONTEXT_CONFIG_LOCATION);
		OrderServiceClient client = new OrderServiceClient(beanFactory);
		client.invokeOrderServices(orderId, nrOfCalls);
	}
}
 
Example #7
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 #8
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. via {@code <qualifier>} or {@code @Qualifier}) matching the given
 * qualifier, or having a bean name matching the given qualifier.
 * @param beanFactory the factory to get the target bean from (also searching ancestors)
 * @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})
 * @throws NoUniqueBeanDefinitionException if multiple matching beans of type {@code T} found
 * @throws NoSuchBeanDefinitionException if no matching bean of type {@code T} found
 * @throws BeansException if the bean could not be created
 * @see BeanFactoryUtils#beanOfTypeIncludingAncestors(ListableBeanFactory, Class)
 */
public static <T> T qualifiedBeanOfType(BeanFactory beanFactory, Class<T> beanType, String qualifier)
		throws BeansException {

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

	if (beanFactory instanceof ListableBeanFactory) {
		// Full qualifier matching supported.
		return qualifiedBeanOfType((ListableBeanFactory) beanFactory, beanType, qualifier);
	}
	else if (beanFactory.containsBean(qualifier)) {
		// Fallback: target bean at least found by bean name.
		return beanFactory.getBean(qualifier, beanType);
	}
	else {
		throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
				" bean found for bean name '" + qualifier +
				"'! (Note: Qualifier matching not supported because given " +
				"BeanFactory does not implement ConfigurableListableBeanFactory.)");
	}
}
 
Example #9
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 #10
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. via {@code <qualifier>} or {@code @Qualifier}) matching the given
 * qualifier, or having a bean name matching the given qualifier.
 * @param beanFactory the factory to get the target bean from (also searching ancestors)
 * @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})
 * @throws NoUniqueBeanDefinitionException if multiple matching beans of type {@code T} found
 * @throws NoSuchBeanDefinitionException if no matching bean of type {@code T} found
 * @throws BeansException if the bean could not be created
 * @see BeanFactoryUtils#beanOfTypeIncludingAncestors(ListableBeanFactory, Class)
 */
public static <T> T qualifiedBeanOfType(BeanFactory beanFactory, Class<T> beanType, String qualifier)
		throws BeansException {

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

	if (beanFactory instanceof ListableBeanFactory) {
		// Full qualifier matching supported.
		return qualifiedBeanOfType((ListableBeanFactory) beanFactory, beanType, qualifier);
	}
	else if (beanFactory.containsBean(qualifier)) {
		// Fallback: target bean at least found by bean name.
		return beanFactory.getBean(qualifier, beanType);
	}
	else {
		throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
				" bean found for bean name '" + qualifier +
				"'! (Note: Qualifier matching not supported because given " +
				"BeanFactory does not implement ConfigurableListableBeanFactory.)");
	}
}
 
Example #11
Source File: AmazonRdsInstanceConfiguration.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
	if (beanFactory instanceof ListableBeanFactory) {
		Collection<RdsInstanceConfigurer> configurer = ((ListableBeanFactory) beanFactory)
				.getBeansOfType(RdsInstanceConfigurer.class).values();

		if (configurer.isEmpty()) {
			return;
		}

		if (configurer.size() > 1) {
			throw new IllegalStateException(
					"Only one RdsInstanceConfigurer may exist");
		}

		this.rdsInstanceConfigurer = configurer.iterator().next();
	}
}
 
Example #12
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 #13
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 #14
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 #15
Source File: MeterRegistryPostProcessor.java    From foremast with Apache License 2.0 6 votes vote down vote up
private MeterRegistryConfigurer getConfigurer() {
    if (this.configurer == null) {
        Collection<MeterBinder> meterBinders = Collections.emptyList();
        Collection<MeterFilter> meterFilters = Collections.emptyList();
        Collection<MeterRegistryCustomizer<?>> meterRegistryCustomizers = Collections.emptyList();
        MetricsProperties properties = beanFactory.getBean(MetricsProperties.class);
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory)beanFactory;
            meterBinders = listableBeanFactory.getBeansOfType(MeterBinder.class).values();
            meterFilters = listableBeanFactory.getBeansOfType(MeterFilter.class).values();
            Map<String, MeterRegistryCustomizer> map = listableBeanFactory.getBeansOfType(MeterRegistryCustomizer.class);
            meterRegistryCustomizers = new ArrayList<>();
            for(MeterRegistryCustomizer c : map.values()) {
                meterRegistryCustomizers.add(c);
            }
        }
        this.configurer = new MeterRegistryConfigurer(
                meterBinders,
                meterFilters,
                meterRegistryCustomizers, properties.isUseGlobalRegistry());
    }
    return this.configurer;
}
 
Example #16
Source File: SpringExtensionsRegistryFactory.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ExtensionsRegistry createRegistry(String registryId,
		JRPropertiesMap properties)
{
	ListableBeanFactory beanFactory = getBeanFactory(registryId, properties);
	return new SpringExtensionsRegistry(beanFactory);
}
 
Example #17
Source File: BeanFactoryAspectJAdvisorsBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new BeanFactoryAspectJAdvisorsBuilder for the given BeanFactory.
 * @param beanFactory the ListableBeanFactory to scan
 * @param advisorFactory the AspectJAdvisorFactory to build each Advisor with
 */
public BeanFactoryAspectJAdvisorsBuilder(ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) {
	Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
	Assert.notNull(advisorFactory, "AspectJAdvisorFactory must not be null");
	this.beanFactory = beanFactory;
	this.advisorFactory = advisorFactory;
}
 
Example #18
Source File: AbstractListableBeanFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/** Subclasses must initialize this */
protected ListableBeanFactory getListableBeanFactory() {
	BeanFactory bf = getBeanFactory();
	if (!(bf instanceof ListableBeanFactory)) {
		throw new IllegalStateException("ListableBeanFactory required");
	}
	return (ListableBeanFactory) bf;
}
 
Example #19
Source File: StackResourceRegistryDetectingResourceIdResolver.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private static StackResourceRegistry findSingleOptionalStackResourceRegistry(
		ListableBeanFactory beanFactory) {
	Collection<StackResourceRegistry> stackResourceRegistries = beanFactory
			.getBeansOfType(StackResourceRegistry.class).values();

	if (stackResourceRegistries.size() > 1) {
		throw new IllegalStateException("Multiple stack resource registries found");
	}
	else if (stackResourceRegistries.size() == 1) {
		return stackResourceRegistries.iterator().next();
	}
	else {
		return null;
	}
}
 
Example #20
Source File: DependencyLookupDemo.java    From geekbang-lessons with Apache License 2.0 5 votes vote down vote up
private static void lookupByAnnotationType(BeanFactory beanFactory) {
    if (beanFactory instanceof ListableBeanFactory) {
        ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
        Map<String, User> users = (Map) listableBeanFactory.getBeansWithAnnotation(Super.class);
        System.out.println("查找标注 @Super 所有的 User 集合对象:" + users);
    }
}
 
Example #21
Source File: LookoutAutoConfiguration.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
protected void configureLookoutConfig(LookoutConfig config) {
    if (beanFactory instanceof ListableBeanFactory
        && ((ListableBeanFactory) beanFactory).getBeansOfType(MetricConfigCustomizer.class) != null) {
        for (MetricConfigCustomizer configCustomizer : ((ListableBeanFactory) beanFactory)
            .getBeansOfType(MetricConfigCustomizer.class).values()) {
            configCustomizer.customize(config);
        }
    }
}
 
Example #22
Source File: ObjectUtils.java    From spring-init with Apache License 2.0 5 votes vote down vote up
public static <T> ObjectProvider<T[]> array(ListableBeanFactory beans,
		Class<T> type) {
	return new ObjectProvider<T[]>() {

		@SuppressWarnings("unchecked")
		private T[] prototype = (T[]) Array.newInstance(type, 0);

		@Override
		public T[] getObject() throws BeansException {
			return beans.getBeanProvider(type).orderedStream()
					.collect(Collectors.toList()).toArray(prototype);
		}

		@Override
		public T[] getObject(Object... args) throws BeansException {
			return getObject();
		}

		@Override
		public T[] getIfAvailable() throws BeansException {
			return getObject();
		}

		@Override
		public T[] getIfUnique() throws BeansException {
			return getObject();
		}
	};
}
 
Example #23
Source File: LookoutAutoConfiguration.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
protected List<MetricObserver<LookoutMeasurement>> getMetricObservers() {
    List<MetricObserver<LookoutMeasurement>> metricObservers = null;
    if (beanFactory instanceof ListableBeanFactory) {
        Collection<MetricObserver> metricObserverCollection = ((ListableBeanFactory) beanFactory)
            .getBeansOfType(MetricObserver.class).values();
        if (!CollectionUtils.isEmpty(metricObserverCollection)) {
            metricObservers = new ArrayList<MetricObserver<LookoutMeasurement>>();
            for (MetricObserver metricObserver : metricObserverCollection) {
                metricObservers.add(metricObserver);
            }
        }
    }
    return metricObservers;
}
 
Example #24
Source File: JmsListenerAnnotationBeanPostProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void afterSingletonsInstantiated() {
	// Remove resolved singleton classes from cache
	this.nonAnnotatedClasses.clear();

	if (this.beanFactory instanceof ListableBeanFactory) {
		// Apply JmsListenerConfigurer beans from the BeanFactory, if any
		Map<String, JmsListenerConfigurer> beans =
				((ListableBeanFactory) this.beanFactory).getBeansOfType(JmsListenerConfigurer.class);
		List<JmsListenerConfigurer> configurers = new ArrayList<>(beans.values());
		AnnotationAwareOrderComparator.sort(configurers);
		for (JmsListenerConfigurer configurer : configurers) {
			configurer.configureJmsListeners(this.registrar);
		}
	}

	if (this.containerFactoryBeanName != null) {
		this.registrar.setContainerFactoryBeanName(this.containerFactoryBeanName);
	}

	if (this.registrar.getEndpointRegistry() == null) {
		// Determine JmsListenerEndpointRegistry bean from the BeanFactory
		if (this.endpointRegistry == null) {
			Assert.state(this.beanFactory != null, "BeanFactory must be set to find endpoint registry by bean name");
			this.endpointRegistry = this.beanFactory.getBean(
					JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME, JmsListenerEndpointRegistry.class);
		}
		this.registrar.setEndpointRegistry(this.endpointRegistry);
	}


	// Set the custom handler method factory once resolved by the configurer
	MessageHandlerMethodFactory handlerMethodFactory = this.registrar.getMessageHandlerMethodFactory();
	if (handlerMethodFactory != null) {
		this.messageHandlerMethodFactory.setMessageHandlerMethodFactory(handlerMethodFactory);
	}

	// Actually register all listeners
	this.registrar.afterPropertiesSet();
}
 
Example #25
Source File: BeanFactoryAspectJAdvisorsBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new BeanFactoryAspectJAdvisorsBuilder for the given BeanFactory.
 * @param beanFactory the ListableBeanFactory to scan
 * @param advisorFactory the AspectJAdvisorFactory to build each Advisor with
 */
public BeanFactoryAspectJAdvisorsBuilder(ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) {
	Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
	Assert.notNull(advisorFactory, "AspectJAdvisorFactory must not be null");
	this.beanFactory = beanFactory;
	this.advisorFactory = advisorFactory;
}
 
Example #26
Source File: SpringBootBeanNameResolver.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
/**
 * Will ignore scoped proxy target bean names. https://github.com/ocpsoft/rewrite/issues/170
 *
 * @param beanFactory bean factory
 * @param clazz       type
 * @return set of bean names
 */
private Set<String> resolveBeanNames(ListableBeanFactory beanFactory, Class<?> clazz) {

	final Set<String> result = new HashSet<String>();

	Map<String, ?> beanMap = beanFactory.getBeansOfType(clazz);
	for (String name : beanMap.keySet()) {
		if (name != null && !name.startsWith("scopedTarget.")) {
			result.add(name);
		}
	}

	return result;

}
 
Example #27
Source File: EntityManagerFactoryAccessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieves an EntityManagerFactory by persistence unit name, if none set explicitly.
 * Falls back to a default EntityManagerFactory bean if no persistence unit specified.
 * @see #setPersistenceUnitName
 */
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
	if (getEntityManagerFactory() == null) {
		if (!(beanFactory instanceof ListableBeanFactory)) {
			throw new IllegalStateException("Cannot retrieve EntityManagerFactory by persistence unit name " +
					"in a non-listable BeanFactory: " + beanFactory);
		}
		ListableBeanFactory lbf = (ListableBeanFactory) beanFactory;
		setEntityManagerFactory(EntityManagerFactoryUtils.findEntityManagerFactory(lbf, getPersistenceUnitName()));
	}
}
 
Example #28
Source File: ServiceLocatorFactoryBean.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
	if (!(beanFactory instanceof ListableBeanFactory)) {
		throw new FatalBeanException(
				"ServiceLocatorFactoryBean needs to run in a BeanFactory that is a ListableBeanFactory");
	}
	this.beanFactory = (ListableBeanFactory) beanFactory;
}
 
Example #29
Source File: DependencyLookupDemo.java    From geekbang-lessons with Apache License 2.0 5 votes vote down vote up
private static void lookupCollectionByType(BeanFactory beanFactory) {
    if (beanFactory instanceof ListableBeanFactory) {
        ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
        Map<String, User> users = listableBeanFactory.getBeansOfType(User.class);
        System.out.println("查找到的所有的 User 集合对象:" + users);
    }
}
 
Example #30
Source File: ReactiveNeo4jRepositoryFactory.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {

	super.setBeanFactory(beanFactory);

	if (beanFactory instanceof ListableBeanFactory) {
		addRepositoryProxyPostProcessor((factory, repositoryInformation) -> {
			ReactivePersistenceExceptionTranslationInterceptor advice
				= new ReactivePersistenceExceptionTranslationInterceptor((ListableBeanFactory) beanFactory);
			factory.addAdvice(advice);
		});
	}
}