org.springframework.beans.factory.BeanNotOfRequiredTypeException Java Examples

The following examples show how to use org.springframework.beans.factory.BeanNotOfRequiredTypeException. 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: SolaceJmsAutoConfigurationTest.java    From solace-jms-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void noExternallyLoadedServiceProperties() {
	// Testing one type of externally loaded service is good enough
	// The loader has its own tests for the other scenarios
	String ENV_SOLCAP_SERVICES = "SOLCAP_SERVICES";
	load(String.format("%s={ \"solace-pubsub\": [] }", ENV_SOLCAP_SERVICES));

	String solaceManifest = context.getEnvironment().getProperty(ENV_SOLCAP_SERVICES);
	assertNotNull(solaceManifest);
	assertTrue(solaceManifest.contains("solace-pubsub"));

	assertNotNull(this.context.getBean(SolConnectionFactory.class));
	assertNotNull(this.context.getBean(SpringSolJmsConnectionFactoryCloudFactory.class));
	try {
		assertNull(this.context.getBean(SolaceServiceCredentials.class));
	} catch (BeanNotOfRequiredTypeException e) {
		assert(e.getMessage().contains("was actually of type 'org.springframework.beans.factory.support.NullBean'"));
	}
}
 
Example #2
Source File: AgentFileProtocolResolverRegistrar.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
    if (applicationContext instanceof ConfigurableApplicationContext) {

        final ConfigurableApplicationContext configurableApplicationContext
            = (ConfigurableApplicationContext) applicationContext;

        log.info(
            "Adding instance of {} to the set of protocol resolvers",
            this.agentFileProtocolResolver.getClass().getCanonicalName()
        );
        configurableApplicationContext.addProtocolResolver(this.agentFileProtocolResolver);
    } else {
        throw new BeanNotOfRequiredTypeException(
            "applicationContext",
            ConfigurableApplicationContext.class,
            ApplicationContext.class
        );
    }
}
 
Example #3
Source File: TomcatApplication.java    From micro-server with Apache License 2.0 6 votes vote down vote up
private void addSSL(Connector connector) {
    try {

        SSLProperties sslProperties = serverData.getRootContext().getBean(SSLProperties.class);
        ProtocolHandler handler = connector.getProtocolHandler();
        if (sslProperties != null && handler instanceof AbstractHttp11JsseProtocol) {
            new SSLConfigurationBuilder().build((AbstractHttp11JsseProtocol) handler, sslProperties);
            connector.setScheme("https");
            connector.setSecure(true);
        }

    } catch (BeanNotOfRequiredTypeException e) {

    }


}
 
Example #4
Source File: SolaceJavaAutoConfigurationTest.java    From solace-java-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void noExternallyLoadedServicePropertiesBasicBeanTest() {
	// Testing one type of externally loaded service is good enough
	// The loader has its own tests for the other scenarios
	String ENV_SOLCAP_SERVICES = "SOLCAP_SERVICES";
	load(String.format("%s={ \"solace-pubsub\": [] }", ENV_SOLCAP_SERVICES));

	String solaceManifest = context.getEnvironment().getProperty(ENV_SOLCAP_SERVICES);
	assertNotNull(solaceManifest);
	assertTrue(solaceManifest.contains("solace-pubsub"));

	assertNotNull(this.context.getBean(SpringJCSMPFactoryCloudFactory.class));
	assertNotNull(this.context.getBean(SpringJCSMPFactory.class));
	assertNotNull(this.context.getBean(JCSMPProperties.class));
               try {
                   assertNull(this.context.getBean(SolaceServiceCredentials.class));
               } catch (BeanNotOfRequiredTypeException e) {
                   assert(e.getMessage().contains("was actually of type 'org.springframework.beans.factory.support.NullBean'"));
               }
}
 
Example #5
Source File: DefaultListableBeanFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Raise a BeanNotOfRequiredTypeException for an unresolvable dependency, if applicable,
 * i.e. if the target type of the bean would match but an exposed proxy doesn't.
 */
