org.springframework.beans.factory.BeanCurrentlyInCreationException Java Examples

The following examples show how to use org.springframework.beans.factory.BeanCurrentlyInCreationException. 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: RequestScopeTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void circleLeadsToException() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	RequestAttributes requestAttributes = new ServletRequestAttributes(request);
	RequestContextHolder.setRequestAttributes(requestAttributes);

	try {
		String name = "requestScopedObjectCircle1";
		assertNull(request.getAttribute(name));

		this.beanFactory.getBean(name);
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
	}
}
 
Example #2
Source File: AbstractBeanFactory.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Determine the bean type for the given FactoryBean definition, as far as possible.
 * Only called if there is no singleton instance registered for the target bean already.
 * <p>The default implementation creates the FactoryBean via {@code getBean}
 * to call its {@code getObjectType} method. Subclasses are encouraged to optimize
 * this, typically by just instantiating the FactoryBean but not populating it yet,
 * trying whether its {@code getObjectType} method already returns a type.
 * If no type found, a full FactoryBean creation as performed by this implementation
 * should be used as fallback.
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @return the type for the bean if determinable, or {@code null} else
 * @see org.springframework.beans.factory.FactoryBean#getObjectType()
 * @see #getBean(String)
 */
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
	if (!mbd.isSingleton()) {
		return null;
	}
	try {
		FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
		return getTypeForFactoryBean(factoryBean);
	}
	catch (BeanCreationException ex) {
		if (ex instanceof BeanCurrentlyInCreationException) {
			if (logger.isDebugEnabled()) {
				logger.debug("Bean currently in creation on FactoryBean type check: " + ex);
			}
		}
		else {
			if (logger.isWarnEnabled()) {
				logger.warn("Bean creation exception on FactoryBean type check: " + ex);
			}
		}
		onSuppressedException(ex);
		return null;
	}
}
 
Example #3
Source File: RequestScopeTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void circleLeadsToException() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	RequestAttributes requestAttributes = new ServletRequestAttributes(request);
	RequestContextHolder.setRequestAttributes(requestAttributes);

	try {
		String name = "requestScopedObjectCircle1";
		assertNull(request.getAttribute(name));

		this.beanFactory.getBean(name);
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
	}
}
 
Example #4
Source File: RequestScopeTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void circleLeadsToException() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	RequestAttributes requestAttributes = new ServletRequestAttributes(request);
	RequestContextHolder.setRequestAttributes(requestAttributes);

	try {
		String name = "requestScopedObjectCircle1";
		assertNull(request.getAttribute(name));

		this.beanFactory.getBean(name);
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
	}
}
 
Example #5
Source File: DefaultListableBeanFactory.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
		throws BeansException {

	String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
	Map<String, T> result = new LinkedHashMap<String, T>(beanNames.length);
	for (String beanName : beanNames) {
		try {
			result.put(beanName, getBean(beanName, type));
		}
		catch (BeanCreationException ex) {
			Throwable rootCause = ex.getMostSpecificCause();
			if (rootCause instanceof BeanCurrentlyInCreationException) {
				BeanCreationException bce = (BeanCreationException) rootCause;
				if (isCurrentlyInCreation(bce.getBeanName())) {
					if (this.logger.isDebugEnabled()) {
						this.logger.debug("Ignoring match to currently created bean '" + beanName + "': " +
								ex.getMessage());
					}
					onSuppressedException(ex);
					// Ignore: indicates a circular reference when autowiring constructors.
					// We want to find matches other than the currently created bean itself.
					continue;
				}
			}
			throw ex;
		}
	}
	return result;
}
 
Example #6
Source File: DefaultSingletonBeanRegistry.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Callback before singleton creation.
 * <p>The default implementation register the singleton as currently in creation.
 * @param beanName the name of the singleton about to be created
 * @see #isSingletonCurrentlyInCreation
 */
protected void beforeSingletonCreation(String beanName) {
	if (!this.inCreationCheckExclusions.contains(beanName) &&
			!this.singletonsCurrentlyInCreation.add(beanName)) {
		throw new BeanCurrentlyInCreationException(beanName);
	}
}
 
