Java Code Examples for org.springframework.beans.factory.BeanFactoryUtils#beansOfTypeIncludingAncestors()
The following examples show how to use
org.springframework.beans.factory.BeanFactoryUtils#beansOfTypeIncludingAncestors() .
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: DispatcherHandler.java From spring-analysis-note with MIT License | 6 votes |
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 2
Source File: BeanFactoryAnnotationUtils.java From blog_demos with Apache License 2.0 | 6 votes |
/** * 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 { throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() + " bean found for qualifier '" + qualifier + "' - neither qualifier " + "match nor bean name match!"); } }
Example 3
Source File: RouterFunctionMapping.java From spring-analysis-note with MIT License | 6 votes |
/** * Detect a all {@linkplain RouterFunction router functions} in the * current application context. */ @SuppressWarnings({"unchecked", "rawtypes"}) private void initRouterFunction() { ApplicationContext applicationContext = obtainApplicationContext(); Map<String, RouterFunction> beans = (this.detectHandlerFunctionsInAncestorContexts ? BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RouterFunction.class) : applicationContext.getBeansOfType(RouterFunction.class)); List<RouterFunction> routerFunctions = new ArrayList<>(beans.values()); if (!CollectionUtils.isEmpty(routerFunctions) && logger.isInfoEnabled()) { routerFunctions.forEach(routerFunction -> logger.info("Mapped " + routerFunction)); } this.routerFunction = routerFunctions.stream() .reduce(RouterFunction::andOther) .orElse(null); }
Example 4
Source File: RenderDefinitionHistoryPageInjectionTemplatesHandler.java From proctor with Apache License 2.0 | 6 votes |
private String renderTemplates() { final StringBuilder renderedHTML = new StringBuilder(); final ServletContext servletContext = pageContext.getServletContext(); final WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); try { final Map<String, DefinitionHistoryPageRenderer> rendererBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, DefinitionHistoryPageRenderer.class); for (final DefinitionHistoryPageRenderer renderer : rendererBeans.values()) { if (position == renderer.getDefinitionHistoryPagePositionPosition()) { renderedHTML.append(renderer.getRenderedHtml(testName, testDefinitionVersion)); renderedHTML.append(renderer.getRenderedHtml(pageContext, testName, testDefinitionVersion)); } } } catch (Exception e) { LOGGER.error("An error occurred when attempting to inject template.", e); } return renderedHTML.toString(); }
Example 5
Source File: RocketMQPushConsumerStarter.java From onetwo with Apache License 2.0 | 6 votes |
@SuppressWarnings("rawtypes") @Override public void afterPropertiesSet() throws Exception { logger.info("mq consumer init. namesrvAddr: {}", namesrvAddr); // Assert.hasText(namesrvAddr, "namesrvAddr can not be empty!"); Map<String, AppMQConsumer> consumerBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, AppMQConsumer.class); List<AppMQConsumer> consumerBeanList = Lists.newArrayList(consumerBeans.values()); ConsumerScanner scanner = new ConsumerScanner(applicationContext); consumerBeanList.addAll(scanner.findConsumers()); Map<ConsumerMeta, List<AppMQConsumer>> consumerGroups = consumerBeanList.stream() .collect(Collectors.groupingBy(c->c.getConsumerMeta())); consumerGroups.entrySet().forEach(e->{ try { this.initializeConsumers(e.getKey(), e.getValue()); } catch (MQClientException | InterruptedException ex) { logger.error("mq consumer initialize error: " + ex.getMessage(), ex); } }); }
Example 6
Source File: RenderHelpButtonTagHandler.java From proctor with Apache License 2.0 | 6 votes |
public String getHelpURL(final HelpType helpType) { final ServletContext servletContext = pageContext.getServletContext(); final WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); final Map<String, HelpURLInformation> formatterBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HelpURLInformation.class); if (formatterBeans.size() == 1) { HelpURLInformation helpURLInformation = (HelpURLInformation) formatterBeans.values().toArray()[0]; switch (helpType) { case TEST_TYPE: return helpURLInformation.getTestTypeHelpURL(); case RULE: return helpURLInformation.getRuleHelpURL(); case AUTO_PROMOTION: return helpURLInformation.getAutoPromotionHelpURL(); default: return ""; } } else if (formatterBeans.size() > 1) { LOGGER.warn("Multiple beans of type " + HelpURLInformation.class.getSimpleName() + " found, expected 0 or 1."); } return getDefaultHelpURL(helpType); }
Example 7
Source File: RenderDefinitionDetailsPageInjectionTemplatesHandler.java From proctor with Apache License 2.0 | 6 votes |
private String renderTemplates() { final StringBuilder renderedHTML = new StringBuilder(); final ServletContext servletContext = pageContext.getServletContext(); final WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); try { final Map<String, DefinitionDetailsPageRenderer> rendererBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, DefinitionDetailsPageRenderer.class); for (final DefinitionDetailsPageRenderer renderer : rendererBeans.values()) { if (position == renderer.getDefinitionDetailsPagePosition()) { renderedHTML.append(renderer.getRenderedHtml(testName, testDefinition)); renderedHTML.append(renderer.getRenderedHtml(pageContext, testName, testDefinition)); } } } catch (Exception e) { LOGGER.error("An error occurred when attempting to inject template.", e); } return renderedHTML.toString(); }
Example 8
Source File: RenderMatrixListPageInjectionTemplatesHandler.java From proctor with Apache License 2.0 | 6 votes |
private String renderTemplates() { final StringBuilder renderedHTML = new StringBuilder(); final ServletContext servletContext = pageContext.getServletContext(); final WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); try { final Map<String, MatrixListPageRenderer> rendererBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, MatrixListPageRenderer.class); for (final MatrixListPageRenderer renderer : rendererBeans.values()) { if (position == renderer.getMatrixListPagePosition()) { renderedHTML.append(renderer.getRenderedHtml(testName, testMatrixVersion, testDefinition)); renderedHTML.append(renderer.getRenderedHtml(pageContext, testName, testMatrixVersion, testDefinition)); } } } catch (Exception e) { LOGGER.error("An error occurred when attempting to inject template.", e); } return renderedHTML.toString(); }
Example 9
Source File: PersistenceExceptionTranslationInterceptor.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Detect all PersistenceExceptionTranslators in the given BeanFactory. * @param beanFactory the ListableBeanFactory to obtaining all * PersistenceExceptionTranslators from * @return a chained PersistenceExceptionTranslator, combining all * PersistenceExceptionTranslators found in the factory * @see ChainedPersistenceExceptionTranslator */ protected PersistenceExceptionTranslator detectPersistenceExceptionTranslators(ListableBeanFactory beanFactory) { // Find all translators, being careful not to activate FactoryBeans. Map<String, PersistenceExceptionTranslator> pets = BeanFactoryUtils.beansOfTypeIncludingAncestors( beanFactory, PersistenceExceptionTranslator.class, false, false); ChainedPersistenceExceptionTranslator cpet = new ChainedPersistenceExceptionTranslator(); for (PersistenceExceptionTranslator pet : pets.values()) { cpet.addDelegate(pet); } return cpet; }
Example 10
Source File: DefaultSectionManager.java From nextreports-server with Apache License 2.0 | 5 votes |
@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 11
Source File: DispatcherServlet.java From java-technology-stack with MIT License | 5 votes |
/** * 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<>(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.isTraceEnabled()) { logger.trace("No HandlerAdapters declared for servlet '" + getServletName() + "': using default strategies from DispatcherServlet.properties"); } } }
Example 12
Source File: DispatcherServlet.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Initialize the HandlerExceptionResolver used by this class. * <p>If no bean is defined with the given name in the BeanFactory for this namespace, * we default to no exception resolver. */ private void initHandlerExceptionResolvers(ApplicationContext context) { this.handlerExceptionResolvers = null; if (this.detectAllHandlerExceptionResolvers) { // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts. Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false); if (!matchingBeans.isEmpty()) { this.handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values()); // We keep HandlerExceptionResolvers in sorted order. AnnotationAwareOrderComparator.sort(this.handlerExceptionResolvers); } } else { try { HandlerExceptionResolver her = context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class); this.handlerExceptionResolvers = Collections.singletonList(her); } catch (NoSuchBeanDefinitionException ex) { // Ignore, no HandlerExceptionResolver is fine too. } } // Ensure we have at least some HandlerExceptionResolvers, by registering // default HandlerExceptionResolvers if no other resolvers are found. if (this.handlerExceptionResolvers == null) { this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class); if (logger.isDebugEnabled()) { logger.debug("No HandlerExceptionResolvers found in servlet '" + getServletName() + "': using default"); } } }
Example 13
Source File: PersistenceExceptionTranslationInterceptor.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Detect all PersistenceExceptionTranslators in the given BeanFactory. * @param beanFactory the ListableBeanFactory to obtaining all * PersistenceExceptionTranslators from * @return a chained PersistenceExceptionTranslator, combining all * PersistenceExceptionTranslators found in the factory * @see ChainedPersistenceExceptionTranslator */ protected PersistenceExceptionTranslator detectPersistenceExceptionTranslators(ListableBeanFactory beanFactory) { // Find all translators, being careful not to activate FactoryBeans. Map<String, PersistenceExceptionTranslator> pets = BeanFactoryUtils.beansOfTypeIncludingAncestors( beanFactory, PersistenceExceptionTranslator.class, false, false); ChainedPersistenceExceptionTranslator cpet = new ChainedPersistenceExceptionTranslator(); for (PersistenceExceptionTranslator pet : pets.values()) { cpet.addDelegate(pet); } return cpet; }
Example 14
Source File: ReactivePersistenceExceptionTranslationInterceptor.java From sdn-rx with Apache License 2.0 | 5 votes |
/** * 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 15
Source File: DispatcherServlet.java From spring-analysis-note with MIT License | 5 votes |
/** * 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"); } } }
Example 16
Source File: SpringUtils.java From onetwo with Apache License 2.0 | 5 votes |
public static <T> List<T> getBeans(ListableBeanFactory appContext, Class<T> clazz) { Map<String, T> beanMaps = BeanFactoryUtils.beansOfTypeIncludingAncestors(appContext, clazz); if(beanMaps==null || beanMaps.isEmpty()) return new ArrayList<>(); List<T> list = new ArrayList<T>(beanMaps.values()); AnnotationAwareOrderComparator.sort(list); return list; }
Example 17
Source File: JpaPersistenceProvider.java From rice with Educational Community License v2.0 | 5 votes |
/** * Gets any {@link PersistenceExceptionTranslator}s from the {@link BeanFactory}. * * @param beanFactory The {@link BeanFactory} to use. * * @return A {@link PersistenceExceptionTranslator} from the {@link BeanFactory}. */ protected PersistenceExceptionTranslator detectPersistenceExceptionTranslators(ListableBeanFactory beanFactory) { // Find all translators, being careful not to activate FactoryBeans. Map<String, PersistenceExceptionTranslator> pets = BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, PersistenceExceptionTranslator.class, false, false); ChainedPersistenceExceptionTranslator cpet = new ChainedPersistenceExceptionTranslator(); for (PersistenceExceptionTranslator pet : pets.values()) { cpet.addDelegate(pet); } // always add one last persistence exception translator as a catch all cpet.addDelegate(new DefaultPersistenceExceptionTranslator()); return cpet; }
Example 18
Source File: DispatcherServlet.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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 servlet '" + getServletName() + "': using default"); } } }
Example 19
Source File: ClassPathXmlApplicationContextTests.java From spring-analysis-note with MIT License | 5 votes |
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 20
Source File: Knife4jController.java From yshopmall with Apache License 2.0 | 4 votes |
/** @deprecated */ @Deprecated private void initGlobalRequestMappingArray(WebApplicationContext wc, SwaggerExt swaggerExt) { if (this.globalHandlerMappings.size() == 0) { String parentPath = ""; if (!StringUtils.isEmpty(swaggerExt.getBasePath()) && !"/".equals(swaggerExt.getBasePath())) { parentPath = parentPath + swaggerExt.getBasePath(); } Map<String, HandlerMapping> requestMappings = BeanFactoryUtils.beansOfTypeIncludingAncestors(wc, HandlerMapping.class, true, false); Iterator<HandlerMapping> var5 = requestMappings.values().iterator(); while(true) { HandlerMapping handlerMapping; do { if (!var5.hasNext()) { return; } handlerMapping = var5.next(); } while(!(handlerMapping instanceof RequestMappingHandlerMapping)); RequestMappingHandlerMapping rmhMapping = (RequestMappingHandlerMapping)handlerMapping; Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhMapping.getHandlerMethods(); for (RequestMappingInfo rmi : handlerMethods.keySet()) { PatternsRequestCondition prc = rmi.getPatternsCondition(); Set<RequestMethod> restMethods = rmi.getMethodsCondition().getMethods(); Set<String> patterns = prc.getPatterns(); HandlerMethod handlerMethod = (HandlerMethod) handlerMethods.get(rmi); String url; Class clazz; Method method; for (Iterator<String> var15 = patterns.iterator(); var15.hasNext(); this.globalHandlerMappings.add(new RestHandlerMapping(parentPath + url, clazz, method, restMethods))) { url = var15.next(); clazz = ClassUtils.getUserClass(handlerMethod.getBeanType()); method = ClassUtils.getMostSpecificMethod(handlerMethod.getMethod(), clazz); if (LOGGER.isDebugEnabled()) { LOGGER.debug("url:" + url + "\r\nclass:" + clazz.toString() + "\r\nmethod:" + method.toString()); } } } } } }