private void checkBeanNotOfRequiredType(Class<?> type, DependencyDescriptor descriptor) {
	for (String beanName : this.beanDefinitionNames) {
		RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
		Class<?> targetType = mbd.getTargetType();
		if (targetType != null && type.isAssignableFrom(targetType) &&
				isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) {
			// Probably a proxy interfering with target type match -> throw meaningful exception.
			Object beanInstance = getSingleton(beanName, false);
			Class<?> beanType = (beanInstance != null ? beanInstance.getClass() : predictBeanType(beanName, mbd));
			if (!type.isAssignableFrom((beanType))) {
				throw new BeanNotOfRequiredTypeException(beanName, type, beanType);
			}
		}
	}

	BeanFactory parent = getParentBeanFactory();
	if (parent instanceof DefaultListableBeanFactory) {
		((DefaultListableBeanFactory) parent).checkBeanNotOfRequiredType(type, descriptor);
	}
}
 
Example #6
Source File: DefaultListableBeanFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Raise a BeanNotOfRequiredTypeException for an unresolvable dependency, if applicable,
 * i.e. if the target type of the bean would match but an exposed proxy doesn't.
 */
private void checkBeanNotOfRequiredType(Class<?> type, DependencyDescriptor descriptor) {
	for (String beanName : this.beanDefinitionNames) {
		RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
		Class<?> targetType = mbd.getTargetType();
		if (targetType != null && type.isAssignableFrom(targetType) &&
				isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) {
			// Probably a proxy interfering with target type match -> throw meaningful exception.
			Object beanInstance = getSingleton(beanName, false);
			Class<?> beanType = (beanInstance != null && beanInstance.getClass() != NullBean.class ?
					beanInstance.getClass() : predictBeanType(beanName, mbd));
			if (beanType != null && !type.isAssignableFrom(beanType)) {
				throw new BeanNotOfRequiredTypeException(beanName, type, beanType);
			}
		}
	}

	BeanFactory parent = getParentBeanFactory();
	if (parent instanceof DefaultListableBeanFactory) {
		((DefaultListableBeanFactory) parent).checkBeanNotOfRequiredType(type, descriptor);
	}
}
 
Example #7
Source File: DefaultListableBeanFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Raise a BeanNotOfRequiredTypeException for an unresolvable dependency, if applicable,
 * i.e. if the target type of the bean would match but an exposed proxy doesn't.
 */
private void checkBeanNotOfRequiredType(Class<?> type, DependencyDescriptor descriptor) {
	for (String beanName : this.beanDefinitionNames) {
		RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
		Class<?> targetType = mbd.getTargetType();
		if (targetType != null && type.isAssignableFrom(targetType) &&
				isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) {
			// Probably a proxy interfering with target type match -> throw meaningful exception.
			Object beanInstance = getSingleton(beanName, false);
			Class<?> beanType = (beanInstance != null && beanInstance.getClass() != NullBean.class ?
					beanInstance.getClass() : predictBeanType(beanName, mbd));
			if (beanType != null && !type.isAssignableFrom(beanType)) {
				throw new BeanNotOfRequiredTypeException(beanName, type, beanType);
			}
		}
	}

	BeanFactory parent = getParentBeanFactory();
	if (parent instanceof DefaultListableBeanFactory) {
		((DefaultListableBeanFactory) parent).checkBeanNotOfRequiredType(type, descriptor);
	}
}
 
Example #8
Source File: BeanFactoryDataSourceLookupTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
	final BeanFactory beanFactory = mock(BeanFactory.class);

	given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow(
			new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME,
					DataSource.class, String.class));

	try {
			BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
			lookup.getDataSource(DATASOURCE_BEAN_NAME);
			fail("should have thrown DataSourceLookupFailureException");
	}
	catch (DataSourceLookupFailureException ex) { /* expected */ }
}
 
