org.springframework.beans.factory.NoSuchBeanDefinitionException Java Examples

The following examples show how to use org.springframework.beans.factory.NoSuchBeanDefinitionException. 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: DispatcherServlet.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Initialize the ThemeResolver used by this class.
 * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
 * we default to a FixedThemeResolver.
 */
private void initThemeResolver(ApplicationContext context) {
	try {
		this.themeResolver = context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver.class);
		if (logger.isTraceEnabled()) {
			logger.trace("Detected " + this.themeResolver);
		}
		else if (logger.isDebugEnabled()) {
			logger.debug("Detected " + this.themeResolver.getClass().getSimpleName());
		}
	}
	catch (NoSuchBeanDefinitionException ex) {
		// We need to use the default.
		this.themeResolver = getDefaultStrategy(context, ThemeResolver.class);
		if (logger.isTraceEnabled()) {
			logger.trace("No ThemeResolver '" + THEME_RESOLVER_BEAN_NAME +
					"': using default [" + this.themeResolver.getClass().getSimpleName() + "]");
		}
	}
}
 
Example #2
Source File: CommonAnnotationBeanPostProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected Object getResourceToInject(Object target, @Nullable 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 (requestingBeanName != null && 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);
}
 
Example #3
Source File: EntityManagerFactoryUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Find an EntityManagerFactory with the given name in the given
 * Spring application context (represented as ListableBeanFactory).
 * <p>The specified unit name will be matched against the configured
 * persistence unit, provided that a discovered EntityManagerFactory
 * implements the {@link EntityManagerFactoryInfo} interface. If not,
 * the persistence unit name will be matched against the Spring bean name,
 * assuming that the EntityManagerFactory bean names follow that convention.
 * <p>If no unit name has been given, this method will search for a default
 * EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}.
 * @param beanFactory the ListableBeanFactory to search
 * @param unitName the name of the persistence unit (may be {@code null} or empty,
 * in which case a single bean of type EntityManagerFactory will be searched for)
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 * @see EntityManagerFactoryInfo#getPersistenceUnitName()
 */
public static EntityManagerFactory findEntityManagerFactory(
		ListableBeanFactory beanFactory, @Nullable String unitName) throws NoSuchBeanDefinitionException {

	Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
	if (StringUtils.hasLength(unitName)) {
		// See whether we can find an EntityManagerFactory with matching persistence unit name.
		String[] candidateNames =
				BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, EntityManagerFactory.class);
		for (String candidateName : candidateNames) {
			EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName);
			if (emf instanceof EntityManagerFactoryInfo &&
					unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) {
				return emf;
			}
		}
		// No matching persistence unit found - simply take the EntityManagerFactory
		// with the persistence unit name as bean name (by convention).
		return beanFactory.getBean(unitName, EntityManagerFactory.class);
	}
	else {
		// Find unique EntityManagerFactory bean in the context, falling back to parent contexts.
		return beanFactory.getBean(EntityManagerFactory.class);
	}
}
 
