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

The following examples show how to use org.springframework.beans.factory.BeanFactoryUtils. 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
Source Project: jade-plugin-sql   Source File: PlumSQLInterpreter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    if (operationMapperManager == null) {
        operationMapperManager = new OperationMapperManager();
        operationMapperManager.setEntityMapperManager(new EntityMapperManager());
    }
    if (dialect == null) {
        // 将来可能扩展点:不同的DAO可以有不同的Dialect哦,而且是自动知道,不需要外部设置。
        dialect = new MySQLDialect();
    }
    // 
    if (logger.isInfoEnabled()) {
        String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(//
            applicationContext, GenericDAO.class);
        logger.info("[jade-plugin-sql] found " + beanNames.length + " GenericDAOs: "
                    + Arrays.toString(beanNames));
    }

}
 
Example 2
@Override
protected void initServletContext(ServletContext servletContext) {
	Collection<ViewResolver> matchingBeans =
			BeanFactoryUtils.beansOfTypeIncludingAncestors(obtainApplicationContext(), ViewResolver.class).values();
	if (this.viewResolvers == null) {
		this.viewResolvers = new ArrayList<>(matchingBeans.size());
		for (ViewResolver viewResolver : matchingBeans) {
			if (this != viewResolver) {
				this.viewResolvers.add(viewResolver);
			}
		}
	}
	else {
		for (int i = 0; i < this.viewResolvers.size(); i++) {
			ViewResolver vr = this.viewResolvers.get(i);
			if (matchingBeans.contains(vr)) {
				continue;
			}
			String name = vr.getClass().getName() + i;
			obtainApplicationContext().getAutowireCapableBeanFactory().initializeBean(vr, name);
		}

	}
	AnnotationAwareOrderComparator.sort(this.viewResolvers);
	this.cnmFactoryBean.setServletContext(servletContext);
}
 
