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

The following examples show how to use org.springframework.beans.factory.config.ConfigurableListableBeanFactory#containsBean() . 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: RemoteConfigSourceConfigured.java    From kork with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matches(ConditionContext context, @NotNull AnnotatedTypeMetadata metadata) {
  ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
  if (beanFactory != null) {
    Environment environment = context.getEnvironment();
    String remoteRepoTypes =
        environment.getProperty(
            "spring.cloud.config.remote-repo-types", DEFAULT_REMOTE_REPO_TYPES);

    for (String remoteRepoType : StringUtils.split(remoteRepoTypes, ',')) {
      if (beanFactory.containsBean(remoteRepoType + "EnvironmentRepository")
          || beanFactory.containsBean(remoteRepoType + "-env-repo0")) {
        return true;
      }
    }
  }
  return false;
}
 
Example 2
Source File: RemoteProxyBeanCreator.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected void processSubstitutions(ConfigurableListableBeanFactory beanFactory) {
    if (substitutions != null) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

        for (Map.Entry<String, String> entry : substitutions.entrySet()) {
            // replace bean with substitution bean
            if (beanFactory.containsBean(entry.getKey())) {
                String beanName = entry.getKey();
                String beanClass = entry.getValue();

                BeanDefinition definition = new RootBeanDefinition(beanClass);
                MutablePropertyValues propertyValues = definition.getPropertyValues();
                propertyValues.add("substitutedBean", beanFactory.getBean(beanName));
                registry.registerBeanDefinition(beanName, definition);
            }
        }
    }
}
 
Example 3
Source File: CustomizedMessageSourceBeanDemo.java    From geekbang-lessons with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        ConfigurableApplicationContext applicationContext =
                // Primary Configuration Class
                new SpringApplicationBuilder(CustomizedMessageSourceBeanDemo.class)
                        .web(WebApplicationType.NONE)
                        .run(args);

        ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();

        if (beanFactory.containsBean(AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME)) {
            // 查找 MessageSource 的 BeanDefinition
            System.out.println(beanFactory.getBeanDefinition(AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME));
            // 查找 MessageSource Bean
            MessageSource messageSource = applicationContext.getBean(AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
            System.out.println(messageSource);
        }

        // 关闭应用上下文
        applicationContext.close();
    }
 
Example 4
Source File: BeanFactoryAnnotationUtils.java    From spring4-understanding with Apache License 2.0 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 BeanFactory 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})
 * @throws NoSuchBeanDefinitionException if no matching bean of type {@code T} found
 */
