Java 类org.springframework.beans.factory.BeanFactoryUtils 实例源码

项目:spring-cloud-sockets    文件:DispatcherHandler.java   
@Override
public void afterPropertiesSet() throws Exception {
    String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.applicationContext, Object.class);
    for(String beanName : beanNames){
        Class<?> beanType = this.applicationContext.getType(beanName);
        if(beanType != null){
            final Class<?> userType = ClassUtils.getUserClass(beanType);
            ReflectionUtils.doWithMethods(userType, method -> {
                if(AnnotatedElementUtils.findMergedAnnotation(method, ReactiveSocket.class) != null) {
                    ServiceMethodInfo info = new ServiceMethodInfo(method);
                    logger.info("Registering remote endpoint at path {}, exchange {} for method {}", info.getMappingInfo().getPath(), info.getMappingInfo().getExchangeMode(), method);
                    MethodHandler methodHandler = new MethodHandler(applicationContext.getBean(beanName), info);
                    mappingHandlers.add(methodHandler);
                }
            });
        }
    }
    initDefaultConverters();
}
项目:lams    文件:StaticListableBeanFactory.java   
@Override
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
    String beanName = BeanFactoryUtils.transformedBeanName(name);

    Object bean = this.beans.get(beanName);
    if (bean == null) {
        throw new NoSuchBeanDefinitionException(beanName,
                "Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
    }

    if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
        // If it's a FactoryBean, we want to look at what it creates, not the factory class.
        return ((FactoryBean<?>) bean).getObjectType();
    }
    return bean.getClass();
}
项目:gemini.blueprint    文件:AbstractReferenceDefinitionParser.java   
protected String generateBeanName(String prefix, BeanDefinition def, ParserContext parserContext) {
    BeanDefinitionRegistry registry = parserContext.getRegistry();
    String name = prefix + BeanDefinitionReaderUtils.generateBeanName(def, registry);
    String generated = name;
    int counter = 0;

    while (registry.containsBeanDefinition(generated)) {
        generated = name + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR + counter;
        if (parserContext.isNested()) {
            generated = generated.concat("#generated");
        }
        counter++;
    }

    return generated;
}
项目:lams    文件:DefaultLifecycleProcessor.java   
/**
 * Retrieve all applicable Lifecycle beans: all singletons that have already been created,
 * as well as all SmartLifecycle beans (even if they are marked as lazy-init).
 * @return the Map of applicable beans, with bean names as keys and bean instances as values
 */
protected Map<String, Lifecycle> getLifecycleBeans() {
    Map<String, Lifecycle> beans = new LinkedHashMap<String, Lifecycle>();
    String[] beanNames = this.beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
    for (String beanName : beanNames) {
        String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName);
        boolean isFactoryBean = this.beanFactory.isFactoryBean(beanNameToRegister);
        String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
        if ((this.beanFactory.containsSingleton(beanNameToRegister) &&
                (!isFactoryBean || Lifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck)))) ||
                SmartLifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck))) {
            Lifecycle bean = this.beanFactory.getBean(beanNameToCheck, Lifecycle.class);
            if (bean != this) {
                beans.put(beanNameToRegister, bean);
            }
        }
    }
    return beans;
}
项目:lams    文件:BeanFactoryAnnotationUtils.java   
/**
 * 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) {
    Map<String, T> candidateBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(bf, beanType);
    T matchingBean = null;
    for (String beanName : candidateBeans.keySet()) {
        if (isQualifierMatch(qualifier, beanName, bf)) {
            if (matchingBean != null) {
                throw new NoSuchBeanDefinitionException(qualifier, "No unique " + beanType.getSimpleName() +
                        " bean found for qualifier '" + qualifier + "'");
            }
            matchingBean = candidateBeans.get(beanName);
        }
    }
    if (matchingBean != null) {
        return matchingBean;
    }
    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!");
    }
}
项目:lams    文件:DefaultListableBeanFactory.java   
/**
 * Determine whether the specified bean definition qualifies as an autowire candidate,
 * to be injected into other beans which declare a dependency of matching type.
 * @param beanName the name of the bean definition to check
 * @param descriptor the descriptor of the dependency to resolve
 * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm
 * @return whether the bean should be considered as autowire candidate
 */
protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver)
        throws NoSuchBeanDefinitionException {

    String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName);
    if (containsBeanDefinition(beanDefinitionName)) {
        return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver);
    }
    else if (containsSingleton(beanName)) {
        return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver);
    }
    else if (getParentBeanFactory() instanceof DefaultListableBeanFactory) {
        // No bean definition found in this factory -> delegate to parent.
        return ((DefaultListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName, descriptor, resolver);
    }
    else if (getParentBeanFactory() instanceof ConfigurableListableBeanFactory) {
        // If no DefaultListableBeanFactory, can't pass the resolver along.
        return ((ConfigurableListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName, descriptor);
    }
    else {
        return true;
    }
}
项目:lams    文件:DefaultListableBeanFactory.java   
/**
 * Determine whether the specified bean definition qualifies as an autowire candidate,
 * to be injected into other beans which declare a dependency of matching type.
 * @param beanName the name of the bean definition to check
 * @param mbd the merged bean definition to check
 * @param descriptor the descriptor of the dependency to resolve
 * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm
 * @return whether the bean should be considered as autowire candidate
 */
protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd,
        DependencyDescriptor descriptor, AutowireCandidateResolver resolver) {

    String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName);
    resolveBeanClass(mbd, beanDefinitionName);
    if (mbd.isFactoryMethodUnique) {
        boolean resolve;
        synchronized (mbd.constructorArgumentLock) {
            resolve = (mbd.resolvedConstructorOrFactoryMethod == null);
        }
        if (resolve) {
            new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd);
        }
    }
    return resolver.isAutowireCandidate(
            new BeanDefinitionHolder(mbd, beanName, getAliases(beanDefinitionName)), descriptor);
}
项目:lams    文件:AspectJExpressionPointcut.java   
private FuzzyBoolean contextMatch(Class<?> targetType) {
    String advisedBeanName = getCurrentProxiedBeanName();
    if (advisedBeanName == null) {  // no proxy creation in progress
        // abstain; can't return YES, since that will make pointcut with negation fail
        return FuzzyBoolean.MAYBE;
    }
    if (BeanFactoryUtils.isGeneratedBeanName(advisedBeanName)) {
        return FuzzyBoolean.NO;
    }
    if (targetType != null) {
        boolean isFactory = FactoryBean.class.isAssignableFrom(targetType);
        return FuzzyBoolean.fromBoolean(
                matchesBeanName(isFactory ? BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName : advisedBeanName));
    }
    else {
        return FuzzyBoolean.fromBoolean(matchesBeanName(advisedBeanName) ||
                matchesBeanName(BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName));
    }
}
项目:lams    文件:EntityManagerFactoryUtils.java   
/**
 * Find an EntityManagerFactory with the given name in the given
 * Spring application context (represented as ListableBeanFactory).
 * <p>The specified unit name will be matched against the configured
 * persistence unit, provided that a discovered EntityManagerFactory
 * implements the {@link EntityManagerFactoryInfo} interface. If not,
 * the persistence unit name will be matched against the Spring bean name,
 * assuming that the EntityManagerFactory bean names follow that convention.
 * <p>If no unit name has been given, this method will search for a default
 * EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}.
 * @param beanFactory the ListableBeanFactory to search
 * @param unitName the name of the persistence unit (may be {@code null} or empty,
 * in which case a single bean of type EntityManagerFactory will be searched for)
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 * @see EntityManagerFactoryInfo#getPersistenceUnitName()
 */
public static EntityManagerFactory findEntityManagerFactory(
        ListableBeanFactory beanFactory, String unitName) throws NoSuchBeanDefinitionException {

    Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
    if (StringUtils.hasLength(unitName)) {
        // See whether we can find an EntityManagerFactory with matching persistence unit name.
        String[] candidateNames =
                BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, EntityManagerFactory.class);
        for (String candidateName : candidateNames) {
            EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName);
            if (emf instanceof EntityManagerFactoryInfo) {
                if (unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) {
                    return emf;
                }
            }
        }
        // No matching persistence unit found - simply take the EntityManagerFactory
        // with the persistence unit name as bean name (by convention).
        return beanFactory.getBean(unitName, EntityManagerFactory.class);
    }
    else {
        // Find unique EntityManagerFactory bean in the context, falling back to parent contexts.
        return beanFactory.getBean(EntityManagerFactory.class);
    }
}
项目:lams    文件:PersistenceAnnotationBeanPostProcessor.java   
/**
 * Find a single default EntityManagerFactory in the Spring application context.
 * @return the default EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no single EntityManagerFactory in the context
 */