Example 3
/**
 * 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;
}
 
Example 4
@Override
   public boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
		throws NoSuchBeanDefinitionException {

	// Consider FactoryBeans as autowiring candidates.
	boolean isFactoryBean = (descriptor != null && descriptor.getDependencyType() != null &&
			FactoryBean.class.isAssignableFrom(descriptor.getDependencyType()));
	if (isFactoryBean) {
		beanName = BeanFactoryUtils.transformedBeanName(beanName);
	}

	if (containsBeanDefinition(beanName)) {
		return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanName), descriptor);
	}
	else if (containsSingleton(beanName)) {
		return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor);
	}
	else if (getParentBeanFactory() instanceof ConfigurableListableBeanFactory) {
		// No bean definition found in this factory -> delegate to parent.
		return ((ConfigurableListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName, descriptor);
	}
	else {
		return true;
	}
}
 
Example 5
/**
 * 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);
}
 
Example 6
public String formatRevisionDisplay(final Revision revision) {
    final String defaultFormattedRevision = revision.getAuthor() + " @ " + revision.getDate() + " (" + revision.getRevision() + ")";
    final ServletContext servletContext = pageContext.getServletContext();
    final WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    try {
        final Map<String, DefinitionRevisionDisplayFormatter> formatterBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,DefinitionRevisionDisplayFormatter.class);

        if (formatterBeans.isEmpty()) {
            //No bean found, which is acceptable.
            return StringEscapeUtils.escapeHtml4(defaultFormattedRevision);
        } else if (formatterBeans.size() == 1) {
            final DefinitionRevisionDisplayFormatter formatter = formatterBeans.values().iterator().next();
            return formatter.formatRevision(revision);
        } else {
            throw new IllegalArgumentException("Multiple beans of type " + DefinitionRevisionDisplayFormatter.class.getSimpleName()  + " found, expected 0 or 1.");
        }
    } catch (final Exception e) {
        LOGGER.error("An error occurred when retrieving revision url.", e);
        return defaultFormattedRevision;
    }
}
 
Example 7
private String renderTemplates() {
    final StringBuilder renderedHTML = new StringBuilder();
    final ServletContext servletContext = pageContext.getServletContext();
    final WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    try {
        final Map<String, EditPageRenderer> rendererBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, EditPageRenderer.class);
        for (final EditPageRenderer renderer : rendererBeans.values()) {
            if (position == renderer.getEditPagePosition()) {
                renderedHTML.append(renderer.getRenderedHtml(testName, testDefinitionJson, isCreate));
                renderedHTML.append(renderer.getRenderedHtml(pageContext, testName, testDefinitionJson, isCreate));
            }
        }
    } catch (Exception e) {
        LOGGER.error("An error occurred when attempting to inject template.", e);
    }
    return renderedHTML.toString();
}
 
Example 8
Source Project: astrix   Source File: GsBinder.java    License: Apache License 2.0 6 votes vote down vote up
private GigaSpace findEmbeddedSpace(ApplicationContext applicationContext) {
	GigaSpace result = null;
	for (GigaSpace gigaSpace : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, GigaSpace.class).values()) {
		if (isEmbedded(gigaSpace)) {
			if (result != null) {
				throw new IllegalStateException("Multiple embedded spaces defined in applicationContext");
			} else {
				result = gigaSpace;
			}
		}
	}
	if (result == null) {
		throw new IllegalStateException("Failed to find an embedded space in applicationContext");
	}
	return result;
}
 
Example 9
Source Project: spring-analysis-note   Source File: DefaultListableBeanFactory.java    License: MIT License 6 votes vote down vote up
/**
 * 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);
	}

	BeanFactory parent = getParentBeanFactory();
	if (parent instanceof DefaultListableBeanFactory) {
		// No bean definition found in this factory -> delegate to parent.
		return ((DefaultListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor, resolver);
	}
	else if (parent instanceof ConfigurableListableBeanFactory) {
		// If no DefaultListableBeanFactory, can't pass the resolver along.
		return ((ConfigurableListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor);
	}
	else {
		return true;
	}
}
 
Example 10
Source Project: java-technology-stack   Source File: DefaultLifecycleProcessor.java    License: MIT License 6 votes vote down vote up
/**
 * 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() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	Map<String, Lifecycle> beans = new LinkedHashMap<>();
	String[] beanNames = beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
	for (String beanName : beanNames) {
		String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName);
		boolean isFactoryBean = beanFactory.isFactoryBean(beanNameToRegister);
		String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
		if ((beanFactory.containsSingleton(beanNameToRegister) &&
				(!isFactoryBean || matchesBeanType(Lifecycle.class, beanNameToCheck, beanFactory))) ||
				matchesBeanType(SmartLifecycle.class, beanNameToCheck, beanFactory)) {
			Object bean = beanFactory.getBean(beanNameToCheck);
			if (bean != this && bean instanceof Lifecycle) {
				beans.put(beanNameToRegister, (Lifecycle) bean);
			}
		}
	}
	return beans;
}
 
Example 11
/**
 * 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");
			}
		}
	}
}
 
Example 12
Source Project: java-technology-stack   Source File: DispatcherHandler.java    License: MIT License 6 votes vote down vote up
protected void initStrategies(ApplicationContext context) {
	Map<String, HandlerMapping> mappingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
			context, HandlerMapping.class, true, false);

	ArrayList<HandlerMapping> mappings = new ArrayList<>(mappingBeans.values());
	AnnotationAwareOrderComparator.sort(mappings);
	this.handlerMappings = Collections.unmodifiableList(mappings);

	Map<String, HandlerAdapter> adapterBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
			context, HandlerAdapter.class, true, false);

	this.handlerAdapters = new ArrayList<>(adapterBeans.values());
	AnnotationAwareOrderComparator.sort(this.handlerAdapters);

	Map<String, HandlerResultHandler> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
			context, HandlerResultHandler.class, true, false);

	this.resultHandlers = new ArrayList<>(beans.values());
	AnnotationAwareOrderComparator.sort(this.resultHandlers);
}
 
Example 13
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 14
Source Project: blog_demos   Source File: StaticListableBeanFactory.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 15
/**
 * 建立当前 ApplicationContext 中的所有 Controller 和 url 的对应关系
 */
protected void detectHandlers() throws BeansException {
	ApplicationContext applicationContext = obtainApplicationContext();
	// 获取 ApplicationContext 容器中所有 bean 的 Name
	String[] beanNames = (this.detectHandlersInAncestorContexts ?
			BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, Object.class) :
			applicationContext.getBeanNamesForType(Object.class));

	// 遍历 beanNames,并找到这些 bean 对应的 url
	for (String beanName : beanNames) {
		// 找 bean 上的所有 url(Controller 上的 url+方法上的 url),该方法由对应的子类实现
		String[] urls = determineUrlsForHandler(beanName);
		if (!ObjectUtils.isEmpty(urls)) {
			// // 保存 urls 和 beanName 的对应关系,put it to Map<urls,beanName>
			// 该方法在父类 AbstractUrlHandlerMapping中实现
			registerHandler(urls, beanName);
		}
	}

	if ((logger.isDebugEnabled() && !getHandlerMap().isEmpty()) || logger.isTraceEnabled()) {
		logger.debug("Detected " + getHandlerMap().size() + " mappings in " + formatMappingName());
	}
}
 