Example #4
Source File: InjectAnnotationAutowireContextTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testAutowiredFieldWithMultipleNonQualifiedCandidates() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue(MARK);
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	context.registerBeanDefinition(JUERGEN, person1);
	context.registerBeanDefinition(MARK, person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedFieldTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #5
Source File: DispatcherServlet.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Initialize the {@link FlashMapManager} used by this servlet instance.
 * <p>If no implementation is configured then we default to
 * {@code org.springframework.web.servlet.support.DefaultFlashMapManager}.
 */
private void initFlashMapManager(ApplicationContext context) {
	try {
		this.flashMapManager = context.getBean(FLASH_MAP_MANAGER_BEAN_NAME, FlashMapManager.class);
		if (logger.isTraceEnabled()) {
			logger.trace("Detected " + this.flashMapManager.getClass().getSimpleName());
		}
		else if (logger.isDebugEnabled()) {
			logger.debug("Detected " + this.flashMapManager);
		}
	}
	catch (NoSuchBeanDefinitionException ex) {
		// We need to use the default.
		this.flashMapManager = getDefaultStrategy(context, FlashMapManager.class);
		if (logger.isTraceEnabled()) {
			logger.trace("No FlashMapManager '" + FLASH_MAP_MANAGER_BEAN_NAME +
					"': using default [" + this.flashMapManager.getClass().getSimpleName() + "]");
		}
	}
}
 
Example #6
Source File: QualifierAnnotationAutowireContextTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void autowiredMethodParameterWithSingleNonQualifiedCandidate() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs = new ConstructorArgumentValues();
	cavs.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person = new RootBeanDefinition(Person.class, cavs, null);
	context.registerBeanDefinition(JUERGEN, person);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedMethodParameterTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #7
Source File: LazyAutowiredAnnotationBeanPostProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testLazyResourceInjectionWithNonExistingTarget() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
	AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);
	RootBeanDefinition bd = new RootBeanDefinition(FieldResourceInjectionBean.class);
	bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	bf.registerBeanDefinition("annotatedBean", bd);

	FieldResourceInjectionBean bean = (FieldResourceInjectionBean) bf.getBean("annotatedBean");
	assertNotNull(bean.getTestBean());
	try {
		bean.getTestBean().getName();
		fail("Should have thrown NoSuchBeanDefinitionException");
	}
	catch (NoSuchBeanDefinitionException ex) {
		// expected
	}
}
 
Example #8
Source File: LazyAutowiredAnnotationBeanPostProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testLazyOptionalResourceInjectionWithNonExistingTarget() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
	AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);
	RootBeanDefinition bd = new RootBeanDefinition(OptionalFieldResourceInjectionBean.class);
	bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	bf.registerBeanDefinition("annotatedBean", bd);

	OptionalFieldResourceInjectionBean bean = (OptionalFieldResourceInjectionBean) bf.getBean("annotatedBean");
	assertNotNull(bean.getTestBean());
	assertNotNull(bean.getTestBeans());
	assertTrue(bean.getTestBeans().isEmpty());
	try {
		bean.getTestBean().getName();
		fail("Should have thrown NoSuchBeanDefinitionException");
	}
	catch (NoSuchBeanDefinitionException ex) {
		// expected
	}
}
 
Example #9
Source File: BeanFactoryAnnotationUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a
 * qualifier (e.g. via {@code <qualifier>} or {@code @Qualifier}) matching the given
 * qualifier, or having a bean name matching the given qualifier.
 * @param beanFactory the factory to get the target bean from (also searching ancestors)
 * @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 NoUniqueBeanDefinitionException if multiple matching beans of type {@code T} found
 * @throws NoSuchBeanDefinitionException if no matching bean of type {@code T} found
 * @throws BeansException if the bean could not be created
 * @see BeanFactoryUtils#beanOfTypeIncludingAncestors(ListableBeanFactory, Class)
 */
public static <T> T qualifiedBeanOfType(BeanFactory beanFactory, Class<T> beanType, String qualifier)
		throws BeansException {

	Assert.notNull(beanFactory, "BeanFactory must not be null");

	if (beanFactory instanceof ListableBeanFactory) {
		// Full qualifier matching supported.
		return qualifiedBeanOfType((ListableBeanFactory) 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.)");
	}
}
 
Example #10
Source File: ClassPathBeanDefinitionScannerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAutowireCandidatePatternDoesNotMatch() {
	GenericApplicationContext context = new GenericApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(true);
	scanner.setBeanNameGenerator(new TestBeanNameGenerator());
	scanner.setAutowireCandidatePatterns("*NoSuchDao");
	scanner.scan(BASE_PACKAGE);

	try {
		context.refresh();
		context.getBean("fooService");
		fail("BeanCreationException expected; fooDao should not have been an autowire-candidate");
	}
	catch (BeanCreationException expected) {
		assertTrue(expected.getMostSpecificCause() instanceof NoSuchBeanDefinitionException);
	}
}
 