Example #7
Source File: AbstractBeanFactory.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the given PropertyEditorRegistry with the custom editors
 * that have been registered with this BeanFactory.
 * <p>To be called for BeanWrappers that will create and populate bean
 * instances, and for SimpleTypeConverter used for constructor argument
 * and factory method type conversion.
 * @param registry the PropertyEditorRegistry to initialize
 */
protected void registerCustomEditors(PropertyEditorRegistry registry) {
	PropertyEditorRegistrySupport registrySupport =
			(registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
	if (registrySupport != null) {
		registrySupport.useConfigValueEditors();
	}
	if (!this.propertyEditorRegistrars.isEmpty()) {
		for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
			try {
				registrar.registerCustomEditors(registry);
			}
			catch (BeanCreationException ex) {
				Throwable rootCause = ex.getMostSpecificCause();
				if (rootCause instanceof BeanCurrentlyInCreationException) {
					BeanCreationException bce = (BeanCreationException) rootCause;
					if (isCurrentlyInCreation(bce.getBeanName())) {
						if (logger.isDebugEnabled()) {
							logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
									"] failed because it tried to obtain currently created bean '" +
									ex.getBeanName() + "': " + ex.getMessage());
						}
						onSuppressedException(ex);
						continue;
					}
				}
				throw ex;
			}
		}
	}
	if (!this.customEditors.isEmpty()) {
		for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) {
			Class<?> requiredType = entry.getKey();
			Class<? extends PropertyEditor> editorClass = entry.getValue();
			registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass));
		}
	}
}
 
Example #8
Source File: DefaultListableBeanFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
		throws BeansException {

	String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
	Map<String, T> result = new LinkedHashMap<String, T>(beanNames.length);
	for (String beanName : beanNames) {
		try {
			result.put(beanName, getBean(beanName, type));
		}
		catch (BeanCreationException ex) {
			Throwable rootCause = ex.getMostSpecificCause();
			if (rootCause instanceof BeanCurrentlyInCreationException) {
				BeanCreationException bce = (BeanCreationException) rootCause;
				if (isCurrentlyInCreation(bce.getBeanName())) {
					if (this.logger.isDebugEnabled()) {
						this.logger.debug("Ignoring match to currently created bean '" + beanName + "': " +
								ex.getMessage());
					}
					onSuppressedException(ex);
					// Ignore: indicates a circular reference when autowiring constructors.
					// We want to find matches other than the currently created bean itself.
					continue;
				}
			}
			throw ex;
		}
	}
	return result;
}
 
Example #9
Source File: XmlBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testCircularReferencesWithNotAllowed() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	xbf.setAllowCircularReferences(false);
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
	reader.loadBeanDefinitions(REFTYPES_CONTEXT);
	try {
		xbf.getBean("jenny");
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
	}
}
 
Example #10
Source File: AbstractBeanFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determine the bean type for the given FactoryBean definition, as far as possible.
 * Only called if there is no singleton instance registered for the target bean already.
 * <p>The default implementation creates the FactoryBean via {@code getBean}
 * to call its {@code getObjectType} method. Subclasses are encouraged to optimize
 * this, typically by just instantiating the FactoryBean but not populating it yet,
 * trying whether its {@code getObjectType} method already returns a type.
 * If no type found, a full FactoryBean creation as performed by this implementation
 * should be used as fallback.
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @return the type for the bean if determinable, or {@code null} else
 * @see org.springframework.beans.factory.FactoryBean#getObjectType()
 * @see #getBean(String)
 */
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
	if (!mbd.isSingleton()) {
		return null;
	}
	try {
		FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
		return getTypeForFactoryBean(factoryBean);
	}
	catch (BeanCreationException ex) {
		if (ex instanceof BeanCurrentlyInCreationException) {
			if (logger.isDebugEnabled()) {
				logger.debug("Bean currently in creation on FactoryBean type check: " + ex);
			}
		}
		else if (mbd.isLazyInit()) {
			if (logger.isDebugEnabled()) {
				logger.debug("Bean creation exception on lazy FactoryBean type check: " + ex);
			}
		}
		else {
			if (logger.isWarnEnabled()) {
				logger.warn("Bean creation exception on non-lazy FactoryBean type check: " + ex);
			}
		}
		onSuppressedException(ex);
		return null;
	}
}
 