private static <T> T qualifiedBeanOfType(ConfigurableListableBeanFactory bf, Class<T> beanType, String qualifier) {
	String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
	String matchingBean = null;
	for (String beanName : candidateBeans) {
		if (isQualifierMatch(qualifier, beanName, bf)) {
			if (matchingBean != null) {
				throw new NoSuchBeanDefinitionException(qualifier, "No unique " + beanType.getSimpleName() +
						" bean found for qualifier '" + qualifier + "'");
			}
			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 5
Source File: AbstractApplicationContext.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Finish the initialization of this context's bean factory,
 * initializing all remaining singleton beans.
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// Initialize conversion service for this context.
	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
		beanFactory.setConversionService(
				beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
	}

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

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

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

	// Instantiate all remaining (non-lazy-init) singletons.
	beanFactory.preInstantiateSingletons();
}
 
Example 6
Source File: BeanFactoryAnnotationUtils.java    From lams with GNU General Public License v2.0 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 BeanFactory 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(ConfigurableListableBeanFactory bf, Class<T> beanType, String qualifier) {
	String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
	String matchingBean = null;
	for (String beanName : candidateBeans) {
		if (isQualifierMatch(qualifier, 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: AbstractApplicationContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Finish the initialization of this context's bean factory,
 * initializing all remaining singleton beans.
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// Initialize conversion service for this context.
	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
		beanFactory.setConversionService(
				beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
	}

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

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

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

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

	// Instantiate all remaining (non-lazy-init) singletons.
	beanFactory.preInstantiateSingletons();
}
 
Example 8
Source File: BeanFactoryAnnotationUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Check whether the named bean declares a qualifier of the given name.
 * @param qualifier the qualifier to match
 * @param beanName the name of the candidate bean
 * @param bf the {@code BeanFactory} from which to retrieve the named bean
 * @return {@code true} if either the bean definition (in the XML case)
 * or the bean's factory method (in the {@code @Bean} case) defines a matching
 * qualifier value (through {@code <qualifier>} or {@code @Qualifier})
 */
private static boolean isQualifierMatch(String qualifier, String beanName, ConfigurableListableBeanFactory bf) {
	if (bf.containsBean(beanName)) {
		try {
			BeanDefinition bd = bf.getMergedBeanDefinition(beanName);
			if (bd instanceof AbstractBeanDefinition) {
				AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
				AutowireCandidateQualifier candidate = abd.getQualifier(Qualifier.class.getName());
				if ((candidate != null && qualifier.equals(candidate.getAttribute(AutowireCandidateQualifier.VALUE_KEY))) ||
						qualifier.equals(beanName) || ObjectUtils.containsElement(bf.getAliases(beanName), qualifier)) {
					return true;
				}
			}
			if (bd instanceof RootBeanDefinition) {
				Method factoryMethod = ((RootBeanDefinition) bd).getResolvedFactoryMethod();
				if (factoryMethod != null) {
					Qualifier targetAnnotation = factoryMethod.getAnnotation(Qualifier.class);
					if (targetAnnotation != null && qualifier.equals(targetAnnotation.value())) {
						return true;
					}
				}
			}
		}
		catch (NoSuchBeanDefinitionException ex) {
			// Ignore - can't compare qualifiers for a manually registered singleton object
		}
	}
	return false;
}
 
Example 9
Source File: AbstractApplicationContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Configure the factory's standard context characteristics,
 * such as the context's ClassLoader and post-processors.
 * @param beanFactory the BeanFactory to configure
 */
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	beanFactory.setBeanClassLoader(getClassLoader());
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// Configure the bean factory with context callbacks.
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);

	// BeanFactory interface not registered as resolvable type in a plain factory.
	// MessageSource registered (and found for autowiring) as a bean.
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// Set a temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	// Register default environment beans.
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}
 
Example 10
Source File: BeanFactoryAnnotationUtils.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Check whether the named bean declares a qualifier of the given name.
 * @param qualifier the qualifier to match
 * @param beanName the name of the candidate bean
 * @param bf the {@code BeanFactory} from which to retrieve the named bean
 * @return {@code true} if either the bean definition (in the XML case)
 * or the bean's factory method (in the {@code @Bean} case) defines a matching
 * qualifier value (through {@code <qualifier>} or {@code @Qualifier})
 */
private static boolean isQualifierMatch(String qualifier, String beanName, ConfigurableListableBeanFactory bf) {
	if (bf.containsBean(beanName)) {
		try {
			BeanDefinition bd = bf.getMergedBeanDefinition(beanName);
			if (bd instanceof AbstractBeanDefinition) {
				AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
				AutowireCandidateQualifier candidate = abd.getQualifier(Qualifier.class.getName());
				if ((candidate != null && qualifier.equals(candidate.getAttribute(AutowireCandidateQualifier.VALUE_KEY))) ||
						qualifier.equals(beanName) || ObjectUtils.containsElement(bf.getAliases(beanName), qualifier)) {
					return true;
				}
			}
			if (bd instanceof RootBeanDefinition) {
				Method factoryMethod = ((RootBeanDefinition) bd).getResolvedFactoryMethod();
				if (factoryMethod != null) {
					Qualifier targetAnnotation = factoryMethod.getAnnotation(Qualifier.class);
					if (targetAnnotation != null && qualifier.equals(targetAnnotation.value())) {
						return true;
					}
				}
			}
		}
		catch (NoSuchBeanDefinitionException ex) {
			// ignore - can't compare qualifiers for a manually registered singleton object
		}
	}
	return false;
}
 
Example 11
Source File: AbstractApplicationContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Instantiate and invoke all registered BeanFactoryPostProcessor beans,
 * respecting explicit order if given.
 * <p>Must be called before singleton instantiation.
 */
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

	// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
	// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
	if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}
}
 
Example 12
Source File: BeanExtender.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
{
    ParameterCheck.mandatory("beanName", beanName);
    ParameterCheck.mandatory("extendingBeanName", extendingBeanName);

    // check for bean name
    if (!beanFactory.containsBean(beanName))
    {
        throw new NoSuchBeanDefinitionException("Can't find bean '" + beanName + "' to be extended.");
    }

    // check for extending bean
    if (!beanFactory.containsBean(extendingBeanName))
    {
        throw new NoSuchBeanDefinitionException("Can't find bean '" + extendingBeanName + "' that is going to extend original bean definition.");
    }

    // get the bean definitions
    BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
    BeanDefinition extendingBeanDefinition = beanFactory.getBeanDefinition(extendingBeanName);

    // update class
    if (StringUtils.isNotBlank(extendingBeanDefinition.getBeanClassName()) &&
        !beanDefinition.getBeanClassName().equals(extendingBeanDefinition.getBeanClassName()))
    {
        beanDefinition.setBeanClassName(extendingBeanDefinition.getBeanClassName());
    }

    // update properties
    MutablePropertyValues properties = beanDefinition.getPropertyValues();
    MutablePropertyValues extendingProperties = extendingBeanDefinition.getPropertyValues();
    for (PropertyValue propertyValue : extendingProperties.getPropertyValueList())
    {
        properties.add(propertyValue.getName(), propertyValue.getValue());
    }
}
 
Example 13
Source File: AbstractApplicationContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Finish the initialization of this context's bean factory,
 * initializing all remaining singleton beans.
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// Initialize conversion service for this context.
	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
		beanFactory.setConversionService(
				beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
	}

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

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

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

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

	// Instantiate all remaining (non-lazy-init) singletons.
	beanFactory.preInstantiateSingletons();
}
 