Example #11
Source File: QualifierAnnotationAutowireContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void autowiredFieldWithMultipleNonQualifiedCandidates() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue(MARK);
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	context.registerBeanDefinition(JUERGEN, person1);
	context.registerBeanDefinition(MARK, person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedFieldTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #12
Source File: DefaultListableBeanFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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
@Nullable
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()) {
				Class<?> beanClass = abd.getBeanClass();
				if (beanClass != beanType) {
					ann = AnnotationUtils.findAnnotation(beanClass, annotationType);
				}
			}
		}
	}
	return ann;
}
 
Example #13
Source File: QualifierAnnotationAutowireContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void autowiredFieldDoesNotResolveCandidateWithDefaultValueAndConflictingValueOnBeanDefinition() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	// qualifier added, and non-default value specified
	person1.addQualifier(new AutowireCandidateQualifier(TestQualifierWithDefaultValue.class, "not the default"));
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue(MARK);
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	context.registerBeanDefinition(JUERGEN, person1);
	context.registerBeanDefinition(MARK, person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedFieldWithDefaultValueTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #14
Source File: CommonAnnotationBeanPostProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected Object getResourceToInject(Object target, @Nullable 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 (requestingBeanName != null && 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);
}
 
Example #15
Source File: SpringBootstrap.java    From sbp with Apache License 2.0 6 votes vote down vote up
protected void registerBeanFromMainContext(AbstractApplicationContext applicationContext,
                                           Class<?> beanClass) {
    try {
        Map<String, ?> beans = mainApplicationContext.getBeansOfType(beanClass);
        for (String beanName : beans.keySet()) {
            if (applicationContext.containsBean(beanName)) continue;
            Object bean = beans.get(beanName);
            applicationContext.getBeanFactory().registerSingleton(beanName, bean);
            importedBeanNames.add(beanName);
            applicationContext.getBeanFactory().autowireBean(bean);
        }
        log.info("Bean {} is registered from main ApplicationContext", beanClass.getSimpleName());
    } catch (NoSuchBeanDefinitionException ex) {
        log.warn("Bean {} is not found in main ApplicationContext", beanClass.getSimpleName());
    }
}
 
Example #16
Source File: DispatcherServlet.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Initialize the LocaleResolver used by this class.
 * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
 * we default to AcceptHeaderLocaleResolver.
 */
private void initLocaleResolver(ApplicationContext context) {
	try {
		this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class);
		if (logger.isTraceEnabled()) {
			logger.trace("Detected " + this.localeResolver);
		}
		else if (logger.isDebugEnabled()) {
			logger.debug("Detected " + this.localeResolver.getClass().getSimpleName());
		}
	}
	catch (NoSuchBeanDefinitionException ex) {
		// We need to use the default.
		this.localeResolver = getDefaultStrategy(context, LocaleResolver.class);
		if (logger.isTraceEnabled()) {
			logger.trace("No LocaleResolver '" + LOCALE_RESOLVER_BEAN_NAME +
					"': using default [" + this.localeResolver.getClass().getSimpleName() + "]");
		}
	}
}
 
Example #17
Source File: DispatcherServlet.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Initialize the MultipartResolver used by this class.
 * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
 * no multipart handling is provided.
 */
private void initMultipartResolver(ApplicationContext context) {
	try {
		this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
		if (logger.isTraceEnabled()) {
			logger.trace("Detected " + this.multipartResolver);
		}
		else if (logger.isDebugEnabled()) {
			logger.debug("Detected " + this.multipartResolver.getClass().getSimpleName());
		}
	}
	catch (NoSuchBeanDefinitionException ex) {
		// Default is no multipart resolver.
		this.multipartResolver = null;
		if (logger.isTraceEnabled()) {
			logger.trace("No MultipartResolver '" + MULTIPART_RESOLVER_BEAN_NAME + "' declared");
		}
	}
}
 
Example #18
Source File: StaticListableBeanFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
	String beanName = BeanFactoryUtils.transformedBeanName(name);

	Object bean = this.beans.get(beanName);
	if (bean == null) {
		throw new NoSuchBeanDefinitionException(beanName,
				"Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]");
	}

	if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
		// If it's a FactoryBean, we want to look at what it creates, not the factory class.
		return ((FactoryBean<?>) bean).getObjectType();
	}
	return bean.getClass();
}
 
