简介
ConfigurableBeanFactory定义BeanFactory的配置。ConfigurableBeanFactory中定义了太多太多的api,比如类加载器,类型转化,属性编辑器,BeanPostProcessor,作用域,bean定义,处理bean依赖关系,合并其他ConfigurableBeanFactory,bean如何销毁。ConfigurableBeanFactory同时继承了HierarchicalBeanFactory 和 SingletonBeanRegistry 这两个接口,即同时继承了分层和单例类注册的功能。
具体:
- 2个静态不可变常量分别代表单例类和原型类。
- 1个设置父工厂的方法,跟HierarchicalBeanFactory接口的getParentBeanFactory方法互补。
- 4个跟类加载器有关的方法:get/set工厂类加载器和get/set临时类加载器。
- 2个设置、是否缓存元数据的方法(热加载开关)。
- 11个处理Bean注册、加载等细节的方法,包括:Bean表达式分解器、转换服务、属性编辑登记员、属性编辑器、属性编辑注册器、类型转换器、嵌入式的字符串分解器
- 2个处理Bean后处理器的方法。
- 3个跟注册范围相关的方法。
- 1个返回安全访问上下文的方法、1个从其他的工厂复制相关的所有配置的方法。
- 2个跟Bean别名相关的方法、1个返回合并后的Bean定义的方法。
- 1个判断是否为工厂Bean的方法、2个跟当前Bean创建时机相关的方法。
- 3个跟Bean依赖相关的方法、3个销毁Bean相关的方法。
以下是 ConfigurableBeanFactory 接口中一些重要的方法:
- setAllowCircularReferences(boolean allowCircularReferences):
设置是否允许循环引用。如果设置为 false,Spring 容器在检测到循环引用时会抛出异常。 - isAllowCircularReferences():
返回当前是否允许循环引用。 - setDependencyCheck(String dependencyCheck):
设置依赖检查的类型。这可以是 NONE、OBJECTS、SIMPLE、ALL 或 PROTOTYPE 中的一个。这些值决定了 Spring 在创建 bean 时应如何检查其依赖。 - getDependencyCheck():返回当前的依赖检查类型。
- setAutowireMode(int autowireMode):
设置自动装配的模式。这可以是 AUTOWIRE_NO、AUTOWIRE_BY_NAME、AUTOWIRE_BY_TYPE 或 AUTOWIRE_CONSTRUCTOR 中的一个。 - getAutowireMode():
返回当前的自动装配模式。 - setAutowireCandidate(Class<?> beanClass, boolean autowireCandidate):
设置指定类的实例是否应作为自动装配的候选者。 - isAutowireCandidate(Class<?> beanClass):
返回指定类的实例是否是自动装配的候选者。 - setIgnoreDependencyInterface(boolean ignoreDependencyInterface):
设置是否应忽略依赖接口。如果设置为 true,则不会将接口作为依赖注入的候选者。 - isIgnoreDependencyInterface():
返回当前是否忽略依赖接口。 - registerSingleton(String beanName, Object singletonObject):
注册一个单例 bean。这通常用于在 bean 工厂中手动添加或覆盖 bean。 - removeSingleton(String beanName):
从 bean 工厂中移除一个单例 bean。 - registerResolvableDependency(Class<?> dependencyType, Object key, Object value):
注册一个可解析的依赖,这样当 bean 需要该依赖时,容器可以使用这个注册的值。 - removeResolvableDependency(Class<?> dependencyType, Object key):
从容器中移除一个可解析的依赖。
ConfigurableBeanFactory 通常用于更高级的 Spring 配置和自定义扩展。在大多数情况下,开发者不需要直接与此接口交互,因为 Spring 的 XmlBeanFactory、DefaultListableBeanFactory 等实现类已经提供了这些功能。然而,在创建自定义的 BeanFactory 实现或需要更细粒度的控制时,这个接口会很有用。
源码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
/**
* Scope identifier for the standard singleton scope: "singleton".
* Custom scopes can be added via {@code registerScope}.
* @see #registerScope
*/
String SCOPE_SINGLETON = "singleton";
/**
* Scope identifier for the standard prototype scope: "prototype".
* Custom scopes can be added via {@code registerScope}.
* @see #registerScope
*/
String SCOPE_PROTOTYPE = "prototype";
/**
* Set the parent of this bean factory.
* <p>Note that the parent cannot be changed: It should only be set outside
* a constructor if it isn't available at the time of factory instantiation.
* @param parentBeanFactory the parent BeanFactory
* @throws IllegalStateException if this factory is already associated with
* a parent BeanFactory
* @see #getParentBeanFactory()
*/
void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException;
/**
* Set the class loader to use for loading bean classes.
* Default is the thread context class loader.
* <p>Note that this class loader will only apply to bean definitions
* that do not carry a resolved bean class yet. This is the case as of
* Spring 2.0 by default: Bean definitions only carry bean class names,
* to be resolved once the factory processes the bean definition.
* @param beanClassLoader the class loader to use,
* or {@code null} to suggest the default class loader
*/
void setBeanClassLoader(@Nullable ClassLoader beanClassLoader);
/**
* Return this factory's class loader for loading bean classes
* (only {@code null} if even the system ClassLoader isn't accessible).
* @see org.springframework.util.ClassUtils#forName(String, ClassLoader)
*/
@Nullable
ClassLoader getBeanClassLoader();
/**
* Specify a temporary ClassLoader to use for type matching purposes.
* Default is none, simply using the standard bean ClassLoader.
* <p>A temporary ClassLoader is usually just specified if
* <i>load-time weaving</i> is involved, to make sure that actual bean
* classes are loaded as lazily as possible. The temporary loader is
* then removed once the BeanFactory completes its bootstrap phase.
* @since 2.5
*/
void setTempClassLoader(@Nullable ClassLoader tempClassLoader);
/**
* Return the temporary ClassLoader to use for type matching purposes,
* if any.
* @since 2.5
*/
@Nullable
ClassLoader getTempClassLoader();
/**
* Set whether to cache bean metadata such as given bean definitions
* (in merged fashion) and resolved bean classes. Default is on.
* <p>Turn this flag off to enable hot-refreshing of bean definition objects
* and in particular bean classes. If this flag is off, any creation of a bean
* instance will re-query the bean class loader for newly resolved classes.
*/
void setCacheBeanMetadata(boolean cacheBeanMetadata);
/**
* Return whether to cache bean metadata such as given bean definitions
* (in merged fashion) and resolved bean classes.
*/
boolean isCacheBeanMetadata();
/**
* Specify the resolution strategy for expressions in bean definition values.
* <p>There is no expression support active in a BeanFactory by default.
* An ApplicationContext will typically set a standard expression strategy
* here, supporting "#{...}" expressions in a Unified EL compatible style.
* @since 3.0
*/
void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver);
/**
* Return the resolution strategy for expressions in bean definition values.
* @since 3.0
*/
@Nullable
BeanExpressionResolver getBeanExpressionResolver();
/**
* Specify a Spring 3.0 ConversionService to use for converting
* property values, as an alternative to JavaBeans PropertyEditors.
* @since 3.0
*/
void setConversionService(@Nullable ConversionService conversionService);
/**
* Return the associated ConversionService, if any.
* @since 3.0
*/
@Nullable
ConversionService getConversionService();
/**
* Add a PropertyEditorRegistrar to be applied to all bean creation processes.
* <p>Such a registrar creates new PropertyEditor instances and registers them
* on the given registry, fresh for each bean creation attempt. This avoids
* the need for synchronization on custom editors; hence, it is generally
* preferable to use this method instead of {@link #registerCustomEditor}.
* @param registrar the PropertyEditorRegistrar to register
*/
void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar);
/**
* Register the given custom property editor for all properties of the
* given type. To be invoked during factory configuration.
* <p>Note that this method will register a shared custom editor instance;
* access to that instance will be synchronized for thread-safety. It is
* generally preferable to use {@link #addPropertyEditorRegistrar} instead
* of this method, to avoid for the need for synchronization on custom editors.
* @param requiredType type of the property
* @param propertyEditorClass the {@link PropertyEditor} class to register
*/
void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass);
/**
* Initialize the given PropertyEditorRegistry with the custom editors
* that have been registered with this BeanFactory.
* @param registry the PropertyEditorRegistry to initialize
*/
void copyRegisteredEditorsTo(PropertyEditorRegistry registry);
/**
* Set a custom type converter that this BeanFactory should use for converting
* bean property values, constructor argument values, etc.
* <p>This will override the default PropertyEditor mechanism and hence make
* any custom editors or custom editor registrars irrelevant.
* @since 2.5
* @see #addPropertyEditorRegistrar
* @see #registerCustomEditor
*/
void setTypeConverter(TypeConverter typeConverter);
/**
* Obtain a type converter as used by this BeanFactory. This may be a fresh
* instance for each call, since TypeConverters are usually <i>not</i> thread-safe.
* <p>If the default PropertyEditor mechanism is active, the returned
* TypeConverter will be aware of all custom editors that have been registered.
* @since 2.5
*/
TypeConverter getTypeConverter();
/**
* Add a String resolver for embedded values such as annotation attributes.
* @param valueResolver the String resolver to apply to embedded values
* @since 3.0
*/
void addEmbeddedValueResolver(StringValueResolver valueResolver);
/**
* Determine whether an embedded value resolver has been registered with this
* bean factory, to be applied through {@link #resolveEmbeddedValue(String)}.
* @since 4.3
*/
boolean hasEmbeddedValueResolver();
/**
* Resolve the given embedded value, e.g. an annotation attribute.
* @param value the value to resolve
* @return the resolved value (may be the original value as-is)
* @since 3.0
*/
@Nullable
String resolveEmbeddedValue(String value);
/**
* Add a new BeanPostProcessor that will get applied to beans created
* by this factory. To be invoked during factory configuration.
* <p>Note: Post-processors submitted here will be applied in the order of
* registration; any ordering semantics expressed through implementing the
* {@link org.springframework.core.Ordered} interface will be ignored. Note
* that autodetected post-processors (e.g. as beans in an ApplicationContext)
* will always be applied after programmatically registered ones.
* @param beanPostProcessor the post-processor to register
*/
void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);
/**
* Return the current number of registered BeanPostProcessors, if any.
*/
int getBeanPostProcessorCount();
/**
* Register the given scope, backed by the given Scope implementation.
* @param scopeName the scope identifier
* @param scope the backing Scope implementation
*/
void registerScope(String scopeName, Scope scope);
/**
* Return the names of all currently registered scopes.
* <p>This will only return the names of explicitly registered scopes.
* Built-in scopes such as "singleton" and "prototype" won't be exposed.
* @return the array of scope names, or an empty array if none
* @see #registerScope
*/
String[] getRegisteredScopeNames();
/**
* Return the Scope implementation for the given scope name, if any.
* <p>This will only return explicitly registered scopes.
* Built-in scopes such as "singleton" and "prototype" won't be exposed.
* @param scopeName the name of the scope
* @return the registered Scope implementation, or {@code null} if none
* @see #registerScope
* 获取作用域
*/
@Nullable
Scope getRegisteredScope(String scopeName);
/**
* Provides a security access control context relevant to this factory.
* @return the applicable AccessControlContext (never {@code null})
* @since 3.0
*/
AccessControlContext getAccessControlContext();
/**
* Copy all relevant configuration from the given other factory.
* <p>Should include all standard configuration settings as well as
* BeanPostProcessors, Scopes, and factory-specific internal settings.
* Should not include any metadata of actual bean definitions,
* such as BeanDefinition objects and bean name aliases.
* @param otherFactory the other BeanFactory to copy from
* 复制配置
*/
void copyConfigurationFrom(ConfigurableBeanFactory otherFactory);
/**
* Given a bean name, create an alias. We typically use this method to
* support names that are illegal within XML ids (used for bean names).
* <p>Typically invoked during factory configuration, but can also be
* used for runtime registration of aliases. Therefore, a factory
* implementation should synchronize alias access.
* @param beanName the canonical name of the target bean
* @param alias the alias to be registered for the bean
* @throws BeanDefinitionStoreException if the alias is already in use
* 注册bean的别名
*/
void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException;
/**
* Resolve all alias target names and aliases registered in this
* factory, applying the given StringValueResolver to them.
* <p>The value resolver may for example resolve placeholders
* in target bean names and even in alias names.
* @param valueResolver the StringValueResolver to apply
* @since 2.5
* 解析bean的别名
*/
void resolveAliases(StringValueResolver valueResolver);
/**
* Return a merged BeanDefinition for the given bean name,
* merging a child bean definition with its parent if necessary.
* Considers bean definitions in ancestor factories as well.
* @param beanName the name of the bean to retrieve the merged definition for
* @return a (potentially merged) BeanDefinition for the given bean
* @throws NoSuchBeanDefinitionException if there is no bean definition with the given name
* @since 2.5
* 根据beanName获取bean的定义信息
*/
BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
/**
* Determine whether the bean with the given name is a FactoryBean.
* @param name the name of the bean to check
* @return whether the bean is a FactoryBean
* ({@code false} means the bean exists but is not a FactoryBean)
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 2.5
* 判断该name的bean的是否是FactoryBean类型
*/
boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException;
/**
* Explicitly control the current in-creation status of the specified bean.
* For container-internal use only.
* @param beanName the name of the bean
* @param inCreation whether the bean is currently in creation
* @since 3.1
* inCreation为true则从inCreationCheckExclusions集合中移除该bean
* inCreation为false则将beanName添加到inCreationCheckExclusions集合中
*/
void setCurrentlyInCreation(String beanName, boolean inCreation);
/**
* Determine whether the specified bean is currently in creation.
* @param beanName the name of the bean
* @return whether the bean is currently in creation
* @since 2.5
* 根据beanName判断该bean是否正在创建中
*/
boolean isCurrentlyInCreation(String beanName);
/**
* Register a dependent bean for the given bean,
* to be destroyed before the given bean is destroyed.
* @param beanName the name of the bean
* @param dependentBeanName the name of the dependent bean
* @since 2.5
* 根据beanName和该bean依赖的BeanName注册依赖bean
*/
void registerDependentBean(String beanName, String dependentBeanName);
/**
* Return the names of all beans which depend on the specified bean, if any.
* @param beanName the name of the bean
* @return the array of dependent bean names, or an empty array if none
* @since 2.5
* 根据benaName获取该bean的所有依赖
*/
String[] getDependentBeans(String beanName);
/**
* Return the names of all beans that the specified bean depends on, if any.
* @param beanName the name of the bean
* @return the array of names of beans which the bean depends on,
* or an empty array if none
* @since 2.5
* 根据beanName获取该bean所有依赖
*/
String[] getDependenciesForBean(String beanName);
/**
* Destroy the given bean instance (usually a prototype instance
* obtained from this factory) according to its bean definition.
* <p>Any exception that arises during destruction should be caught
* and logged instead of propagated to the caller of this method.
* @param beanName the name of the bean definition
* @param beanInstance the bean instance to destroy
* 根据beanName和bean实例销毁bean
*/
void destroyBean(String beanName, Object beanInstance);
/**
* Destroy the specified scoped bean in the current target scope, if any.
* <p>Any exception that arises during destruction should be caught
* and logged instead of propagated to the caller of this method.
* @param beanName the name of the scoped bean
* 根据beanName销毁bean
*/
void destroyScopedBean(String beanName);
/**
* Destroy all singleton beans in this factory, including inner beans that have
* been registered as disposable. To be called on shutdown of a factory.
* <p>Any exception that arises during destruction should be caught
* and logged instead of propagated to the caller of this method.
* 销毁所有的单例bean
*/
void destroySingletons();
}