Example #11
Source File: AbstractBeanFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initialize the given PropertyEditorRegistry with the custom editors
 * that have been registered with this BeanFactory.
 * <p>To be called for BeanWrappers that will create and populate bean
 * instances, and for SimpleTypeConverter used for constructor argument
 * and factory method type conversion.
 * @param registry the PropertyEditorRegistry to initialize
 */
protected void registerCustomEditors(PropertyEditorRegistry registry) {
	PropertyEditorRegistrySupport registrySupport =
			(registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
	if (registrySupport != null) {
		registrySupport.useConfigValueEditors();
	}
	if (!this.propertyEditorRegistrars.isEmpty()) {
		for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
			try {
				registrar.registerCustomEditors(registry);
			}
			catch (BeanCreationException ex) {
				Throwable rootCause = ex.getMostSpecificCause();
				if (rootCause instanceof BeanCurrentlyInCreationException) {
					BeanCreationException bce = (BeanCreationException) rootCause;
					if (isCurrentlyInCreation(bce.getBeanName())) {
						if (logger.isDebugEnabled()) {
							logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
									"] failed because it tried to obtain currently created bean '" +
									ex.getBeanName() + "': " + ex.getMessage());
						}
						onSuppressedException(ex);
						continue;
					}
				}
				throw ex;
			}
		}
	}
	if (!this.customEditors.isEmpty()) {
		for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) {
			Class<?> requiredType = entry.getKey();
			Class<? extends PropertyEditor> editorClass = entry.getValue();
			registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass));
		}
	}
}
 
Example #12
Source File: XmlBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testCircularReferencesWithWrapping() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
	reader.loadBeanDefinitions(REFTYPES_CONTEXT);
	xbf.addBeanPostProcessor(new WrappingPostProcessor());
	try {
		xbf.getBean("jenny");
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
	}
}
 
Example #13
Source File: DefaultListableBeanFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
		throws BeansException {

	String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
	Map<String, T> result = new LinkedHashMap<>(beanNames.length);
	for (String beanName : beanNames) {
		try {
			Object beanInstance = getBean(beanName);
			if (!(beanInstance instanceof NullBean)) {
				result.put(beanName, (T) beanInstance);
			}
		}
		catch (BeanCreationException ex) {
			Throwable rootCause = ex.getMostSpecificCause();
			if (rootCause instanceof BeanCurrentlyInCreationException) {
				BeanCreationException bce = (BeanCreationException) rootCause;
				String exBeanName = bce.getBeanName();
				if (exBeanName != null && isCurrentlyInCreation(exBeanName)) {
					if (logger.isTraceEnabled()) {
						logger.trace("Ignoring match to currently created bean '" + exBeanName + "': " +
								ex.getMessage());
					}
					onSuppressedException(ex);
					// Ignore: indicates a circular reference when autowiring constructors.
					// We want to find matches other than the currently created bean itself.
					continue;
				}
			}
			throw ex;
		}
	}
	return result;
}
 
Example #14
Source File: AbstractBeanFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Determine the bean type for the given FactoryBean definition, as far as possible.
 * Only called if there is no singleton instance registered for the target bean already.
 * <p>The default implementation creates the FactoryBean via {@code getBean}
 * to call its {@code getObjectType} method. Subclasses are encouraged to optimize
 * this, typically by just instantiating the FactoryBean but not populating it yet,
 * trying whether its {@code getObjectType} method already returns a type.
 * If no type found, a full FactoryBean creation as performed by this implementation
 * should be used as fallback.
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @return the type for the bean if determinable, or {@code null} otherwise
 * @see org.springframework.beans.factory.FactoryBean#getObjectType()
 * @see #getBean(String)
 */