protected EntityManagerFactory findDefaultEntityManagerFactory(String requestingBeanName)
        throws NoSuchBeanDefinitionException {

    String[] beanNames =
            BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, EntityManagerFactory.class);
    if (beanNames.length == 1) {
        String unitName = beanNames[0];
        EntityManagerFactory emf = (EntityManagerFactory) this.beanFactory.getBean(unitName);
        if (this.beanFactory instanceof ConfigurableBeanFactory) {
            ((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
        }
        return emf;
    }
    else if (beanNames.length > 1) {
        throw new NoUniqueBeanDefinitionException(EntityManagerFactory.class, beanNames);
    }
    else {
        throw new NoSuchBeanDefinitionException(EntityManagerFactory.class);
    }
}
项目:holon-datastore-jpa    文件:JpaRegistrar.java   
/**
 * Get the {@link DataSource} type bean name which corresponds to given data context id
 * @param registry Bean registry
 * @param beanFactory Bean factory
 * @param dataContextId Optional data context id
 * @return The DataSource bean name, or <code>null</code> if not found
 */
private static String getDataSourceBeanName(BeanDefinitionRegistry registry, BeanFactory beanFactory,
        String dataContextId) {
    // check unique DataSource if no data context id specified
    if (dataContextId == null && beanFactory instanceof ListableBeanFactory) {
        String[] dataSourceBeanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                (ListableBeanFactory) beanFactory, DataSource.class, false, false);
        if (dataSourceBeanNames != null && dataSourceBeanNames.length == 1) {
            return dataSourceBeanNames[0];
        }
    }
    // check bean name using data context id
    String dsBeanName = BeanRegistryUtils.buildBeanName(dataContextId,
            EnableDataSource.DEFAULT_DATASOURCE_BEAN_NAME);
    if (registry.containsBeanDefinition(dsBeanName) && beanFactory.isTypeMatch(dsBeanName, DataSource.class)) {
        return dsBeanName;
    }
    return null;
}
项目:holon-datastore-jpa    文件:JpaDatastoreAutoConfigurationRegistrar.java   
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
    // Register JPA Datastore (transactional)
    if (beanFactory instanceof ListableBeanFactory) {
        String[] emfBeanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                (ListableBeanFactory) beanFactory, EntityManagerFactory.class, true, false);
        if (emfBeanNames == null || emfBeanNames.length == 0) {
            emfBeanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) beanFactory,
                    AbstractEntityManagerFactoryBean.class, true, false);
        }
        if (emfBeanNames != null && emfBeanNames.length == 1) {
            String emfBeanName = (emfBeanNames[0].startsWith("&")) ? emfBeanNames[0].substring(1) : emfBeanNames[0];
            JpaDatastoreRegistrar.registerDatastore(registry, null, PrimaryMode.AUTO, emfBeanName, true, false,
                    beanClassLoader);
        }
    }
}
项目:nebo    文件:HessianFilter.java   
public HessianFilter(ServletContext context) {
    WebApplicationContext webApplicationContext = WebApplicationContextUtils.findWebApplicationContext(context);
    String[] strarr = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(webApplicationContext, Object.class);
    for (String s : strarr) {
        Object target = webApplicationContext.getBean(s);
        HessianEndpoint hessianEndpointAnnotation = target.getClass().getAnnotation(HessianEndpoint.class);
        if (hessianEndpointAnnotation != null) {
            try {
                Class apiClz = null;
                Class[] interfacesClass = target.getClass().getInterfaces();
                if (interfacesClass != null && interfacesClass.length > 0) {
                    apiClz = interfacesClass[0];
                } else {
                    apiClz = target.getClass();
                }
                HessianSkeleton hessianSkeleton = new HessianSkeleton(target, apiClz);
                hessianSkeletonMap.put(HessianConstant.HESSIAN_PATH + hessianEndpointAnnotation.servicePattern(), hessianSkeleton);
            } catch (Exception e) {
                logger.error("registerProcessor error : " + e.getMessage(), e);
            }
        }

    }
}
项目:spring4-understanding    文件:AspectJExpressionPointcut.java   
private FuzzyBoolean contextMatch(Class<?> targetType) {
    String advisedBeanName = getCurrentProxiedBeanName();
    if (advisedBeanName == null) {  // no proxy creation in progress
        // abstain; can't return YES, since that will make pointcut with negation fail
        return FuzzyBoolean.MAYBE;
    }
    if (BeanFactoryUtils.isGeneratedBeanName(advisedBeanName)) {
        return FuzzyBoolean.NO;
    }
    if (targetType != null) {
        boolean isFactory = FactoryBean.class.isAssignableFrom(targetType);
        return FuzzyBoolean.fromBoolean(
                matchesBeanName(isFactory ? BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName : advisedBeanName));
    }
    else {
        return FuzzyBoolean.fromBoolean(matchesBeanName(advisedBeanName) ||
                matchesBeanName(BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName));
    }
}
项目:spring4-understanding    文件:DefaultLifecycleProcessor.java   
/**
 * Retrieve all applicable Lifecycle beans: all singletons that have already been created,
 * as well as all SmartLifecycle beans (even if they are marked as lazy-init).
 * @return the Map of applicable beans, with bean names as keys and bean instances as values
 */