Example #9
Source File: EnableAsyncTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void properExceptionForResolvedProxyDependencyMismatch() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(AsyncConfig.class, AsyncBeanUser.class, AsyncBeanWithInterface.class);

	try {
		ctx.refresh();
		fail("Should have thrown UnsatisfiedDependencyException");
	}
	catch (UnsatisfiedDependencyException ex) {
		assertTrue(ex.getCause() instanceof BeanNotOfRequiredTypeException);
	}

	ctx.close();
}
 
Example #10
Source File: BeanFactoryDataSourceLookupTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Test
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
	final BeanFactory beanFactory = mock(BeanFactory.class);

	given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow(
			new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME,
					DataSource.class, String.class));

	try {
			BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
			lookup.getDataSource(DATASOURCE_BEAN_NAME);
			fail("should have thrown DataSourceLookupFailureException");
	} catch (DataSourceLookupFailureException ex) { /* expected */ }
}
 
Example #11
Source File: EnableAsyncTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void exceptionThrownWithBeanNotOfRequiredTypeRootCause() {
	try {
		new AnnotationConfigApplicationContext(JdkProxyConfiguration.class);
		fail("Should have thrown exception");
	}
	catch (Throwable ex) {
		ex.printStackTrace();
		while (ex.getCause() != null) {
			ex = ex.getCause();
		}
		assertThat(ex, instanceOf(BeanNotOfRequiredTypeException.class));
	}
}
 
Example #12
Source File: AbstractBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void getSharedInstanceByNonmatchingClass() {
	try {
		getBeanFactory().getBean("rod", BeanFactory.class);
		fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
	}
	catch (BeanNotOfRequiredTypeException ex) {
		// So far, so good
		assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
		assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
		assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
	}
}
 
Example #13
Source File: AbstractBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void getInstanceByNonmatchingClass() {
	try {
		getBeanFactory().getBean("rod", BeanFactory.class);
		fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
	}
	catch (BeanNotOfRequiredTypeException ex) {
		// So far, so good
		assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
		assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
		assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
		assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass());
	}
}
 
Example #14
Source File: StaticListableBeanFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
	Object bean = getBean(name);
	if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
		throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
	}
	return (T) bean;
}
 
Example #15
Source File: BeanFactoryDataSourceLookupTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
	final BeanFactory beanFactory = mock(BeanFactory.class);

	given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow(
			new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME,
					DataSource.class, String.class));

	try {
			BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
			lookup.getDataSource(DATASOURCE_BEAN_NAME);
			fail("should have thrown DataSourceLookupFailureException");
	} catch (DataSourceLookupFailureException ex) { /* expected */ }
}
 
Example #16
Source File: StaticListableBeanFactory.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
	Object bean = getBean(name);
	if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
		throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
	}
	return (T) bean;
}
 
Example #17
Source File: SolaceJavaAutoConfigurationTest.java    From solace-java-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void applicationPropertiesBasicBeanTest() {
	load("");
	assertNotNull(this.context.getBean(SpringJCSMPFactoryCloudFactory.class));
	assertNotNull(this.context.getBean(SpringJCSMPFactory.class));
	assertNotNull(this.context.getBean(JCSMPProperties.class));
               try {
                   assertNull(this.context.getBean(SolaceServiceCredentials.class));
               } catch (BeanNotOfRequiredTypeException e) {
                   assert(e.getMessage().contains("was actually of type 'org.springframework.beans.factory.support.NullBean'"));
               }
}
 
Example #18
Source File: StaticListableBeanFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException {
	Object bean = getBean(name);
	if (requiredType != null && !requiredType.isInstance(bean)) {
		throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
	}
	return (T) bean;
}
 