@Nullable
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
	if (!mbd.isSingleton()) {
		return null;
	}
	try {
		FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
		return getTypeForFactoryBean(factoryBean);
	}
	catch (BeanCreationException ex) {
		if (ex.contains(BeanCurrentlyInCreationException.class)) {
			if (logger.isTraceEnabled()) {
				logger.trace("Bean currently in creation on FactoryBean type check: " + ex);
			}
		}
		else if (mbd.isLazyInit()) {
			if (logger.isTraceEnabled()) {
				logger.trace("Bean creation exception on lazy FactoryBean type check: " + ex);
			}
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("Bean creation exception on non-lazy FactoryBean type check: " + ex);
			}
		}
		onSuppressedException(ex);
		return null;
	}
}
 
Example #15
Source File: AbstractBeanFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Initialize the given PropertyEditorRegistry with the custom editors
 * that have been registered with this BeanFactory.
 * <p>To be called for BeanWrappers that will create and populate bean
 * instances, and for SimpleTypeConverter used for constructor argument
 * and factory method type conversion.
 * @param registry the PropertyEditorRegistry to initialize
 */
protected void registerCustomEditors(PropertyEditorRegistry registry) {
	PropertyEditorRegistrySupport registrySupport =
			(registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
	if (registrySupport != null) {
		registrySupport.useConfigValueEditors();
	}
	if (!this.propertyEditorRegistrars.isEmpty()) {
		for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
			try {
				registrar.registerCustomEditors(registry);
			}
			catch (BeanCreationException ex) {
				Throwable rootCause = ex.getMostSpecificCause();
				if (rootCause instanceof BeanCurrentlyInCreationException) {
					BeanCreationException bce = (BeanCreationException) rootCause;
					String bceBeanName = bce.getBeanName();
					if (bceBeanName != null && isCurrentlyInCreation(bceBeanName)) {
						if (logger.isDebugEnabled()) {
							logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
									"] failed because it tried to obtain currently created bean '" +
									ex.getBeanName() + "': " + ex.getMessage());
						}
						onSuppressedException(ex);
						continue;
					}
				}
				throw ex;
			}
		}
	}
	if (!this.customEditors.isEmpty()) {
		this.customEditors.forEach((requiredType, editorClass) ->
				registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)));
	}
}
 
Example #16
Source File: XmlBeanFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testCircularReferencesWithWrapping() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
	reader.loadBeanDefinitions(REFTYPES_CONTEXT);
	xbf.addBeanPostProcessor(new WrappingPostProcessor());
	try {
		xbf.getBean("jenny");
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
	}
}
 
Example #17
Source File: XmlBeanFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testCircularReferencesWithNotAllowed() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	xbf.setAllowCircularReferences(false);
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
	reader.loadBeanDefinitions(REFTYPES_CONTEXT);
	try {
		xbf.getBean("jenny");
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
	}
}
 
Example #18
Source File: AbstractBeanFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the given PropertyEditorRegistry with the custom editors
 * that have been registered with this BeanFactory.
 * <p>To be called for BeanWrappers that will create and populate bean
 * instances, and for SimpleTypeConverter used for constructor argument
 * and factory method type conversion.
 * @param registry the PropertyEditorRegistry to initialize
 */
protected void registerCustomEditors(PropertyEditorRegistry registry) {
	PropertyEditorRegistrySupport registrySupport =
			(registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
	if (registrySupport != null) {
		registrySupport.useConfigValueEditors();
	}
	if (!this.propertyEditorRegistrars.isEmpty()) {
		for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
			try {
				registrar.registerCustomEditors(registry);
			}
			catch (BeanCreationException ex) {
				Throwable rootCause = ex.getMostSpecificCause();
				if (rootCause instanceof BeanCurrentlyInCreationException) {
					BeanCreationException bce = (BeanCreationException) rootCause;
					if (isCurrentlyInCreation(bce.getBeanName())) {
						if (logger.isDebugEnabled()) {
							logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
									"] failed because it tried to obtain currently created bean '" +
									ex.getBeanName() + "': " + ex.getMessage());
						}
						onSuppressedException(ex);
						continue;
					}
				}
				throw ex;
			}
		}
	}
	if (!this.customEditors.isEmpty()) {
		for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) {
			Class<?> requiredType = entry.getKey();
			Class<? extends PropertyEditor> editorClass = entry.getValue();
			registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass));
		}
	}
}
 