protected Map<String, Lifecycle> getLifecycleBeans() {
    Map<String, Lifecycle> beans = new LinkedHashMap<String, Lifecycle>();
    String[] beanNames = this.beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
    for (String beanName : beanNames) {
        String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName);
        boolean isFactoryBean = this.beanFactory.isFactoryBean(beanNameToRegister);
        String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
        if ((this.beanFactory.containsSingleton(beanNameToRegister) &&
                (!isFactoryBean || Lifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck)))) ||
                SmartLifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck))) {
            Lifecycle bean = this.beanFactory.getBean(beanNameToCheck, Lifecycle.class);
            if (bean != this) {
                beans.put(beanNameToRegister, bean);
            }
        }
    }
    return beans;
}
项目:spring4-understanding    文件:EntityManagerFactoryUtils.java   
/**
 * Find an EntityManagerFactory with the given name in the given
 * Spring application context (represented as ListableBeanFactory).
 * <p>The specified unit name will be matched against the configured
 * persistence unit, provided that a discovered EntityManagerFactory
 * implements the {@link EntityManagerFactoryInfo} interface. If not,
 * the persistence unit name will be matched against the Spring bean name,
 * assuming that the EntityManagerFactory bean names follow that convention.
 * <p>If no unit name has been given, this method will search for a default
 * EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}.
 * @param beanFactory the ListableBeanFactory to search
 * @param unitName the name of the persistence unit (may be {@code null} or empty,
 * in which case a single bean of type EntityManagerFactory will be searched for)
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 * @see EntityManagerFactoryInfo#getPersistenceUnitName()
 */
public static EntityManagerFactory findEntityManagerFactory(
        ListableBeanFactory beanFactory, String unitName) throws NoSuchBeanDefinitionException {

    Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
    if (StringUtils.hasLength(unitName)) {
        // See whether we can find an EntityManagerFactory with matching persistence unit name.
        String[] candidateNames =
                BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, EntityManagerFactory.class);
        for (String candidateName : candidateNames) {
            EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName);
            if (emf instanceof EntityManagerFactoryInfo) {
                if (unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) {
                    return emf;
                }
            }
        }
        // No matching persistence unit found - simply take the EntityManagerFactory
        // with the persistence unit name as bean name (by convention).
        return beanFactory.getBean(unitName, EntityManagerFactory.class);
    }
    else {
        // Find unique EntityManagerFactory bean in the context, falling back to parent contexts.
        return beanFactory.getBean(EntityManagerFactory.class);
    }
}
项目:spring4-understanding    文件:PersistenceAnnotationBeanPostProcessor.java   
/**
 * Find a single default EntityManagerFactory in the Spring application context.
 * @return the default EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no single EntityManagerFactory in the context
 */