Example 14
Source File: AbstractApplicationContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Instantiate and invoke all registered BeanFactoryPostProcessor beans,
 * respecting explicit order if given.
 * <p>Must be called before singleton instantiation.
 */
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

	// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
	// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
	if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}
}
 
Example 15
Source File: AbstractApplicationContext.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Finish the initialization of this context's bean factory,
 * initializing all remaining singleton beans.
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// Initialize conversion service for this context.
	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
		beanFactory.setConversionService(
				beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
	}

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

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

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

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

	// Instantiate all remaining (non-lazy-init) singletons.
	beanFactory.preInstantiateSingletons();
}
 
Example 16
Source File: AbstractApplicationContext.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Instantiate and invoke all registered BeanFactoryPostProcessor beans,
 * respecting explicit order if given.
 * <p>Must be called before singleton instantiation.
 */
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	// getBeanFactoryPostProcessors(): 获取当前应用上下文 beanFactoryPostProcessors 变量
	// invokeBeanFactoryPostProcessors(): 实例化并调用所有已注册的 BeanFactoryPostProcessor 后处理器
	PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

	// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
	// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
	if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}
}
 
Example 17
Source File: AbstractApplicationContext.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Configure the factory's standard context characteristics,
 * such as the context's ClassLoader and post-processors.
 * @param beanFactory the BeanFactory to configure
 */
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	beanFactory.setBeanClassLoader(getClassLoader());
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// Configure the bean factory with context callbacks.
	// 这一步中,给 beanFactory 注册了个 beanPostProcessor,后处理器的类型是 ApplicationContextAwareProcessor
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
	beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

	// BeanFactory interface not registered as resolvable type in a plain factory.
	// MessageSource registered (and found for autowiring) as a bean.
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// Register early post-processor for detecting inner beans as ApplicationListeners.
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// Set a temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	// Register default environment beans.
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}
 
Example 18
Source File: AbstractApplicationContext.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Configure the factory's standard context characteristics,
 * such as the context's ClassLoader and post-processors.
 * @param beanFactory the BeanFactory to configure
 */
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	beanFactory.setBeanClassLoader(getClassLoader());
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// Configure the bean factory with context callbacks.
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
	beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

	// BeanFactory interface not registered as resolvable type in a plain factory.
	// MessageSource registered (and found for autowiring) as a bean.
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// Register early post-processor for detecting inner beans as ApplicationListeners.
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// Set a temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	// Register default environment beans.
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}
 
Example 19
Source File: AbstractApplicationContext.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Configure the factory's standard context characteristics,
 * such as the context's ClassLoader and post-processors.
 * @param beanFactory the BeanFactory to configure
 */
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	beanFactory.setBeanClassLoader(getClassLoader());
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// Configure the bean factory with context callbacks.
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
	beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

	// BeanFactory interface not registered as resolvable type in a plain factory.
	// MessageSource registered (and found for autowiring) as a bean.
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// Register early post-processor for detecting inner beans as ApplicationListeners.
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// Set a temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	// Register default environment beans.
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}
 
Example 20
Source File: AutoProxyBeanFactory.java    From framework with Apache License 2.0 4 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author yang.zhipeng <br>
 * @taskId <br>
 * @param beanFactory <br>
 * @throws BeansException <br>
 */
@Override
public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException {
    logger.info("*************************Dao注入列表***************************");
    SQLHandler sqlHandler = new SQLHandler();
    sqlHandler.setDaoConfig(config);

    ICache cache = CacheHelper.getCache();
    cache.removeNode(CacheConstant.SQL_PARAM_DIR);
    cache.removeNode(CacheConstant.SQL_DIR);

    try {
        for (String pack : packagesToScan) {
            if (StringUtils.isNotEmpty(pack)) {
                Set<Class<?>> clazzSet = BeanUtil.getClasses(pack);
                String className = null;
                for (Class<?> clazz : clazzSet) {
                    if (clazz.isAnnotationPresent(Dao.class)) {
                        className = clazz.getName();
                        String beanName = StringUtils.uncapitalize(clazz.getSimpleName());
                        if (beanFactory.containsBean(beanName)) {
                            beanName = className;
                            if (beanFactory.containsBean(beanName)) {
                                continue;
                            }
                        }

                        // 此处不缓存SQL
                        sqlHandler.invoke(clazz);

                        // 单独加载一个接口的代理类
                        ProxyFactoryBean factoryBean = new ProxyFactoryBean();
                        factoryBean.setBeanFactory(beanFactory);
                        factoryBean.setInterfaces(clazz);
                        factoryBean.setInterceptorNames(interceptors);
                        factoryBean.setTarget(getDaoHandler(clazz));
                        beanFactory.registerSingleton(beanName, factoryBean);
                        logger.info("    success create interface [{0}] with name {1}", className, beanName);
                    }
                }
            }
        }
    }
    catch (Exception e) {
        logger.error("------->自动扫描jar包失败", e);
    }
    logger.info("***********************************************************");
}