Example #19
Source File: DefaultListableBeanFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
		throws BeansException {

	String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
	Map<String, T> result = new LinkedHashMap<>(beanNames.length);
	for (String beanName : beanNames) {
		try {
			Object beanInstance = getBean(beanName);
			if (!(beanInstance instanceof NullBean)) {
				result.put(beanName, (T) beanInstance);
			}
		}
		catch (BeanCreationException ex) {
			Throwable rootCause = ex.getMostSpecificCause();
			if (rootCause instanceof BeanCurrentlyInCreationException) {
				BeanCreationException bce = (BeanCreationException) rootCause;
				String exBeanName = bce.getBeanName();
				if (exBeanName != null && isCurrentlyInCreation(exBeanName)) {
					if (logger.isTraceEnabled()) {
						logger.trace("Ignoring match to currently created bean '" + exBeanName + "': " +
								ex.getMessage());
					}
					onSuppressedException(ex);
					// Ignore: indicates a circular reference when autowiring constructors.
					// We want to find matches other than the currently created bean itself.
					continue;
				}
			}
			throw ex;
		}
	}
	return result;
}
 
Example #20
Source File: DefaultListableBeanFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
		throws BeansException {

	String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
	Map<String, T> result = new LinkedHashMap<String, T>(beanNames.length);
	for (String beanName : beanNames) {
		try {
			result.put(beanName, getBean(beanName, type));
		}
		catch (BeanCreationException ex) {
			Throwable rootCause = ex.getMostSpecificCause();
			if (rootCause instanceof BeanCurrentlyInCreationException) {
				BeanCreationException bce = (BeanCreationException) rootCause;
				if (isCurrentlyInCreation(bce.getBeanName())) {
					if (this.logger.isDebugEnabled()) {
						this.logger.debug("Ignoring match to currently created bean '" + beanName + "': " +
								ex.getMessage());
					}
					onSuppressedException(ex);
					// Ignore: indicates a circular reference when autowiring constructors.
					// We want to find matches other than the currently created bean itself.
					continue;
				}
			}
			throw ex;
		}
	}
	return result;
}
 
Example #21
Source File: AbstractBeanFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Determine the bean type for the given FactoryBean definition, as far as possible.
 * Only called if there is no singleton instance registered for the target bean already.
 * <p>The default implementation creates the FactoryBean via {@code getBean}
 * to call its {@code getObjectType} method. Subclasses are encouraged to optimize
 * this, typically by just instantiating the FactoryBean but not populating it yet,
 * trying whether its {@code getObjectType} method already returns a type.
 * If no type found, a full FactoryBean creation as performed by this implementation
 * should be used as fallback.
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @return the type for the bean if determinable, or {@code null} otherwise
 * @see org.springframework.beans.factory.FactoryBean#getObjectType()
 * @see #getBean(String)
 */
@Nullable
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
	if (!mbd.isSingleton()) {
		return null;
	}
	try {
		FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
		return getTypeForFactoryBean(factoryBean);
	}
	catch (BeanCreationException ex) {
		if (ex.contains(BeanCurrentlyInCreationException.class)) {
			if (logger.isTraceEnabled()) {
				logger.trace("Bean currently in creation on FactoryBean type check: " + ex);
			}
		}
		else if (mbd.isLazyInit()) {
			if (logger.isTraceEnabled()) {
				logger.trace("Bean creation exception on lazy FactoryBean type check: " + ex);
			}
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("Bean creation exception on non-lazy FactoryBean type check: " + ex);
			}
		}
		onSuppressedException(ex);
		return null;
	}
}
 
Example #22
Source File: AbstractBeanFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Initialize the given PropertyEditorRegistry with the custom editors
 * that have been registered with this BeanFactory.
 * <p>To be called for BeanWrappers that will create and populate bean
 * instances, and for SimpleTypeConverter used for constructor argument
 * and factory method type conversion.
 * @param registry the PropertyEditorRegistry to initialize
 */