Example 16
private String renderTemplates() {
    final StringBuilder renderedHTML = new StringBuilder();
    final ServletContext servletContext = pageContext.getServletContext();
    final WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    try {
        final Map<String, DefinitionDeletePageRenderer> rendererBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, DefinitionDeletePageRenderer.class);
        for (final DefinitionDeletePageRenderer renderer : rendererBeans.values()) {
            if (position == renderer.getDefinitionDeletePagePosition()) {
                renderedHTML.append(renderer.getRenderedHtml(testName));
                renderedHTML.append(renderer.getRenderedHtml(pageContext, testName));
            }
        }
    } catch (final Exception e) {
        LOGGER.error("An error occurred when attempting to inject template.", e);
    }
    return renderedHTML.toString();
}
 
Example 17
Source Project: java-technology-stack   Source File: WebMvcConfigurationSupport.java    License: MIT License 6 votes vote down vote up
/**
 * 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(
			mvcContentNegotiationManager(), this.applicationContext);
	configureViewResolvers(registry);

	if (registry.getViewResolvers().isEmpty() && this.applicationContext != null) {
		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());
	if (this.applicationContext != null) {
		composite.setApplicationContext(this.applicationContext);
	}
	if (this.servletContext != null) {
		composite.setServletContext(this.servletContext);
	}
	return composite;
}
 
Example 18
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 19
/**
 * Detect all PersistenceExceptionTranslators in the given BeanFactory.
 *
 * @return a chained PersistenceExceptionTranslator, combining all
 * PersistenceExceptionTranslators found in the factory
 * @see ChainedPersistenceExceptionTranslator
 */
private PersistenceExceptionTranslator detectPersistenceExceptionTranslators() {
	// Find all translators, being careful not to activate FactoryBeans.
	Map<String, PersistenceExceptionTranslator> pets = BeanFactoryUtils.beansOfTypeIncludingAncestors(
		beanFactory, PersistenceExceptionTranslator.class, false, false);
	ChainedPersistenceExceptionTranslator cpet = new ChainedPersistenceExceptionTranslator();
	pets.values().forEach(cpet::addDelegate);
	return cpet;
}
 
Example 20
Source Project: lams   Source File: ControllerAdviceBean.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find the names of beans annotated with
 * {@linkplain ControllerAdvice @ControllerAdvice} in the given
 * ApplicationContext and wrap them as {@code ControllerAdviceBean} instances.
 */
public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext applicationContext) {
	List<ControllerAdviceBean> beans = new ArrayList<ControllerAdviceBean>();
	for (String name : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, Object.class)) {
		if (applicationContext.findAnnotationOnBean(name, ControllerAdvice.class) != null) {
			beans.add(new ControllerAdviceBean(name, applicationContext));
		}
	}
	return beans;
}
 
Example 21
Source Project: nextreports-server   Source File: DefaultSectionManager.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
	sections = new LinkedHashMap<String, Section>();
	
	Map<String, Section> matches = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, Section.class);
	for (Section section: matches.values()) {
		if (AnalysisSection.ID.equals(section.getId())) {
			if(moduleLicence.isValid(NextServerModuleLicence.ANALYSIS_MODULE)) {				
				sections.put(section.getId(), section);
			}
		} else if (AuditSection.ID.equals(section.getId())) {
			if(moduleLicence.isValid(NextServerModuleLicence.AUDIT_MODULE)) {				
				sections.put(section.getId(), section);
			}	
		} else {
			sections.put(section.getId(), section);
		}			
	}
	
	sections = Collections.unmodifiableMap(sections);
			
	sectionsCache = new ArrayList<Section>(sections.values());
	sectionsCache = Collections.unmodifiableList(sectionsCache);
	
	idsCache = new ArrayList<String>(sections.keySet());
	idsCache = Collections.unmodifiableList(idsCache);		
}
 