Example #19
Source File: DispatcherServlet.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Initialize the MultipartResolver used by this class.
 * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
 * no multipart handling is provided.
 */
private void initMultipartResolver(ApplicationContext context) {
	try {
		this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
		if (logger.isTraceEnabled()) {
			logger.trace("Detected " + this.multipartResolver);
		}
		else if (logger.isDebugEnabled()) {
			logger.debug("Detected " + this.multipartResolver.getClass().getSimpleName());
		}
	}
	catch (NoSuchBeanDefinitionException ex) {
		// Default is no multipart resolver.
		this.multipartResolver = null;
		if (logger.isTraceEnabled()) {
			logger.trace("No MultipartResolver '" + MULTIPART_RESOLVER_BEAN_NAME + "' declared");
		}
	}
}
 
Example #20
Source File: QualifierAnnotationAutowireContextTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void autowiredFieldWithMultipleNonQualifiedCandidates() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue(MARK);
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	context.registerBeanDefinition(JUERGEN, person1);
	context.registerBeanDefinition(MARK, person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedFieldTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #21
Source File: DefaultListableBeanFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Determine whether the specified bean definition qualifies as an autowire candidate,
 * to be injected into other beans which declare a dependency of matching type.
 * @param beanName the name of the bean definition to check
 * @param descriptor the descriptor of the dependency to resolve
 * @param resolver the AutowireCandidateResolver to use for the actual resolution algorithm
 * @return whether the bean should be considered as autowire candidate
 */
protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver)
		throws NoSuchBeanDefinitionException {

	String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName);
	if (containsBeanDefinition(beanDefinitionName)) {
		return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver);
	}
	else if (containsSingleton(beanName)) {
		return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver);
	}

	BeanFactory parent = getParentBeanFactory();
	if (parent instanceof DefaultListableBeanFactory) {
		// No bean definition found in this factory -> delegate to parent.
		return ((DefaultListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor, resolver);
	}
	else if (parent instanceof ConfigurableListableBeanFactory) {
		// If no DefaultListableBeanFactory, can't pass the resolver along.
		return ((ConfigurableListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor);
	}
	else {
		return true;
	}
}
 
Example #22
Source File: AbstractBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void aliasing() {
	BeanFactory bf = getBeanFactory();
	if (!(bf instanceof ConfigurableBeanFactory)) {
		return;
	}
	ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf;

	String alias = "rods alias";
	try {
		cbf.getBean(alias);
		fail("Shouldn't permit factory get on normal bean");
	}
	catch (NoSuchBeanDefinitionException ex) {
		// Ok
		assertTrue(alias.equals(ex.getBeanName()));
	}

	// Create alias
	cbf.registerAlias("rod", alias);
	Object rod = getBeanFactory().getBean("rod");
	Object aliasRod = getBeanFactory().getBean(alias);
	assertTrue(rod == aliasRod);
}
 
Example #23
Source File: XmlBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Check that a prototype can't inherit from a bogus parent.
 * If a singleton does this the factory will fail to load.
 */
@Test
public void testBogusParentageFromParentFactory() {
	DefaultListableBeanFactory parent = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT);
	DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
	new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT);
	try {
		child.getBean("bogusParent", TestBean.class);
		fail();
	}
	catch (BeanDefinitionStoreException ex) {
		// check exception message contains the name
		assertTrue(ex.getMessage().contains("bogusParent"));
		assertTrue(ex.getCause() instanceof NoSuchBeanDefinitionException);
	}
}
 
Example #24
Source File: InjectAnnotationAutowireContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAutowiredMethodParameterWithSingleNonQualifiedCandidate() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs = new ConstructorArgumentValues();
	cavs.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person = new RootBeanDefinition(Person.class, cavs, null);
	context.registerBeanDefinition(JUERGEN, person);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedMethodParameterTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #25
Source File: BeanFactoryAnnotationUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier
 * (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier).
 * @param bf the factory to get the target bean from
 * @param beanType the type of bean to retrieve
 * @param qualifier the qualifier for selecting between multiple bean matches
 * @return the matching bean of type {@code T} (never {@code null})
 */