protected void registerCustomEditors(PropertyEditorRegistry registry) {
	PropertyEditorRegistrySupport registrySupport =
			(registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
	if (registrySupport != null) {
		registrySupport.useConfigValueEditors();
	}
	if (!this.propertyEditorRegistrars.isEmpty()) {
		for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
			try {
				registrar.registerCustomEditors(registry);
			}
			catch (BeanCreationException ex) {
				Throwable rootCause = ex.getMostSpecificCause();
				if (rootCause instanceof BeanCurrentlyInCreationException) {
					BeanCreationException bce = (BeanCreationException) rootCause;
					String bceBeanName = bce.getBeanName();
					if (bceBeanName != null && isCurrentlyInCreation(bceBeanName)) {
						if (logger.isDebugEnabled()) {
							logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
									"] failed because it tried to obtain currently created bean '" +
									ex.getBeanName() + "': " + ex.getMessage());
						}
						onSuppressedException(ex);
						continue;
					}
				}
				throw ex;
			}
		}
	}
	if (!this.customEditors.isEmpty()) {
		this.customEditors.forEach((requiredType, editorClass) ->
				registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)));
	}
}
 
Example #23
Source File: XmlBeanFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testCircularReferencesWithWrapping() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
	reader.loadBeanDefinitions(REFTYPES_CONTEXT);
	xbf.addBeanPostProcessor(new WrappingPostProcessor());
	try {
		xbf.getBean("jenny");
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
	}
}
 
Example #24
Source File: XmlBeanFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testCircularReferencesWithNotAllowed() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	xbf.setAllowCircularReferences(false);
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
	reader.loadBeanDefinitions(REFTYPES_CONTEXT);
	try {
		xbf.getBean("jenny");
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
	}
}
 
Example #25
Source File: DefaultListableBeanFactory.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
   public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
		throws BeansException {

	String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
	Map<String, T> result = new LinkedHashMap<String, T>(beanNames.length);
	for (String beanName : beanNames) {
		try {
			result.put(beanName, getBean(beanName, type));
		}
		catch (BeanCreationException ex) {
			Throwable rootCause = ex.getMostSpecificCause();
			if (rootCause instanceof BeanCurrentlyInCreationException) {
				BeanCreationException bce = (BeanCreationException) rootCause;
				if (isCurrentlyInCreation(bce.getBeanName())) {
					if (this.logger.isDebugEnabled()) {
						this.logger.debug("Ignoring match to currently created bean '" + beanName + "': " +
								ex.getMessage());
					}
					onSuppressedException(ex);
					// Ignore: indicates a circular reference when autowiring constructors.
					// We want to find matches other than the currently created bean itself.
					continue;
				}
			}
			throw ex;
		}
	}
	return result;
}
 
Example #26
Source File: ScriptFactoryPostProcessor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public Class<?> predictBeanType(Class<?> beanClass, String beanName) {
	// We only apply special treatment to ScriptFactory implementations here.
	if (!ScriptFactory.class.isAssignableFrom(beanClass)) {
		return null;
	}

	BeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);

	try {
		String scriptFactoryBeanName = SCRIPT_FACTORY_NAME_PREFIX + beanName;
		String scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName;
		prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName);

		ScriptFactory scriptFactory = this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
		ScriptSource scriptSource = getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
		Class<?>[] interfaces = scriptFactory.getScriptInterfaces();

		Class<?> scriptedType = scriptFactory.getScriptedObjectType(scriptSource);
		if (scriptedType != null) {
			return scriptedType;
		}
		else if (!ObjectUtils.isEmpty(interfaces)) {
			return (interfaces.length == 1 ? interfaces[0] : createCompositeInterface(interfaces));
		}
		else {
			if (bd.isSingleton()) {
				Object bean = this.scriptBeanFactory.getBean(scriptedObjectBeanName);
				if (bean != null) {
					return bean.getClass();
				}
			}
		}
	}
	catch (Exception ex) {
		if (ex instanceof BeanCreationException
				&& ((BeanCreationException) ex).getMostSpecificCause() instanceof BeanCurrentlyInCreationException) {
			if (logger.isTraceEnabled()) {
				logger.trace("Could not determine scripted object type for bean '" + beanName + "': "
						+ ex.getMessage());
			}
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("Could not determine scripted object type for bean '" + beanName + "'", ex);
			}
		}
	}

	return null;
}
 