protected EntityManagerFactory findDefaultEntityManagerFactory(String requestingBeanName)
        throws NoSuchBeanDefinitionException {

    String[] beanNames =
            BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, EntityManagerFactory.class);
    if (beanNames.length == 1) {
        String unitName = beanNames[0];
        EntityManagerFactory emf = (EntityManagerFactory) this.beanFactory.getBean(unitName);
        if (this.beanFactory instanceof ConfigurableBeanFactory) {
            ((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
        }
        return emf;
    }
    else if (beanNames.length > 1) {
        throw new NoUniqueBeanDefinitionException(EntityManagerFactory.class, beanNames);
    }
    else {
        throw new NoSuchBeanDefinitionException(EntityManagerFactory.class);
    }
}
项目:spring4-understanding    文件:ScriptTemplateView.java   
protected ScriptTemplateConfig autodetectViewConfig() throws BeansException {
    try {
        return BeanFactoryUtils.beanOfTypeIncludingAncestors(
                getApplicationContext(), ScriptTemplateConfig.class, true, false);
    }
    catch (NoSuchBeanDefinitionException ex) {
        throw new ApplicationContextException("Expected a single ScriptTemplateConfig bean in the current " +
                "Servlet web application context or the parent root context: ScriptTemplateConfigurer is " +
                "the usual implementation. This bean may have any name.", ex);
    }
}
项目:spring4-understanding    文件:AbstractDetectingUrlHandlerMapping.java   
/**
 * Register all handlers found in the current ApplicationContext.
 * <p>The actual URL determination for a handler is up to the concrete
 * {@link #determineUrlsForHandler(String)} implementation. A bean for
 * which no such URLs could be determined is simply not considered a handler.
 * @throws org.springframework.beans.BeansException if the handler couldn't be registered
 * @see #determineUrlsForHandler(String)
 */
protected void detectHandlers() throws BeansException {
    if (logger.isDebugEnabled()) {
        logger.debug("Looking for URL mappings in application context: " + getApplicationContext());
    }
    String[] beanNames = (this.detectHandlersInAncestorContexts ?
            BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
            getApplicationContext().getBeanNamesForType(Object.class));

    // Take any bean name that we can determine URLs for.
    for (String beanName : beanNames) {
        String[] urls = determineUrlsForHandler(beanName);
        if (!ObjectUtils.isEmpty(urls)) {
            // URL paths found: Let's consider it a handler.
            registerHandler(urls, beanName);
        }
        else {
            if (logger.isDebugEnabled()) {
                logger.debug("Rejected bean name '" + beanName + "': no URL paths identified");
            }
        }
    }
}
项目:spring4-understanding    文件:WebMvcConfigurationSupport.java   
/**
 * Register a {@link ViewResolverComposite} that contains a chain of view resolvers
 * to use for view resolution.
 * By default this resolver is ordered at 0 unless content negotiation view
 * resolution is used in which case the order is raised to
 * {@link org.springframework.core.Ordered#HIGHEST_PRECEDENCE
 * Ordered.HIGHEST_PRECEDENCE}.
 * <p>If no other resolvers are configured,
 * {@link ViewResolverComposite#resolveViewName(String, Locale)} returns null in order
 * to allow other potential {@link ViewResolver} beans to resolve views.
 * @since 4.1
 */
@Bean
public ViewResolver mvcViewResolver() {
    ViewResolverRegistry registry = new ViewResolverRegistry();
    registry.setContentNegotiationManager(mvcContentNegotiationManager());
    registry.setApplicationContext(this.applicationContext);
    configureViewResolvers(registry);

    if (registry.getViewResolvers().isEmpty()) {
        String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                this.applicationContext, ViewResolver.class, true, false);
        if (names.length == 1) {
            registry.getViewResolvers().add(new InternalResourceViewResolver());
        }
    }

    ViewResolverComposite composite = new ViewResolverComposite();
    composite.setOrder(registry.getOrder());
    composite.setViewResolvers(registry.getViewResolvers());
    composite.setApplicationContext(this.applicationContext);
    composite.setServletContext(this.servletContext);
    return composite;
}
项目:spring4-understanding    文件:BeanFactoryAnnotationUtils.java   
/**
 * 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!");
    }
}
项目:spring4-understanding    文件:StaticListableBeanFactory.java   
@Override
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
    String beanName = BeanFactoryUtils.transformedBeanName(name);

    Object bean = this.beans.get(beanName);
    if (bean == null) {
        throw new NoSuchBeanDefinitionException(beanName,
                "Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
    }

    if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
        // If it's a FactoryBean, we want to look at what it creates, not the factory class.
        return ((FactoryBean<?>) bean).getObjectType();
    }
    return bean.getClass();
}
项目:spring4-understanding    文件:DefaultListableBeanFactory.java   
/**
 * Determine whether the specified bean definition qualifies as an autowire candidate,
 * to be injected into other beans which declare a dependency of matching type.
 * @param beanName the name of the bean definition to check
 * @param descriptor the descriptor of the dependency to resolve
 * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm
 * @return whether the bean should be considered as autowire candidate
 */
protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver)
        throws NoSuchBeanDefinitionException {

    String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName);
    if (containsBeanDefinition(beanDefinitionName)) {
        return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver);
    }
    else if (containsSingleton(beanName)) {
        return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver);
    }
    else if (getParentBeanFactory() instanceof DefaultListableBeanFactory) {
        // No bean definition found in this factory -> delegate to parent.
        return ((DefaultListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName, descriptor, resolver);
    }
    else if (getParentBeanFactory() instanceof ConfigurableListableBeanFactory) {
        // If no DefaultListableBeanFactory, can't pass the resolver along.
        return ((ConfigurableListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName, descriptor);
    }
    else {
        return true;
    }
}
项目:spring4-understanding    文件:DefaultListableBeanFactory.java   
/**
 * Determine whether the specified bean definition qualifies as an autowire candidate,
 * to be injected into other beans which declare a dependency of matching type.
 * @param beanName the name of the bean definition to check
 * @param mbd the merged bean definition to check
 * @param descriptor the descriptor of the dependency to resolve
 * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm
 * @return whether the bean should be considered as autowire candidate
 */
protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd,
        DependencyDescriptor descriptor, AutowireCandidateResolver resolver) {

    String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName);
    resolveBeanClass(mbd, beanDefinitionName);
    if (mbd.isFactoryMethodUnique) {
        boolean resolve;
        synchronized (mbd.constructorArgumentLock) {
            resolve = (mbd.resolvedConstructorOrFactoryMethod == null);
        }
        if (resolve) {
            new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd);
        }
    }
    return resolver.isAutowireCandidate(
            new BeanDefinitionHolder(mbd, beanName, getAliases(beanDefinitionName)), descriptor);
}
项目:my-spring-cache-redis    文件:DefaultLifecycleProcessor.java   
/**
 * Retrieve all applicable Lifecycle beans: all singletons that have already been created,
 * as well as all SmartLifecycle beans (even if they are marked as lazy-init).
 * @return the Map of applicable beans, with bean names as keys and bean instances as values
 */