Example #19
Source File: EnableAsyncTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void properExceptionForResolvedProxyDependencyMismatch() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(AsyncConfig.class, AsyncBeanUser.class, AsyncBeanWithInterface.class);

	try {
		ctx.refresh();
		fail("Should have thrown UnsatisfiedDependencyException");
	}
	catch (UnsatisfiedDependencyException ex) {
		assertTrue(ex.getCause() instanceof BeanNotOfRequiredTypeException);
	}

	ctx.close();
}
 
Example #20
Source File: AbstractBeanFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void getInstanceByNonmatchingClass() {
	try {
		getBeanFactory().getBean("rod", BeanFactory.class);
		fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
	}
	catch (BeanNotOfRequiredTypeException ex) {
		// So far, so good
		assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
		assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
		assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
		assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass());
	}
}
 
Example #21
Source File: AbstractBeanFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void getSharedInstanceByNonmatchingClass() {
	try {
		getBeanFactory().getBean("rod", BeanFactory.class);
		fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
	}
	catch (BeanNotOfRequiredTypeException ex) {
		// So far, so good
		assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
		assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
		assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
	}
}
 
Example #22
Source File: EnableAsyncTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void properExceptionForExistingProxyDependencyMismatch() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(AsyncConfig.class, AsyncBeanWithInterface.class, AsyncBeanUser.class);

	try {
		ctx.refresh();
		fail("Should have thrown UnsatisfiedDependencyException");
	}
	catch (UnsatisfiedDependencyException ex) {
		assertTrue(ex.getCause() instanceof BeanNotOfRequiredTypeException);
	}
	ctx.close();
}
 
Example #23
Source File: StaticListableBeanFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
	Object bean = getBean(name);
	if (requiredType != null && !requiredType.isInstance(bean)) {
		throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
	}
	return (T) bean;
}
 
Example #24
Source File: BeanFactoryDataSourceLookupTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
	final BeanFactory beanFactory = mock(BeanFactory.class);

	given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow(
			new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME,
					DataSource.class, String.class));

	try {
			BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
			lookup.getDataSource(DATASOURCE_BEAN_NAME);
			fail("should have thrown DataSourceLookupFailureException");
	}
	catch (DataSourceLookupFailureException ex) { /* expected */ }
}
 
Example #25
Source File: StaticListableBeanFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException {
	Object bean = getBean(name);
	if (requiredType != null && !requiredType.isInstance(bean)) {
		throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
	}
	return (T) bean;
}
 
Example #26
Source File: AbstractBeanFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void getInstanceByNonmatchingClass() {
	try {
		getBeanFactory().getBean("rod", BeanFactory.class);
		fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
	}
	catch (BeanNotOfRequiredTypeException ex) {
		// So far, so good
		assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
		assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
		assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
		assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass());
	}
}
 
Example #27
Source File: AbstractBeanFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void getSharedInstanceByNonmatchingClass() {
	try {
		getBeanFactory().getBean("rod", BeanFactory.class);
		fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
	}
	catch (BeanNotOfRequiredTypeException ex) {
		// So far, so good
		assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
		assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
		assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
	}
}
 
Example #28
Source File: EnableAsyncTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void properExceptionForExistingProxyDependencyMismatch() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(AsyncConfig.class, AsyncBeanWithInterface.class, AsyncBeanUser.class);

	try {
		ctx.refresh();
		fail("Should have thrown UnsatisfiedDependencyException");
	}
	catch (UnsatisfiedDependencyException ex) {
		assertTrue(ex.getCause() instanceof BeanNotOfRequiredTypeException);
	}
	ctx.close();
}
 
