Java Code Examples for org.springframework.beans.factory.ListableBeanFactory

The following examples show how to use org.springframework.beans.factory.ListableBeanFactory. These examples are extracted from open source projects. 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
@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 2
Source Project: spring-analysis-note   Source File: EntityManagerFactoryUtils.java    License: 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 3
/**
 * 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 4
Source Project: spring-analysis-note   Source File: BeanFactoryAnnotationUtils.java    License: 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 5
Source Project: spring-analysis-note   Source File: BeanFactoryAnnotationUtils.java    License: 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 6
@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 7
Source Project: java-technology-stack   Source File: EntityManagerFactoryUtils.java    License: 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 8
/**
 * 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 9
Source Project: jpetstore-kubernetes   Source File: OrderServiceClient.java    License: 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 10
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 11
Source Project: java-technology-stack   Source File: BeanFactoryAnnotationUtils.java    License: 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 12
Source Project: java-technology-stack   Source File: BeanFactoryAnnotationUtils.java    License: 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 Project: lams   Source File: SchedulerAccessorBean.java    License: 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 14
Source Project: foremast   Source File: MeterRegistryPostProcessor.java    License: 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 15
Source Project: foremast   Source File: MeterRegistryPostProcessor.java    License: 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
@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 17
Source Project: sdn-rx   Source File: ReactiveNeo4jRepositoryFactory.java    License: 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);
		});
	}
}
 
Example 18
/**
 * Creates a new factory with the given {@link MessageSource} to get messages
 * depending on the locale.
 * @param messageSource to get i18n messages from
 */
public EntityFormatAnnotationFormatterFactory(MessageSource messageSource,
    ListableBeanFactory beanFactory, ConversionService conversionService,
    String defaultExpression) {
  this.messageSource = messageSource;
  this.conversionService = conversionService;
  this.defaultExpression = defaultExpression;
  this.entity2Resolver = loadEntityResolvers(beanFactory);
}
 
Example 19
/**
 * 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 20
Source Project: spring-analysis-note   Source File: MBeanExporter.java    License: MIT License 5 votes vote down vote up
/**
 * This callback is only required for resolution of bean names in the
 * {@link #setBeans(java.util.Map) "beans"} {@link Map} and for
 * autodetection of MBeans (in the latter case, a
 * {@code ListableBeanFactory} is required).
 * @see #setBeans
 * @see #setAutodetect
 */
@Override
public void setBeanFactory(BeanFactory beanFactory) {
	if (beanFactory instanceof ListableBeanFactory) {
		this.beanFactory = (ListableBeanFactory) beanFactory;
	}
	else {
		logger.debug("MBeanExporter not running in a ListableBeanFactory: autodetection of MBeans not available.");
	}
}
 
Example 21
/**
 * 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 22
/**
 * Create a new PersistenceExceptionTranslationAdvisor.
 * @param beanFactory the ListableBeanFactory to obtaining all
 * PersistenceExceptionTranslators from
 * @param repositoryAnnotationType the annotation type to check for
 */
PersistenceExceptionTranslationAdvisor(
		ListableBeanFactory beanFactory, Class<? extends Annotation> repositoryAnnotationType) {

	this.advice = new PersistenceExceptionTranslationInterceptor(beanFactory);
	this.pointcut = new AnnotationMatchingPointcut(repositoryAnnotationType, true);
}
 
Example 23
@SuppressWarnings({"rawtypes"})
private static Map<Class<?>, EntityResolver<?, ?>> loadEntityResolvers(
    ListableBeanFactory beanFactory) {
  Map<String, EntityResolver> entityServices = beanFactory.getBeansOfType(EntityResolver.class);
  Map<Class<?>, EntityResolver<?, ?>> entity2Resolver = new HashMap<>(entityServices.size());
  for (EntityResolver entityResolver : entityServices.values()) {
    entity2Resolver.put(entityResolver.getEntityType(), entityResolver);
  }
  return entity2Resolver;
}
 
Example 24
/** Subclasses must initialize this */
protected ListableBeanFactory getListableBeanFactory() {
	BeanFactory bf = getBeanFactory();
	if (!(bf instanceof ListableBeanFactory)) {
		throw new IllegalStateException("ListableBeanFactory required");
	}
	return (ListableBeanFactory) bf;
}
 
Example 25
/**
 * Obtains all web service beans and publishes them as JAX-WS endpoints.
 */
@Override
public void setBeanFactory(BeanFactory beanFactory) {
	if (!(beanFactory instanceof ListableBeanFactory)) {
		throw new IllegalStateException(getClass().getSimpleName() + " requires a ListableBeanFactory");
	}
	this.beanFactory = (ListableBeanFactory) beanFactory;
}
 
Example 26
@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 27
/**
 * 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 28
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 29
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 Project: geekbang-lessons   Source File: DependencyLookupDemo.java    License: 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);
    }
}