Example 22
private void assertOneMessageSourceOnly(ClassPathXmlApplicationContext ctx, Object myMessageSource) {
	String[] beanNamesForType = ctx.getBeanNamesForType(StaticMessageSource.class);
	assertEquals(1, beanNamesForType.length);
	assertEquals("myMessageSource", beanNamesForType[0]);
	beanNamesForType = ctx.getBeanNamesForType(StaticMessageSource.class, true, true);
	assertEquals(1, beanNamesForType.length);
	assertEquals("myMessageSource", beanNamesForType[0]);
	beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, StaticMessageSource.class);
	assertEquals(1, beanNamesForType.length);
	assertEquals("myMessageSource", beanNamesForType[0]);
	beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, StaticMessageSource.class, true, true);
	assertEquals(1, beanNamesForType.length);
	assertEquals("myMessageSource", beanNamesForType[0]);

	Map<?, StaticMessageSource> beansOfType = ctx.getBeansOfType(StaticMessageSource.class);
	assertEquals(1, beansOfType.size());
	assertSame(myMessageSource, beansOfType.values().iterator().next());
	beansOfType = ctx.getBeansOfType(StaticMessageSource.class, true, true);
	assertEquals(1, beansOfType.size());
	assertSame(myMessageSource, beansOfType.values().iterator().next());
	beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, StaticMessageSource.class);
	assertEquals(1, beansOfType.size());
	assertSame(myMessageSource, beansOfType.values().iterator().next());
	beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, StaticMessageSource.class, true, true);
	assertEquals(1, beansOfType.size());
	assertSame(myMessageSource, beansOfType.values().iterator().next());
}
 
Example 23
Source Project: spring-analysis-note   Source File: ScriptTemplateView.java    License: MIT License 5 votes vote down vote up
protected ScriptTemplateConfig autodetectViewConfig() throws BeansException {
	try {
		return BeanFactoryUtils.beanOfTypeIncludingAncestors(
				obtainApplicationContext(), ScriptTemplateConfig.class, true, false);
	}
	catch (NoSuchBeanDefinitionException ex) {
		throw new ApplicationContextException("Expected a single ScriptTemplateConfig bean in the current " +
				"web application context or the parent root context: ScriptTemplateConfigurer is " +
				"the usual implementation. This bean may have any name.", ex);
	}
}
 
Example 24
/**
 * Checks the given bean name whether it is unique. If not already unique,
 * a counter is added, increasing the counter until the name is unique.
 * @param innerBeanName the original name for the inner bean
 * @return the adapted name for the inner bean
 */
private String adaptInnerBeanName(String innerBeanName) {
	String actualInnerBeanName = innerBeanName;
	int counter = 0;
	while (this.beanFactory.isBeanNameInUse(actualInnerBeanName)) {
		counter++;
		actualInnerBeanName = innerBeanName + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR + counter;
	}
	return actualInnerBeanName;
}
 
Example 25
Source Project: spring4-understanding   Source File: DispatcherServlet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the HandlerAdapters used by this class.
 * <p>If no HandlerAdapter beans are defined in the BeanFactory for this namespace,
 * we default to SimpleControllerHandlerAdapter.
 */
private void initHandlerAdapters(ApplicationContext context) {
	this.handlerAdapters = null;

	if (this.detectAllHandlerAdapters) {
		// Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
		Map<String, HandlerAdapter> matchingBeans =
				BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
		if (!matchingBeans.isEmpty()) {
			this.handlerAdapters = new ArrayList<HandlerAdapter>(matchingBeans.values());
			// We keep HandlerAdapters in sorted order.
			AnnotationAwareOrderComparator.sort(this.handlerAdapters);
		}
	}
	else {
		try {
			HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
			this.handlerAdapters = Collections.singletonList(ha);
		}
		catch (NoSuchBeanDefinitionException ex) {
			// Ignore, we'll add a default HandlerAdapter later.
		}
	}

	// Ensure we have at least some HandlerAdapters, by registering
	// default HandlerAdapters if no other adapters are found.
	if (this.handlerAdapters == null) {
		this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
		if (logger.isDebugEnabled()) {
			logger.debug("No HandlerAdapters found in servlet '" + getServletName() + "': using default");
		}
	}
}
 
Example 26
Source Project: spring4-understanding   Source File: DispatcherPortlet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the ViewResolvers used by this class.
 * <p>If no ViewResolver beans are defined in the BeanFactory
 * for this namespace, we default to InternalResourceViewResolver.
 */
private void initViewResolvers(ApplicationContext context) {
	this.viewResolvers = null;

	if (this.detectAllViewResolvers) {
		// Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
		Map<String, ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
				context, ViewResolver.class, true, false);
		if (!matchingBeans.isEmpty()) {
			this.viewResolvers = new ArrayList<ViewResolver>(matchingBeans.values());
			// We keep ViewResolvers in sorted order.
			AnnotationAwareOrderComparator.sort(this.viewResolvers);
		}
	}
	else {
		try {
			ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
			this.viewResolvers = Collections.singletonList(vr);
		}
		catch (NoSuchBeanDefinitionException ex) {
			// Ignore, we'll add a default ViewResolver later.
		}
	}

	// Ensure we have at least one ViewResolver, by registering
	// a default ViewResolver if no other resolvers are found.
	if (this.viewResolvers == null) {
		this.viewResolvers = getDefaultStrategies(context, ViewResolver.class);
		if (logger.isDebugEnabled()) {
			logger.debug("No ViewResolvers found in portlet '" + getPortletName() + "': using default");
		}
	}
}
 
