@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(); }
/** * 先使用类的缩写,再使用类全称来查找 * @param pageClsStr pageClsStr * @return pageClsStr */ private Object getBean(String pageClsStr) { String beanName = convertBeanName(pageClsStr); Object obj = null; try { obj = context.getBean(beanName); } catch(NoSuchBeanDefinitionException e) { obj = context.getBean(pageClsStr); } return obj; }
@PostConstruct public void init() { if (!configuration.isInitialize()) { LOGGER.debug(() -> "Initialization disabled (not running DDL scripts) for data context id: [" + getDataContextId().orElse("DEFAULT") + "]"); return; } DataSource dataSource = null; try { dataSource = applicationContext.getBean(dataSourceBeanName, DataSource.class); } catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException | BeanNotOfRequiredTypeException e) { // ignore } if (dataSource == null) { LOGGER.debug(() -> "No DataSource found using bean name " + dataSourceBeanName + ": skip initialization"); return; } runSchemaScripts(dataSource); }
@Override protected AuthenticationComponent getAuthenticationComponent(String instanceId) { ApplicationContext context = this.applicationContextManager.getApplicationContext(instanceId); if(context != null) { try { AuthenticationComponent authenticationComponent = (AuthenticationComponent) context .getBean(sourceBeanName); return authenticationComponent; } catch (NoSuchBeanDefinitionException e) { return null; } } return null; }
@Override public void afterPropertiesSet() throws Exception { ParameterCheck.mandatory("authenticationContextManager", authenticationContextManager); //Attempt to get RepositoryAuthenticationDao from the subsystem for(String contextName : authenticationContextManager.getInstanceIds()) { ApplicationContext ctx = authenticationContextManager.getApplicationContext(contextName); try { authenticationDao = (RepositoryAuthenticationDao) ctx.getBean(RepositoryAuthenticationDao.class); } catch(NoSuchBeanDefinitionException e) {} } }
@Override protected ActionDefinition getTypedItem(Item item) { final String actionDefId = item.getId(); ActionDefinition actionDef = null; try { actionDef = actionService.getActionDefinition(actionDefId); } catch (NoSuchBeanDefinitionException nsbdx) { // Intentionally empty. } if (actionDef == null) { throw new FormNotFoundException(item); } return actionDef; }
@Override protected Object makeItemData(ActionDefinition item) { ActionItemData actionItemData = null; try { Action action = actionService.createAction(item.getName()); actionItemData = new ActionItemData(item, action); } catch (NoSuchBeanDefinitionException nsbdx) { throw new FormException("Failed to create action '" + item.getName() + "'", nsbdx); } return actionItemData; }
private ApplicationContextFactory getSourceApplicationContextFactory() { if (sourceApplicationContextFactory != null) { return sourceApplicationContextFactory; } else { try { return applicationContext.getBean(sourceApplicationContextFactoryName, ApplicationContextFactory.class); } catch (NoSuchBeanDefinitionException e) { return null; } } }
/** * given that the bean does not exist ensure that an exception is thrown */ @Test public void beanDoesNotExist() { // === given === // set the bean names beanExtender.setBeanName(BEAN_NAME); beanExtender.setExtendingBeanName(EXTENDING_BEAN_NAME); doReturn(false).when(mockedBeanFactory).containsBean(BEAN_NAME); doReturn(true).when(mockedBeanFactory).containsBean(EXTENDING_BEAN_NAME); // expecting exception exception.expect(NoSuchBeanDefinitionException.class); // === when === beanExtender.postProcessBeanFactory(mockedBeanFactory); }
/** * given that the extending bean does not exist ensure that an exception is thrown */ @Test public void extendingBeanDoesNotExist() { // === given === // set the bean names beanExtender.setBeanName(BEAN_NAME); beanExtender.setExtendingBeanName(EXTENDING_BEAN_NAME); doReturn(true).when(mockedBeanFactory).containsBean(BEAN_NAME); doReturn(false).when(mockedBeanFactory).containsBean(EXTENDING_BEAN_NAME); // expecting exception exception.expect(NoSuchBeanDefinitionException.class); // === when === beanExtender.postProcessBeanFactory(mockedBeanFactory); }
@Override public ActionDefinition getActionDefinitionById(String actionDefinitionId) { if (actionDefinitionId == null) { throw new IllegalArgumentException("Missing actionDefinitionId"); } // Non-existing actionDefinitionId -> 404 ActionDefinition result = null; try { result = getActionDefinition(actionService.getActionDefinition(actionDefinitionId)); } catch (NoSuchBeanDefinitionException nsbdx) { // Intentionally empty. } if (result == null) { throw new EntityNotFoundException(actionDefinitionId); } return result; }
@Override public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException { LOGGER.debug(() -> "Lookup @Path and @Provider JAX-RS resource in bean factory [" + beanFactory + "]"); resources = new ArrayList<>(); for (String name : beanFactory.getBeanDefinitionNames()) { try { BeanDefinition definition = beanFactory.getBeanDefinition(name); if (!definition.isAbstract()) { Class<?> beanClass = BeanRegistryUtils.getBeanClass(name, definition, beanFactory, classLoader); if (beanClass != null) { if (isJaxrsResourceClass(definition, beanClass)) { resources.add(new WeakReference<>(beanClass)); LOGGER.debug(() -> "Found JAX-RS resource class: [" + beanClass.getName() + "]"); } } } } catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException e) { // ignore } } }
@Override protected Object getResourceToInject(Object target, String requestingBeanName) { if (StringUtils.hasLength(this.beanName)) { if (beanFactory != null && beanFactory.containsBean(this.beanName)) { // Local match found for explicitly specified local bean name. Object bean = beanFactory.getBean(this.beanName, this.lookupType); if (beanFactory instanceof ConfigurableBeanFactory) { ((ConfigurableBeanFactory) beanFactory).registerDependentBean(this.beanName, requestingBeanName); } return bean; } else if (this.isDefaultName && !StringUtils.hasLength(this.mappedName)) { throw new NoSuchBeanDefinitionException(this.beanName, "Cannot resolve 'beanName' in local BeanFactory. Consider specifying a general 'name' value instead."); } } // JNDI name lookup - may still go to a local BeanFactory. return getResource(this, requestingBeanName); }
/** * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a * qualifier (e.g. via {@code <qualifier>} or {@code @Qualifier}) matching the given * qualifier, or having a bean name matching the given qualifier. * @param beanFactory 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 */ public static <T> T qualifiedBeanOfType(BeanFactory beanFactory, Class<T> beanType, String qualifier) { if (beanFactory instanceof ConfigurableListableBeanFactory) { // Full qualifier matching supported. return qualifiedBeanOfType((ConfigurableListableBeanFactory) beanFactory, beanType, qualifier); } else if (beanFactory.containsBean(qualifier)) { // Fallback: target bean at least found by bean name. return beanFactory.getBean(qualifier, beanType); } else { throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() + " bean found for bean name '" + qualifier + "'! (Note: Qualifier matching not supported because given " + "BeanFactory does not implement ConfigurableListableBeanFactory.)"); } }
/** * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier * (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier). * @param bf the BeanFactory to get the target bean from * @param beanType the type of bean to retrieve * @param qualifier the qualifier for selecting between multiple bean matches * @return the matching bean of type {@code T} (never {@code null}) * @throws NoSuchBeanDefinitionException if no matching bean of type {@code T} found */ private static <T> T qualifiedBeanOfType(ConfigurableListableBeanFactory bf, Class<T> beanType, String qualifier) { Map<String, T> candidateBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(bf, beanType); T matchingBean = null; for (String beanName : candidateBeans.keySet()) { if (isQualifierMatch(qualifier, beanName, bf)) { if (matchingBean != null) { throw new NoSuchBeanDefinitionException(qualifier, "No unique " + beanType.getSimpleName() + " bean found for qualifier '" + qualifier + "'"); } matchingBean = candidateBeans.get(beanName); } } if (matchingBean != null) { return matchingBean; } else if (bf.containsBean(qualifier)) { // Fallback: target bean at least found by bean name - probably a manually registered singleton. return bf.getBean(qualifier, beanType); } else { throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() + " bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!"); } }
@Override public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Object beanInstance = getSingleton(beanName, false); if (beanInstance != null) { return (beanInstance instanceof FactoryBean); } else if (containsSingleton(beanName)) { // null instance registered return false; } // No singleton instance found -> check bean definition. if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { // No bean definition found in this factory -> delegate to parent. return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name); } return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName)); }
/** * Find a {@link Annotation} of {@code annotationType} on the specified * bean, traversing its interfaces and super classes if no annotation can be * found on the given class itself, as well as checking its raw bean class * if not found on the exposed bean reference (e.g. in case of a proxy). */ @Override public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) throws NoSuchBeanDefinitionException{ A ann = null; Class<?> beanType = getType(beanName); if (beanType != null) { ann = AnnotationUtils.findAnnotation(beanType, annotationType); } if (ann == null && containsBeanDefinition(beanName)) { BeanDefinition bd = getMergedBeanDefinition(beanName); if (bd instanceof AbstractBeanDefinition) { AbstractBeanDefinition abd = (AbstractBeanDefinition) bd; if (abd.hasBeanClass()) { ann = AnnotationUtils.findAnnotation(abd.getBeanClass(), annotationType); } } } return ann; }
/** * Determine whether the specified bean definition qualifies as an autowire candidate, * to be injected into other beans which declare a dependency of matching type. * @param beanName the name of the bean definition to check * @param descriptor the descriptor of the dependency to resolve * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm * @return whether the bean should be considered as autowire candidate */ protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) throws NoSuchBeanDefinitionException { String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); if (containsBeanDefinition(beanDefinitionName)) { return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver); } else if (containsSingleton(beanName)) { return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver); } else if (getParentBeanFactory() instanceof DefaultListableBeanFactory) { // No bean definition found in this factory -> delegate to parent. return ((DefaultListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName, descriptor, resolver); } else if (getParentBeanFactory() instanceof ConfigurableListableBeanFactory) { // If no DefaultListableBeanFactory, can't pass the resolver along. return ((ConfigurableListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName, descriptor); } else { return true; } }
@Override public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { Assert.hasText(beanName, "'beanName' must not be empty"); synchronized (this.beanDefinitionMap) { BeanDefinition bd = this.beanDefinitionMap.remove(beanName); if (bd == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("No bean named '" + beanName + "' found in " + this); } throw new NoSuchBeanDefinitionException(beanName); } this.beanDefinitionNames.remove(beanName); this.frozenBeanDefinitionNames = null; } resetBeanDefinition(beanName); }
/** * Find an EntityManagerFactory with the given name in the given * Spring application context (represented as ListableBeanFactory). * <p>The specified unit name will be matched against the configured * persistence unit, provided that a discovered EntityManagerFactory * implements the {@link EntityManagerFactoryInfo} interface. If not, * the persistence unit name will be matched against the Spring bean name, * assuming that the EntityManagerFactory bean names follow that convention. * <p>If no unit name has been given, this method will search for a default * EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}. * @param beanFactory the ListableBeanFactory to search * @param unitName the name of the persistence unit (may be {@code null} or empty, * in which case a single bean of type EntityManagerFactory will be searched for) * @return the EntityManagerFactory * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context * @see EntityManagerFactoryInfo#getPersistenceUnitName() */ public static EntityManagerFactory findEntityManagerFactory( ListableBeanFactory beanFactory, String unitName) throws NoSuchBeanDefinitionException { Assert.notNull(beanFactory, "ListableBeanFactory must not be null"); if (StringUtils.hasLength(unitName)) { // See whether we can find an EntityManagerFactory with matching persistence unit name. String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, EntityManagerFactory.class); for (String candidateName : candidateNames) { EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName); if (emf instanceof EntityManagerFactoryInfo) { if (unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) { return emf; } } } // No matching persistence unit found - simply take the EntityManagerFactory // with the persistence unit name as bean name (by convention). return beanFactory.getBean(unitName, EntityManagerFactory.class); } else { // Find unique EntityManagerFactory bean in the context, falling back to parent contexts. return beanFactory.getBean(EntityManagerFactory.class); } }
@Override public Long notifyToolToCopyContent(ToolActivity toolActivity, String customCSV) throws DataMissingException, ToolException { Long toolcontentID = toolActivity.getToolContentId(); try { ToolContentManager contentManager = (ToolContentManager) findToolService(toolActivity.getTool()); toolcontentID = contentIDGenerator.getNextToolContentIDFor(toolActivity.getTool()); // If it is a tool adapter tool, call the special copyToolContent which takes the customCSV param if (contentManager instanceof ToolAdapterContentManager) { ToolAdapterContentManager adapterContentManager = (ToolAdapterContentManager) contentManager; adapterContentManager.copyToolContent(toolActivity.getToolContentId(), toolcontentID, customCSV); } else { contentManager.copyToolContent(toolActivity.getToolContentId(), toolcontentID); } } catch (NoSuchBeanDefinitionException e) { String message = "A tool which is defined in the database appears to missing from the classpath. Unable to copy/update the tool content. ToolActivity " + toolActivity; LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); } return toolcontentID; }
/** * Return the {@link JpaEntityScanPackages} for the given bean factory. * @param beanFactory the source bean factory * @param dataContextId Data context id * @return the {@link JpaEntityScanPackages} for the bean factory (never {@code null}) */ public static JpaEntityScanPackages get(BeanFactory beanFactory, String dataContextId) { try { return beanFactory.getBean(buildBeanName(dataContextId), JpaEntityScanPackages.class); } catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException ex) { return NONE; } }
@Test public void switchToJwt() { TestPropertyValues.of("security.oauth2.resource.jwt.keyValue=FOOBAR") .applyTo(this.environment); this.context = new SpringApplicationBuilder(ResourceConfiguration.class) .environment(this.environment).web(WebApplicationType.NONE).run(); DefaultTokenServices services = this.context.getBean(DefaultTokenServices.class); assertThat(services).isNotNull(); this.thrown.expect(NoSuchBeanDefinitionException.class); this.context.getBean(RemoteTokenServices.class); }
public static Object getBean(ServletContext servletContext, String name) { Object result = null; try { if (getApplicationContext(servletContext).containsBean(name)) { result = getApplicationContext(servletContext).getBean(name); } } catch (NoSuchBeanDefinitionException e) { LOG.error(e.getMessage(), e); } return result; }
/** * Returns a bean of specified type in the specified bean factory or its * ancestors. In contrast with Spring's BeanFactoryUtils, doesn't throw an * exception if no bean is found, but rather returns null. * * @param lbf * the bean factory to look for the bean * @param type * the expected type of the bean * @return the bean - if exactly one is defined. null - if none is defined * @throws NoSuchBeanDefinitionException * if more than one bean is defined */ public static <T> T beanOfTypeIncludingAncestors(final ListableBeanFactory lbf, final Class<T> type) { final Map<String, T> map = org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, type); switch (map.size()) { case 0: return null; case 1: return map.values().iterator().next(); default: throw new NoSuchBeanDefinitionException( "More than one bean of type " + type.getName() + " found: " + map.keySet()); } }
@Test public void doesntProvideCollectorComponent_whenSqsQueueUrlUnset() { context = new AnnotationConfigApplicationContext(); context.register(PropertyPlaceholderAutoConfiguration.class, EventHubCollectorProperties.class, EventHubCollectorAutoConfiguration.class, InMemoryConfiguration.class); context.refresh(); thrown.expect(NoSuchBeanDefinitionException.class); context.getBean(EventHubCollector.class); }
@Override public T getObject() throws BeansException { try { return delegate.getObject(); } catch (NoSuchBeanDefinitionException o_O) { return fallback.get(); } }
/** * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) */ @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { ParameterCheck.mandatory("beanName", beanName); ParameterCheck.mandatory("extendingBeanName", extendingBeanName); // check for bean name if (!beanFactory.containsBean(beanName)) { throw new NoSuchBeanDefinitionException("Can't find bean '" + beanName + "' to be extended."); } // check for extending bean if (!beanFactory.containsBean(extendingBeanName)) { throw new NoSuchBeanDefinitionException("Can't find bean '" + extendingBeanName + "' that is going to extend original bean definition."); } // get the bean definitions BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); BeanDefinition extendingBeanDefinition = beanFactory.getBeanDefinition(extendingBeanName); // update class if (StringUtils.isNotBlank(extendingBeanDefinition.getBeanClassName()) && !beanDefinition.getBeanClassName().equals(extendingBeanDefinition.getBeanClassName())) { beanDefinition.setBeanClassName(extendingBeanDefinition.getBeanClassName()); } // update properties MutablePropertyValues properties = beanDefinition.getPropertyValues(); MutablePropertyValues extendingProperties = extendingBeanDefinition.getPropertyValues(); for (PropertyValue propertyValue : extendingProperties.getPropertyValueList()) { properties.add(propertyValue.getName(), propertyValue.getValue()); } }
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/{id}") public List<VerifierResponse> verify(@PathParam("id") String connectorId, Map<String, Object> parameters) { List<VerifierResponse> answer; Verifier verifier; try { // First find try to lookup the verifier from the application context verifier = applicationContext.getBean(connectorId, Verifier.class); } catch (NoSuchBeanDefinitionException|NoSuchBeanException ignored) { LOGGER.debug("No bean of type: {} with id: {} found in application context, switch to factory finder", Verifier.class.getName(), connectorId); verifier = null; try { // Then fallback to camel's factory finder final FactoryFinder finder = camelContext.getFactoryFinder(RESOURCE_PATH); final Class<?> type = finder.findClass(connectorId); verifier = (Verifier) camelContext.getInjector().newInstance(type); } catch (Exception e) { LOGGER.warn("No factory finder of type: {} for id: {}", Verifier.class.getName(), connectorId, e); } } if (verifier != null) { answer = verifier.verify(camelContext, connectorId, parameters); answer = filterExceptions(answer); } else { answer = Collections.singletonList(createUnsupportedResponse(connectorId)); } return answer; }
@Path("/{connectorId}/actions") public ActionDefinitionEndpoint actions(@PathParam("connectorId") final String connectorId) throws Exception { MetadataAdapter<?> adapter; try { adapter = applicationContext.getBean(connectorId + "-adapter", MetadataAdapter.class); } catch (NoSuchBeanDefinitionException e) { throw new IllegalStateException("Unable to find adapter for:" + connectorId, e); } return new ActionDefinitionEndpoint(camelContext, connectorId, adapter); }
private String getBeanDefinition(String name) { try { return beanFactory.getMergedBeanDefinition(name) != null ? name : null; } catch (NoSuchBeanDefinitionException ex) { return null; } }
@Test public void doesntProvidesIssue343AdjusterWhenFinagleEnabledAndIssue343Disabled() { addEnvironment(context, "zipkin.sparkstreaming.adjuster.finagle.enabled:" + true); context.register(PropertyPlaceholderAutoConfiguration.class, ZipkinFinagleAdjusterAutoConfiguration.class); context.refresh(); thrown.expect(NoSuchBeanDefinitionException.class); context.getBean(FinagleIssue343Adjuster.class); }
@Override public Resource resolve(String location, ResourceLoader resourceLoader) { if (!location.startsWith(PROTOCOL)) { return null; } String pathWithoutProtocol = location.substring(PROTOCOL.length()); String[] pathParts = pathWithoutProtocol.split("/"); if (pathParts.length == 0 || pathWithoutProtocol.isEmpty()) { return null; } String bucketName = pathParts[0]; if (this.storage == null) { this.storage = this.beanFactory.getBean(Storage.class); try { this.settings = this.beanFactory .getBean(GoogleStorageProtocolResolverSettings.class); } catch (NoSuchBeanDefinitionException e) { logger.info("There is no bean definition for the resolver settings, " + "so defaults are used."); } } Resource resource; if (pathParts.length < 2) { resource = new GoogleStorageResourceBucket(this.storage, bucketName, this.settings.isAutoCreateFiles()); } else { resource = new GoogleStorageResourceObject(this.storage, location, this.settings.isAutoCreateFiles()); } return resource; }
/** * 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); } }
@Override public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) throws NoSuchBeanDefinitionException{ assertBeanFactoryActive(); return getBeanFactory().findAnnotationOnBean(beanName, annotationType); }
public Object getProperty(String property) { if (containsBean(property)) { return getBean(property); } else if (this.contextWrapper.isReadableProperty(property)) { return this.contextWrapper.getPropertyValue(property); } throw new NoSuchBeanDefinitionException(property); }
/** * Check whether the named bean declares a qualifier of the given name. * @param qualifier the qualifier to match * @param beanName the name of the candidate bean * @param bf the {@code BeanFactory} from which to retrieve the named bean * @return {@code true} if either the bean definition (in the XML case) * or the bean's factory method (in the {@code @Bean} case) defines a matching * qualifier value (through {@code <qualifier>} or {@code @Qualifier}) */ private static boolean isQualifierMatch(String qualifier, String beanName, ConfigurableListableBeanFactory bf) { if (bf.containsBean(beanName)) { try { BeanDefinition bd = bf.getMergedBeanDefinition(beanName); if (bd instanceof AbstractBeanDefinition) { AbstractBeanDefinition abd = (AbstractBeanDefinition) bd; AutowireCandidateQualifier candidate = abd.getQualifier(Qualifier.class.getName()); if ((candidate != null && qualifier.equals(candidate.getAttribute(AutowireCandidateQualifier.VALUE_KEY))) || qualifier.equals(beanName) || ObjectUtils.containsElement(bf.getAliases(beanName), qualifier)) { return true; } } if (bd instanceof RootBeanDefinition) { Method factoryMethod = ((RootBeanDefinition) bd).getResolvedFactoryMethod(); if (factoryMethod != null) { Qualifier targetAnnotation = factoryMethod.getAnnotation(Qualifier.class); if (targetAnnotation != null && qualifier.equals(targetAnnotation.value())) { return true; } } } } catch (NoSuchBeanDefinitionException ex) { // Ignore - can't compare qualifiers for a manually registered singleton object } } return false; }
@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 { return ((FactoryBean<?>) bean).getObject(); } catch (Exception ex) { throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); } } else { return bean; } }
@Override public <T> T getBean(Class<T> requiredType) throws BeansException { String[] beanNames = getBeanNamesForType(requiredType); if (beanNames.length == 1) { return getBean(beanNames[0], requiredType); } else if (beanNames.length > 1) { throw new NoUniqueBeanDefinitionException(requiredType, beanNames); } else { throw new NoSuchBeanDefinitionException(requiredType); } }
@Override public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { Object bean = getBean(name); // In case of FactoryBean, return prototype status of created object. return ((bean instanceof SmartFactoryBean && ((SmartFactoryBean<?>) bean).isPrototype()) || (bean instanceof FactoryBean && !((FactoryBean<?>) bean).isSingleton())); }