Example #27
Source File: ScriptFactoryPostProcessor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Class<?> predictBeanType(Class<?> beanClass, String beanName) {
	// We only apply special treatment to ScriptFactory implementations here.
	if (!ScriptFactory.class.isAssignableFrom(beanClass)) {
		return null;
	}

	BeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);

	try {
		String scriptFactoryBeanName = SCRIPT_FACTORY_NAME_PREFIX + beanName;
		String scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName;
		prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName);

		ScriptFactory scriptFactory = this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
		ScriptSource scriptSource = getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
		Class<?>[] interfaces = scriptFactory.getScriptInterfaces();

		Class<?> scriptedType = scriptFactory.getScriptedObjectType(scriptSource);
		if (scriptedType != null) {
			return scriptedType;
		}
		else if (!ObjectUtils.isEmpty(interfaces)) {
			return (interfaces.length == 1 ? interfaces[0] : createCompositeInterface(interfaces));
		}
		else {
			if (bd.isSingleton()) {
				Object bean = this.scriptBeanFactory.getBean(scriptedObjectBeanName);
				if (bean != null) {
					return bean.getClass();
				}
			}
		}
	}
	catch (Exception ex) {
		if (ex instanceof BeanCreationException &&
				((BeanCreationException) ex).getMostSpecificCause() instanceof BeanCurrentlyInCreationException) {
			if (logger.isTraceEnabled()) {
				logger.trace("Could not determine scripted object type for bean '" + beanName + "': "
						+ ex.getMessage());
			}
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("Could not determine scripted object type for bean '" + beanName + "'", ex);
			}
		}
	}

	return null;
}
 
Example #28
Source File: BeanFactoryAdvisorRetrievalHelper.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Find all eligible Advisor beans in the current bean factory,
 * ignoring FactoryBeans and excluding beans that are currently in creation.
 * @return the list of {@link org.springframework.aop.Advisor} beans
 * @see #isEligibleBean
 */
public List<Advisor> findAdvisorBeans() {
	// Determine list of advisor bean names, if not cached already.
	String[] advisorNames = null;
	synchronized (this) {
		advisorNames = this.cachedAdvisorBeanNames;
		if (advisorNames == null) {
			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the auto-proxy creator apply to them!
			advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
					this.beanFactory, Advisor.class, true, false);
			this.cachedAdvisorBeanNames = advisorNames;
		}
	}
	if (advisorNames.length == 0) {
		return new LinkedList<Advisor>();
	}

	List<Advisor> advisors = new LinkedList<Advisor>();
	for (String name : advisorNames) {
		if (isEligibleBean(name)) {
			if (this.beanFactory.isCurrentlyInCreation(name)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Skipping currently created advisor '" + name + "'");
				}
			}
			else {
				try {
					advisors.add(this.beanFactory.getBean(name, Advisor.class));
				}
				catch (BeanCreationException ex) {
					Throwable rootCause = ex.getMostSpecificCause();
					if (rootCause instanceof BeanCurrentlyInCreationException) {
						BeanCreationException bce = (BeanCreationException) rootCause;
						if (this.beanFactory.isCurrentlyInCreation(bce.getBeanName())) {
							if (logger.isDebugEnabled()) {
								logger.debug("Skipping advisor '" + name +
										"' with dependency on currently created bean: " + ex.getMessage());
							}
							// Ignore: indicates a reference back to the bean we're trying to advise.
							// We want to find advisors other than the currently created bean itself.
							continue;
						}
					}
					throw ex;
				}
			}
		}
	}
	return advisors;
}
 