protected Map<String, Lifecycle> getLifecycleBeans() {
    Map<String, Lifecycle> beans = new LinkedHashMap<String, Lifecycle>();
    String[] beanNames = this.beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
    for (String beanName : beanNames) {
        String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName);
        boolean isFactoryBean = this.beanFactory.isFactoryBean(beanNameToRegister);
        String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
        if ((this.beanFactory.containsSingleton(beanNameToRegister) &&
                (!isFactoryBean || Lifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck)))) ||
                SmartLifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck))) {
            Lifecycle bean = this.beanFactory.getBean(beanNameToCheck, Lifecycle.class);
            if (bean != this) {
                beans.put(beanNameToRegister, bean);
            }
        }
    }
    return beans;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:EndpointWebMvcChildContextConfiguration.java   
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
    if (this.managementServerProperties == null) {
        this.managementServerProperties = BeanFactoryUtils
                .beanOfTypeIncludingAncestors(this.beanFactory,
                        ManagementServerProperties.class);
        this.server = BeanFactoryUtils.beanOfTypeIncludingAncestors(
                this.beanFactory, ServerProperties.class);
    }
    // Customize as per the parent context first (so e.g. the access logs go to
    // the same place)
    this.server.customize(container);
    // Then reset the error pages
    container.setErrorPages(Collections.<ErrorPage>emptySet());
    // and the context path
    container.setContextPath("");
    // and add the management-specific bits
    container.setPort(this.managementServerProperties.getPort());
    if (this.managementServerProperties.getSsl() != null) {
        container.setSsl(this.managementServerProperties.getSsl());
    }
    container.setServerHeader(this.server.getServerHeader());
    container.setAddress(this.managementServerProperties.getAddress());
    container.addErrorPages(new ErrorPage(this.server.getError().getPath()));
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:MvcEndpoints.java   
@Override
public void afterPropertiesSet() throws Exception {
    Collection<MvcEndpoint> existing = BeanFactoryUtils
            .beansOfTypeIncludingAncestors(this.applicationContext, MvcEndpoint.class)
            .values();
    this.endpoints.addAll(existing);
    this.customTypes = findEndpointClasses(existing);
    @SuppressWarnings("rawtypes")
    Collection<Endpoint> delegates = BeanFactoryUtils
            .beansOfTypeIncludingAncestors(this.applicationContext, Endpoint.class)
            .values();
    for (Endpoint<?> endpoint : delegates) {
        if (isGenericEndpoint(endpoint.getClass()) && endpoint.isEnabled()) {
            EndpointMvcAdapter adapter = new EndpointMvcAdapter(endpoint);
            String path = determinePath(endpoint,
                    this.applicationContext.getEnvironment());
            if (path != null) {
                adapter.setPath(path);
            }
            this.endpoints.add(adapter);
        }
    }
}
项目:ibole-microservice    文件:RpcClientListenerBean.java   
/**
 * 
 */
private void startRpcClient() {
  // Map<String, RpcRegistery> providerConfigMap =
  // BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RpcRegistery.class,
  // false, false);
  RpcRegistery rpcRegistery =
      BeanFactoryUtils.beanOfType(applicationContext, RpcRegistery.class);
  ServerIdentifier identifier =
      new ServerIdentifier(rpcRegistery.getRootPath(), rpcRegistery.getAddress());
  ClientOptions clientOptions = ClientOptions.DEFAULT;
  clientOptions = clientOptions.withRegistryCenterAddress(identifier)
          .withZoneToPrefer(rpcRegistery.getPreferredZone())
          .withServerHostOverride(getServerHostOverride())
          .withUsedTls(rpcRegistery.isUsedTls());
  RpcClientProvider.provider().getRpcClient().initialize(clientOptions);
  RpcClientProvider.provider().getRpcClient().start();
}
项目:spring    文件:DefaultLifecycleProcessor.java   
/**
 * Retrieve all applicable Lifecycle beans: all singletons that have already been created,
 * as well as all SmartLifecycle beans (even if they are marked as lazy-init).
 * @return the Map of applicable beans, with bean names as keys and bean instances as values
 */