private static <T> T qualifiedBeanOfType(ListableBeanFactory bf, Class<T> beanType, String qualifier) {
	String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
	String matchingBean = null;
	for (String beanName : candidateBeans) {
		if (isQualifierMatch(qualifier::equals, beanName, bf)) {
			if (matchingBean != null) {
				throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName);
			}
			matchingBean = beanName;
		}
	}
	if (matchingBean != null) {
		return bf.getBean(matchingBean, beanType);
	}
	else if (bf.containsBean(qualifier)) {
		// Fallback: target bean at least found by bean name - probably a manually registered singleton.
		return bf.getBean(qualifier, beanType);
	}
	else {
		throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
				" bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!");
	}
}
 
Example #26
Source File: TransactionInterceptorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void determineTransactionManagerWithQualifierUnknown() {
	BeanFactory beanFactory = mock(BeanFactory.class);
	TransactionInterceptor ti = simpleTransactionInterceptor(beanFactory);
	DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
	attribute.setQualifier("fooTransactionManager");

	thrown.expect(NoSuchBeanDefinitionException.class);
	thrown.expectMessage("'fooTransactionManager'");
	ti.determineTransactionManager(attribute);
}
 
Example #27
Source File: AbstractBeanFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
	String beanName = transformedBeanName(name);
	Object beanInstance = getSingleton(beanName, false);
	if (beanInstance != null) {
		return (beanInstance instanceof FactoryBean);
	}
	// 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));
}
 
Example #28
Source File: InjectAnnotationAutowireContextTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testAutowiredFieldDoesNotResolveWithMultipleQualifierValuesAndConflictingDefaultValue() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue(JUERGEN);
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	AutowireCandidateQualifier qualifier = new AutowireCandidateQualifier(TestQualifierWithMultipleAttributes.class);
	qualifier.setAttribute("number", 456);
	person1.addQualifier(qualifier);
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue(MARK);
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	AutowireCandidateQualifier qualifier2 = new AutowireCandidateQualifier(TestQualifierWithMultipleAttributes.class);
	qualifier2.setAttribute("number", 123);
	qualifier2.setAttribute("value", "not the default");
	person2.addQualifier(qualifier2);
	context.registerBeanDefinition(JUERGEN, person1);
	context.registerBeanDefinition(MARK, person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #29
Source File: AbstractBeanFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
	String beanName = transformedBeanName(name);

	BeanFactory parentBeanFactory = getParentBeanFactory();
	if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
		// No bean definition found in this factory -> delegate to parent.
		return parentBeanFactory.isPrototype(originalBeanName(name));
	}

	RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
	if (mbd.isPrototype()) {
		// In case of FactoryBean, return singleton status of created object if not a dereference.
		return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd));
	}

	// Singleton or scoped - not a prototype.
	// However, FactoryBean may still produce a prototype object...
	if (BeanFactoryUtils.isFactoryDereference(name)) {
		return false;
	}
	if (isFactoryBean(beanName, mbd)) {
		final FactoryBean<?> fb = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
		if (System.getSecurityManager() != null) {
			return AccessController.doPrivileged((PrivilegedAction<Boolean>) () ->
					((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) || !fb.isSingleton()),
					getAccessControlContext());
		}
		else {
			return ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) ||
					!fb.isSingleton());
		}
	}
	else {
		return false;
	}
}
 
Example #30
Source File: RedirectServlet.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private PushRedirectTokenService getPushRedirectTokenService() {
	if (pushRedirectTokenServiceCache == null) {
		try {
			pushRedirectTokenServiceCache = Optional.of(getApplicationContext().getBean("PushRedirectTokenService", PushRedirectTokenService.class));
		} catch (NoSuchBeanDefinitionException e) {
			pushRedirectTokenServiceCache = Optional.empty();
		}
	}
	
	if (pushRedirectTokenServiceCache.isPresent()) {
		return pushRedirectTokenServiceCache.get();
	} else {
		return null;
	}
}