Example 27
Source Project: foremast   Source File: HandlerMappingIntrospector.java    License: Apache License 2.0 5 votes vote down vote up
private static List<HandlerMapping> initHandlerMappings(ApplicationContext applicationContext) {
    Map<String, HandlerMapping> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
            applicationContext, HandlerMapping.class, true, false);
    if (!beans.isEmpty()) {
        List<HandlerMapping> mappings = new ArrayList<>(beans.values());
        AnnotationAwareOrderComparator.sort(mappings);
        return Collections.unmodifiableList(mappings);
    }
    return Collections.unmodifiableList(initFallback(applicationContext));
}
 
Example 28
Source Project: spring-analysis-note   Source File: DispatcherServlet.java    License: MIT License 5 votes vote down vote up
/**
 * Initialize the HandlerMappings used by this class.
 * <p>If no HandlerMapping beans are defined in the BeanFactory for this namespace,
 * we default to BeanNameUrlHandlerMapping.
 */
private void initHandlerMappings(ApplicationContext context) {
	this.handlerMappings = null;

	if (this.detectAllHandlerMappings) {
		// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
		// 默认情况下,寻找应用中所有的 HandlerMapping ,包括祖先容器(其实就是 Spring 容器啦)
		Map<String, HandlerMapping> matchingBeans =
				BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
		if (!matchingBeans.isEmpty()) {
			this.handlerMappings = new ArrayList<>(matchingBeans.values());
			// We keep HandlerMappings in sorted order.
			// handlerMapping 有优先级,需要排序
			AnnotationAwareOrderComparator.sort(this.handlerMappings);
		}
	}
	else {
		try {
			// 从上下文中,获取名称为 handlerMapping 的 bean
			HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
			this.handlerMappings = Collections.singletonList(hm);
		}
		catch (NoSuchBeanDefinitionException ex) {
			// Ignore, we'll add a default HandlerMapping later.
		}
	}

	// Ensure we have at least one HandlerMapping, by registering
	// a default HandlerMapping if no other mappings are found.
	// 需要保证,至少有一个 HandlerMapping
	// 如果前面两步都没找到 mapping,将会由这里加载默认策略
	if (this.handlerMappings == null) {
		this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
		if (logger.isTraceEnabled()) {
			logger.trace("No HandlerMappings declared for servlet '" + getServletName() +
					"': using default strategies from DispatcherServlet.properties");
		}
	}
}
 
Example 29
/**
 * Checks the given bean name whether it is unique. If not already unique,
 * a counter is added, increasing the counter until the name is unique.
 * @param innerBeanName the original name for the inner bean
 * @return the adapted name for the inner bean
 */
private String adaptInnerBeanName(String innerBeanName) {
	String actualInnerBeanName = innerBeanName;
	int counter = 0;
	while (this.beanFactory.isBeanNameInUse(actualInnerBeanName)) {
		counter++;
		actualInnerBeanName = innerBeanName + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR + counter;
	}
	return actualInnerBeanName;
}
 
Example 30
Source Project: spring-analysis-note   Source File: DispatcherServlet.java    License: MIT License 5 votes vote down vote up
/**
 * Initialize the ViewResolvers used by this class.
 * <p>If no ViewResolver beans are defined in the BeanFactory for this
 * namespace, we default to InternalResourceViewResolver.
 */
private void initViewResolvers(ApplicationContext context) {
	this.viewResolvers = null;

	if (this.detectAllViewResolvers) {
		// Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
		Map<String, ViewResolver> matchingBeans =
				BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver.class, true, false);
		if (!matchingBeans.isEmpty()) {
			this.viewResolvers = new ArrayList<>(matchingBeans.values());
			// We keep ViewResolvers in sorted order.
			AnnotationAwareOrderComparator.sort(this.viewResolvers);
		}
	}
	else {
		try {
			ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
			this.viewResolvers = Collections.singletonList(vr);
		}
		catch (NoSuchBeanDefinitionException ex) {
			// Ignore, we'll add a default ViewResolver later.
		}
	}

	// Ensure we have at least one ViewResolver, by registering
	// a default ViewResolver if no other resolvers are found.
	if (this.viewResolvers == null) {
		this.viewResolvers = getDefaultStrategies(context, ViewResolver.class);
		if (logger.isTraceEnabled()) {
			logger.trace("No ViewResolvers declared for servlet '" + getServletName() +
					"': using default strategies from DispatcherServlet.properties");
		}
	}
}