protected Map<String, Lifecycle> getLifecycleBeans() {
    Map<String, Lifecycle> beans = new LinkedHashMap<String, Lifecycle>();
    String[] beanNames = this.beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
    for (String beanName : beanNames) {
        String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName);
        boolean isFactoryBean = this.beanFactory.isFactoryBean(beanNameToRegister);
        String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
        if ((this.beanFactory.containsSingleton(beanNameToRegister) &&
                (!isFactoryBean || Lifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck)))) ||
                SmartLifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck))) {
            Lifecycle bean = this.beanFactory.getBean(beanNameToCheck, Lifecycle.class);
            if (bean != this) {
                beans.put(beanNameToRegister, bean);
            }
        }
    }
    return beans;
}
项目:spring    文件:BeanFactoryAnnotationUtils.java   
/**
 * 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!");
    }
}
项目:spring    文件:StaticListableBeanFactory.java   
@Override
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
    String beanName = BeanFactoryUtils.transformedBeanName(name);

    Object bean = this.beans.get(beanName);
    if (bean == null) {
        throw new NoSuchBeanDefinitionException(beanName,
                "Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
    }

    if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
        // If it's a FactoryBean, we want to look at what it creates, not the factory class.
        return ((FactoryBean<?>) bean).getObjectType();
    }
    return bean.getClass();
}
项目:spring    文件:DefaultListableBeanFactory.java   
/**
 * Determine whether the specified bean definition qualifies as an autowire candidate,
 * to be injected into other beans which declare a dependency of matching type.
 * @param beanName the name of the bean definition to check
 * @param descriptor the descriptor of the dependency to resolve
 * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm
 * @return whether the bean should be considered as autowire candidate
 */
protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver)
        throws NoSuchBeanDefinitionException {

    String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName);
    if (containsBeanDefinition(beanDefinitionName)) {
        return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver);
    }
    else if (containsSingleton(beanName)) {
        return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver);
    }
    else if (getParentBeanFactory() instanceof DefaultListableBeanFactory) {
        // No bean definition found in this factory -> delegate to parent.
        return ((DefaultListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName, descriptor, resolver);
    }
    else if (getParentBeanFactory() instanceof ConfigurableListableBeanFactory) {
        // If no DefaultListableBeanFactory, can't pass the resolver along.
        return ((ConfigurableListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName, descriptor);
    }
    else {
        return true;
    }
}
项目:spring    文件:DefaultListableBeanFactory.java   
/**
 * Determine whether the specified bean definition qualifies as an autowire candidate,
 * to be injected into other beans which declare a dependency of matching type.
 * @param beanName the name of the bean definition to check
 * @param mbd the merged bean definition to check
 * @param descriptor the descriptor of the dependency to resolve
 * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm
 * @return whether the bean should be considered as autowire candidate
 */
protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd,
        DependencyDescriptor descriptor, AutowireCandidateResolver resolver) {

    String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName);
    resolveBeanClass(mbd, beanDefinitionName);
    if (mbd.isFactoryMethodUnique) {
        boolean resolve;
        synchronized (mbd.constructorArgumentLock) {
            resolve = (mbd.resolvedConstructorOrFactoryMethod == null);
        }
        if (resolve) {
            new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd);
        }
    }
    return resolver.isAutowireCandidate(
            new BeanDefinitionHolder(mbd, beanName, getAliases(beanDefinitionName)), descriptor);
}
项目:spring    文件:AspectJExpressionPointcut.java   
private FuzzyBoolean contextMatch(Class<?> targetType) {
    String advisedBeanName = getCurrentProxiedBeanName();
    if (advisedBeanName == null) {  // no proxy creation in progress
        // abstain; can't return YES, since that will make pointcut with negation fail
        return FuzzyBoolean.MAYBE;
    }
    if (BeanFactoryUtils.isGeneratedBeanName(advisedBeanName)) {
        return FuzzyBoolean.NO;
    }
    if (targetType != null) {
        boolean isFactory = FactoryBean.class.isAssignableFrom(targetType);
        return FuzzyBoolean.fromBoolean(
                matchesBeanName(isFactory ? BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName : advisedBeanName));
    }
    else {
        return FuzzyBoolean.fromBoolean(matchesBeanName(advisedBeanName) ||
                matchesBeanName(BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName));
    }
}
项目:incubator-zeppelin-druid    文件:LensJLineShellComponent.java   
@SuppressWarnings("rawtypes")
public void afterPropertiesSet() {

  Map<String, CommandMarker> commands = 
    BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext,
      CommandMarker.class);
  for (CommandMarker command : commands.values()) {
    getSimpleParser().add(command);
  }

  Map<String, Converter> converters = BeanFactoryUtils
    .beansOfTypeIncludingAncestors(applicationContext, Converter.class);
  for (Converter<?> converter : converters.values()) {
    getSimpleParser().add(converter);
  }

  setHistorySize(commandLine.getHistorySize());
  if (commandLine.getShellCommandsToExecute() != null) {
    setPrintBanner(false);
  }
}
项目:spring-boot-concourse    文件:EndpointWebMvcChildContextConfiguration.java   
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
    if (this.managementServerProperties == null) {
        this.managementServerProperties = BeanFactoryUtils
                .beanOfTypeIncludingAncestors(this.beanFactory,
                        ManagementServerProperties.class);
        this.server = BeanFactoryUtils.beanOfTypeIncludingAncestors(
                this.beanFactory, ServerProperties.class);
    }
    // Customize as per the parent context first (so e.g. the access logs go to
    // the same place)
    this.server.customize(container);
    // Then reset the error pages
    container.setErrorPages(Collections.<ErrorPage>emptySet());
    // and the context path
    container.setContextPath("");
    // and add the management-specific bits
    container.setPort(this.managementServerProperties.getPort());
    container.setServerHeader(this.server.getServerHeader());
    container.setAddress(this.managementServerProperties.getAddress());
    container.addErrorPages(new ErrorPage(this.server.getError().getPath()));
}
项目:spring-boot-concourse    文件:MvcEndpoints.java   
@Override
public void afterPropertiesSet() throws Exception {
    Collection<MvcEndpoint> existing = BeanFactoryUtils
            .beansOfTypeIncludingAncestors(this.applicationContext, MvcEndpoint.class)
            .values();
    this.endpoints.addAll(existing);
    this.customTypes = findEndpointClasses(existing);
    @SuppressWarnings("rawtypes")
    Collection<Endpoint> delegates = BeanFactoryUtils
            .beansOfTypeIncludingAncestors(this.applicationContext, Endpoint.class)
            .values();
    for (Endpoint<?> endpoint : delegates) {
        if (isGenericEndpoint(endpoint.getClass()) && endpoint.isEnabled()) {
            EndpointMvcAdapter adapter = new EndpointMvcAdapter(endpoint);
            String path = determinePath(endpoint,
                    this.applicationContext.getEnvironment());
            if (path != null) {
                adapter.setPath(path);
            }
            this.endpoints.add(adapter);
        }
    }
}
项目:spring-security-oauth2-boot    文件:OAuth2MethodSecurityConfiguration.java   
private <T> T findInContext(Class<T> type) {
    if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
            this.applicationContext, type).length == 1) {
        return this.applicationContext.getBean(type);
    }
    return null;
}
项目:configx    文件:ConfigBeanConversionService.java   
/**
 * 注册通过{@link ConfigBeanConverterConfigurer}配置的Converters
 *
 * @param beanFactory
 */
private void configurerConverters(ConfigurableListableBeanFactory beanFactory) {
    // Find all CustomConverterConfigurer in the ApplicationContext, including ancestor contexts.
    Map<String, ConfigBeanConverterConfigurer> matchingBeans =
            BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, ConfigBeanConverterConfigurer.class, true, false);
    if (!matchingBeans.isEmpty()) {
        for (ConfigBeanConverterConfigurer converterConfigurer : matchingBeans.values()) {
            if (converterConfigurer.getConverters() != null) {
                for (ConfigBeanConverter converter : converterConfigurer.getConverters()) {
                    converters.add(converter);
                }
            }
        }
    }
}
项目:spring-web-jsflow    文件:FlowStateSerializer.java   
private void createStubInfo() {
    final String[] names = BeanFactoryUtils.beanNamesIncludingAncestors(applicationContext);
    final Map<Object, Object> beansToStubs = new IdentityHashMap<>();
    for (final String name: names) {
        beansToStubs.put(applicationContext.getBean(name), new ApplicationContextBeanStub(name));
    }
    beansToStubs.put(".", applicationContext);
    this.beansToStubs = beansToStubs;
}