Example #29
Source File: DefaultListableBeanFactory.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
		@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

	InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
	try {
		Object shortcut = descriptor.resolveShortcut(this);
		if (shortcut != null) {
			return shortcut;
		}

		Class<?> type = descriptor.getDependencyType();
		Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
		if (value != null) {
			if (value instanceof String) {
				String strVal = resolveEmbeddedValue((String) value);
				BeanDefinition bd = (beanName != null && containsBean(beanName) ?
						getMergedBeanDefinition(beanName) : null);
				value = evaluateBeanDefinitionString(strVal, bd);
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			try {
				return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
			}
			catch (UnsupportedOperationException ex) {
				// A custom TypeConverter which does not support TypeDescriptor resolution...
				return (descriptor.getField() != null ?
						converter.convertIfNecessary(value, type, descriptor.getField()) :
						converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
			}
		}

		Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
		if (multipleBeans != null) {
			return multipleBeans;
		}

		Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
		if (matchingBeans.isEmpty()) {
			if (isRequired(descriptor)) {
				raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
			}
			return null;
		}

		String autowiredBeanName;
		Object instanceCandidate;

		if (matchingBeans.size() > 1) {
			autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
			if (autowiredBeanName == null) {
				if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
					return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
				}
				else {
					// In case of an optional Collection/Map, silently ignore a non-unique case:
					// possibly it was meant to be an empty collection of multiple regular beans
					// (before 4.3 in particular when we didn't even look for collection beans).
					return null;
				}
			}
			instanceCandidate = matchingBeans.get(autowiredBeanName);
		}
		else {
			// We have exactly one match.
			Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
			autowiredBeanName = entry.getKey();
			instanceCandidate = entry.getValue();
		}

		if (autowiredBeanNames != null) {
			autowiredBeanNames.add(autowiredBeanName);
		}
		if (instanceCandidate instanceof Class) {
			instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
		}
		Object result = instanceCandidate;
		if (result instanceof NullBean) {
			if (isRequired(descriptor)) {
				raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
			}
			result = null;
		}
		if (!ClassUtils.isAssignableValue(type, result)) {
			throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
		}
		return result;
	}
	finally {
		ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
	}
}
 
Example #30
Source File: DefaultListableBeanFactory.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
		@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

	InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
	try {
		Object shortcut = descriptor.resolveShortcut(this);
		if (shortcut != null) {
			return shortcut;
		}

		Class<?> type = descriptor.getDependencyType();
		Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
		if (value != null) {
			if (value instanceof String) {
				String strVal = resolveEmbeddedValue((String) value);
				BeanDefinition bd = (beanName != null && containsBean(beanName) ?
						getMergedBeanDefinition(beanName) : null);
				value = evaluateBeanDefinitionString(strVal, bd);
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			try {
				return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
			}
			catch (UnsupportedOperationException ex) {
				// A custom TypeConverter which does not support TypeDescriptor resolution...
				return (descriptor.getField() != null ?
						converter.convertIfNecessary(value, type, descriptor.getField()) :
						converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
			}
		}

		Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
		if (multipleBeans != null) {
			return multipleBeans;
		}

		Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
		if (matchingBeans.isEmpty()) {
			if (isRequired(descriptor)) {
				raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
			}
			return null;
		}

		String autowiredBeanName;
		Object instanceCandidate;

		if (matchingBeans.size() > 1) {
			autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
			if (autowiredBeanName == null) {
				if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
					return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
				}
				else {
					// In case of an optional Collection/Map, silently ignore a non-unique case:
					// possibly it was meant to be an empty collection of multiple regular beans
					// (before 4.3 in particular when we didn't even look for collection beans).
					return null;
				}
			}
			instanceCandidate = matchingBeans.get(autowiredBeanName);
		}
		else {
			// We have exactly one match.
			Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
			autowiredBeanName = entry.getKey();
			instanceCandidate = entry.getValue();
		}

		if (autowiredBeanNames != null) {
			autowiredBeanNames.add(autowiredBeanName);
		}
		if (instanceCandidate instanceof Class) {
			instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
		}
		Object result = instanceCandidate;
		if (result instanceof NullBean) {
			if (isRequired(descriptor)) {
				raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
			}
			result = null;
		}
		if (!ClassUtils.isAssignableValue(type, result)) {
			throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
		}
		return result;
	}
	finally {
		ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
	}
}