Example #29
Source File: BeanFactoryAdvisorRetrievalHelper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find all eligible Advisor beans in the current bean factory,
 * ignoring FactoryBeans and excluding beans that are currently in creation.
 * @return the list of {@link org.springframework.aop.Advisor} beans
 * @see #isEligibleBean
 */
public List<Advisor> findAdvisorBeans() {
	// Determine list of advisor bean names, if not cached already.
	String[] advisorNames = null;
	synchronized (this) {
		advisorNames = this.cachedAdvisorBeanNames;
		if (advisorNames == null) {
			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the auto-proxy creator apply to them!
			advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
					this.beanFactory, Advisor.class, true, false);
			this.cachedAdvisorBeanNames = advisorNames;
		}
	}
	if (advisorNames.length == 0) {
		return new LinkedList<Advisor>();
	}

	List<Advisor> advisors = new LinkedList<Advisor>();
	for (String name : advisorNames) {
		if (isEligibleBean(name)) {
			if (this.beanFactory.isCurrentlyInCreation(name)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Skipping currently created advisor '" + name + "'");
				}
			}
			else {
				try {
					advisors.add(this.beanFactory.getBean(name, Advisor.class));
				}
				catch (BeanCreationException ex) {
					Throwable rootCause = ex.getMostSpecificCause();
					if (rootCause instanceof BeanCurrentlyInCreationException) {
						BeanCreationException bce = (BeanCreationException) rootCause;
						if (this.beanFactory.isCurrentlyInCreation(bce.getBeanName())) {
							if (logger.isDebugEnabled()) {
								logger.debug("Skipping advisor '" + name +
										"' with dependency on currently created bean: " + ex.getMessage());
							}
							// Ignore: indicates a reference back to the bean we're trying to advise.
							// We want to find advisors other than the currently created bean itself.
							continue;
						}
					}
					throw ex;
				}
			}
		}
	}
	return advisors;
}
 
Example #30
Source File: BeanFactoryAdvisorRetrievalHelper.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Find all eligible Advisor beans in the current bean factory,
 * ignoring FactoryBeans and excluding beans that are currently in creation.
 *
 * 在当前bean工厂中查找所有符合条件的Advisor bean,忽略FactoryBeans并排除当前正在创建的bean
 *
 * @return the list of {@link org.springframework.aop.Advisor} beans
 * @see #isEligibleBean
 */
public List<Advisor> findAdvisorBeans() {
	// Determine list of advisor bean names, if not cached already.
	// 确定 advice bean名称列表(如果尚未缓存)
	String[] advisorNames = this.cachedAdvisorBeanNames;
	if (advisorNames == null) {
		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the auto-proxy creator apply to them!
		advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
				this.beanFactory, Advisor.class, true, false);
		this.cachedAdvisorBeanNames = advisorNames;
	}
	if (advisorNames.length == 0) {
		return new ArrayList<>();
	}

	List<Advisor> advisors = new ArrayList<>();
	for (String name : advisorNames) {
		if (isEligibleBean(name)) {
			if (this.beanFactory.isCurrentlyInCreation(name)) {
				if (logger.isTraceEnabled()) {
					logger.trace("Skipping currently created advisor '" + name + "'");
				}
			}
			else {
				try {
					advisors.add(this.beanFactory.getBean(name, Advisor.class));
				}
				catch (BeanCreationException ex) {
					Throwable rootCause = ex.getMostSpecificCause();
					if (rootCause instanceof BeanCurrentlyInCreationException) {
						BeanCreationException bce = (BeanCreationException) rootCause;
						String bceBeanName = bce.getBeanName();
						if (bceBeanName != null && this.beanFactory.isCurrentlyInCreation(bceBeanName)) {
							if (logger.isTraceEnabled()) {
								logger.trace("Skipping advisor '" + name +
										"' with dependency on currently created bean: " + ex.getMessage());
							}
							// Ignore: indicates a reference back to the bean we're trying to advise.
							// We want to find advisors other than the currently created bean itself.
							continue;
						}
					}
					throw ex;
				}
			}
		}
	}
	return advisors;
}