org.springframework.beans.factory.BeanFactoryUtils Java Examples
The following examples show how to use
org.springframework.beans.factory.BeanFactoryUtils.
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: EntityManagerFactoryUtils.java From java-technology-stack with MIT License | 6 votes |
/** * 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 #2
Source File: WebMvcConfigurationSupport.java From java-technology-stack with MIT License | 6 votes |
/** * 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 #3
Source File: AbstractDetectingUrlHandlerMapping.java From java-technology-stack with MIT License | 6 votes |
/** * 建立当前 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 #4
Source File: RenderDefinitionDeletePageInjectionTemplatesHandler.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, 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 #5
Source File: StaticListableBeanFactory.java From blog_demos with Apache License 2.0 | 6 votes |
@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 #6
Source File: BeanFactoryAnnotationUtils.java From java-technology-stack with MIT License | 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 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 #7
Source File: DefaultListableBeanFactory.java From kfs with GNU Affero General Public License v3.0 | 6 votes |
@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 #8
Source File: PlumSQLInterpreter.java From jade-plugin-sql with Apache License 2.0 | 6 votes |
@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 #9
Source File: ContentNegotiatingViewResolver.java From spring-analysis-note with MIT License | 6 votes |
@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 #10
Source File: DefaultLifecycleProcessor.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * 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 #11
Source File: DispatcherHandler.java From java-technology-stack 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 #12
Source File: DefaultListableBeanFactory.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * 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 #13
Source File: AbstractDetectingUrlHandlerMapping.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * 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 #14
Source File: DefaultLifecycleProcessor.java From java-technology-stack with MIT License | 6 votes |
/** * 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 #15
Source File: FormatDefinitionRevisionDisplayTagHandler.java From proctor with Apache License 2.0 | 6 votes |
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 #16
Source File: DefaultListableBeanFactory.java From spring-analysis-note with MIT License | 6 votes |
/** * 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 #17
Source File: GsBinder.java From astrix with Apache License 2.0 | 6 votes |
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 #18
Source File: RenderEditPageInjectionTemplatesTagHandler.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, 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 #19
Source File: HandlerMappingIntrospector.java From java-technology-stack with MIT License | 5 votes |
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 #20
Source File: GroovyMarkupView.java From java-technology-stack with MIT License | 5 votes |
/** * Autodetect a MarkupTemplateEngine via the ApplicationContext. * Called if a MarkupTemplateEngine has not been manually configured. */ protected MarkupTemplateEngine autodetectMarkupTemplateEngine() throws BeansException { try { return BeanFactoryUtils.beanOfTypeIncludingAncestors(obtainApplicationContext(), GroovyMarkupConfig.class, true, false).getTemplateEngine(); } catch (NoSuchBeanDefinitionException ex) { throw new ApplicationContextException("Expected a single GroovyMarkupConfig bean in the current " + "Servlet web application context or the parent root context: GroovyMarkupConfigurer is " + "the usual implementation. This bean may have any name.", ex); } }
Example #21
Source File: StaticListableBeanFactory.java From java-technology-stack with MIT License | 5 votes |
@Override public Object getBean(String name) throws BeansException { 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()) + "]"); } // Don't let calling code try to dereference the // bean factory if the bean isn't a factory if (BeanFactoryUtils.isFactoryDereference(name) && !(bean instanceof FactoryBean)) { throw new BeanIsNotAFactoryException(beanName, bean.getClass()); } if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { try { Object exposedObject = ((FactoryBean<?>) bean).getObject(); if (exposedObject == null) { throw new BeanCreationException(beanName, "FactoryBean exposed null object"); } return exposedObject; } catch (Exception ex) { throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); } } else { return bean; } }
Example #22
Source File: FreeMarkerView.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Autodetect a {@link FreeMarkerConfig} object via the ApplicationContext. * @return the Configuration instance to use for FreeMarkerViews * @throws BeansException if no Configuration instance could be found * @see #getApplicationContext * @see #setConfiguration */ protected FreeMarkerConfig autodetectConfiguration() throws BeansException { try { return BeanFactoryUtils.beanOfTypeIncludingAncestors( getApplicationContext(), FreeMarkerConfig.class, true, false); } catch (NoSuchBeanDefinitionException ex) { throw new ApplicationContextException( "Must define a single FreeMarkerConfig bean in this web application context " + "(may be inherited): FreeMarkerConfigurer is the usual implementation. " + "This bean may be given any name.", ex); } }
Example #23
Source File: ContentNegotiatingViewResolver.java From lams with GNU General Public License v2.0 | 5 votes |
@Override protected void initServletContext(ServletContext servletContext) { Collection<ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(getApplicationContext(), ViewResolver.class).values(); if (this.viewResolvers == null) { this.viewResolvers = new ArrayList<ViewResolver>(matchingBeans.size()); for (ViewResolver viewResolver : matchingBeans) { if (this != viewResolver) { this.viewResolvers.add(viewResolver); } } } else { for (int i = 0; i < viewResolvers.size(); i++) { if (matchingBeans.contains(viewResolvers.get(i))) { continue; } String name = viewResolvers.get(i).getClass().getName() + i; getApplicationContext().getAutowireCapableBeanFactory().initializeBean(viewResolvers.get(i), name); } } if (this.viewResolvers.isEmpty()) { logger.warn("Did not find any ViewResolvers to delegate to; please configure them using the " + "'viewResolvers' property on the ContentNegotiatingViewResolver"); } AnnotationAwareOrderComparator.sort(this.viewResolvers); this.cnmFactoryBean.setServletContext(servletContext); }
Example #24
Source File: DispatcherServlet.java From lams with GNU General Public License v2.0 | 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<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 #25
Source File: MessageBusAdapterConfiguration.java From spring-bus with Apache License 2.0 | 5 votes |
protected Collection<InputChannelBinding> getInputChannels() { Set<InputChannelBinding> channels = new LinkedHashSet<InputChannelBinding>(); String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( this.beanFactory, MessageChannel.class); for (String name : names) { if (name.startsWith("input")) { channels.add(new InputChannelBinding(name)); } } return channels; }
Example #26
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 #27
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 #28
Source File: CategoryManager.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
private String[] loadCategoryUtilizers() { String[] beans = null; try { beans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) this.getBeanFactory(), CategoryUtilizer.class); } catch (Throwable t) { _logger.error("error loading CategoryUtilizer bean names"); throw new RuntimeException(t); } return beans; }
Example #29
Source File: VelocityView.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Autodetect a VelocityEngine via the ApplicationContext. * Called if no explicit VelocityEngine has been specified. * @return the VelocityEngine to use for VelocityViews * @throws BeansException if no VelocityEngine could be found * @see #getApplicationContext * @see #setVelocityEngine */ protected VelocityEngine autodetectVelocityEngine() throws BeansException { try { VelocityConfig velocityConfig = BeanFactoryUtils.beanOfTypeIncludingAncestors( getApplicationContext(), VelocityConfig.class, true, false); return velocityConfig.getVelocityEngine(); } catch (NoSuchBeanDefinitionException ex) { throw new ApplicationContextException( "Must define a single VelocityConfig bean in this web application context " + "(may be inherited): VelocityConfigurer is the usual implementation. " + "This bean may be given any name.", ex); } }
Example #30
Source File: DispatcherPortlet.java From spring4-understanding with Apache License 2.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. } } // Just for consistency, check for default HandlerExceptionResolvers... // There aren't any in usual scenarios. if (this.handlerExceptionResolvers == null) { this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class); if (logger.isDebugEnabled()) { logger.debug("No HandlerExceptionResolvers found in portlet '" + getPortletName() + "': using default"); } } }