【Spring】|【Spring4揭秘 BeanFactory】基本容器-BeanFactory

控制反转即IoC (Inversion of Control),它把传统上由程序代码直接操控的对象的调用权交给容器,通过容器来实现对象组件的装配和管理。所谓的“控制反转”概念就是对组件对象控制权的转移,从程序代码本身转移到了外部容器。
本章介绍第一个基本容器BeanFactory
一、 BeanFactory的类结构 相关接口和实现类的UML图如下
【Spring】|【Spring4揭秘 BeanFactory】基本容器-BeanFactory
文章图片

1.BeanFactory接口:
是Spring bean容器的根接口.提供获取bean,是否包含bean,是否单例与原型,获取bean类型,bean 别名的方法
2.BeanFactory的三个子接口:
HierarchicalBeanFactory:提供父容器的访问功能
ListableBeanFactory:提供了批量获取Bean的方法
AutowireCapableBeanFactory:在BeanFactory基础上实现对已存在实例的管理
3.ConfigurableBeanFactory:
4.ConfigurableListableBeanFactory:
继承了上述的所有接口,增加了其他功能:比如类加载器,类型转化,属性编辑器,BeanPostProcessor,作用域,bean定义,处理bean依赖关系, bean如何销毁…
5.实现类DefaultListableBeanFactory:
实现了ConfigurableListableBeanFactory,实现上述BeanFactory所有功能。它还可以注册BeanDefinition
二 、BeanFactory接口

public interface BeanFactory {String FACTORY_BEAN_PREFIX = "&"; Object getBean(String name) throws BeansException; T getBean(String name, Class requiredType) throws BeansException; T getBean(Class requiredType) throws BeansException; Object getBean(String name, Object... args) throws BeansException; T getBean(Class requiredType, Object... args) throws BeansException; boolean isSingleton(String name) throws NoSuchBeanDefinitionException; boolean isPrototype(String name) throws NoSuchBeanDefinitionException; boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException; boolean isTypeMatch(String name, Class typeToMatch) throws NoSuchBeanDefinitionException; Class getType(String name) throws NoSuchBeanDefinitionException; String[] getAliases(String name); }

FACTORY_BEAN_PREFIX = “&”:
&前缀的字符串可以用来引用一个FactoryBean实例,或把它和工厂产生的Bean区分开,就是说,如果一个FactoryBean的名字为a,那么,&a会得到那个FactoryBean,实例如下:
public class FactoryTest implements FactoryBean { @Override public String getObject() throws Exception { return "test12345"; }@Override public Class getObjectType() {return String.class; }@Override public boolean isSingleton() {return true; }@Override public String toString() { return "A FactoryBean"; }public static void main(String[] args) { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition("test", new RootBeanDefinition(FactoryTest.class)); //注册一个FactoryBean类型的BeanDefinition System.out.println(factory.getBean("test")); //获取Bean,也就是调用了FactoryBean的getObject System.out.println(factory.getBean("&test")); //& 获取FactoryBean } } =========输出======== test12345 A FactoryBean

【【Spring】|【Spring4揭秘 BeanFactory】基本容器-BeanFactory】getBean(String name): 根据名称获取Bean
getBean(String name, Class< T> requiredType): 根据类型获取Bean
getBean(String name, Object… args):获取Bean
getBean(Class< T> requiredType, Object… args):获取Bean
isSingleton(String name)::是否为单实例
isPrototype(String name)::是否为原型(多实例)
isTypeMatch(String name, ResolvableType typeToMatch):名称、类型是否匹配
isTypeMatch(String name, Class< ?> typeToMatch)::名称、类型是否匹配
Class< ? > getType(String name) :根据实例的名字 获取类型
String[] getAliases(String name): 根据实例的名字获取实例的别名数组
三、ListableBeanFactory
public interface ListableBeanFactory extends BeanFactory { //BeanDefinition相关 boolean containsBeanDefinition(String beanName); int getBeanDefinitionCount(); String[] getBeanDefinitionNames(); //跟据bean 的类型获取bean .它不会检查嵌套的FactoryBean创建的bean String[] getBeanNamesForType(ResolvableType type); String[] getBeanNamesForType(Class type); String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit); Map getBeansOfType(Class type) throws BeansException; Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException; //根据注解查找相关BeanName数组 String[] getBeanNamesForAnnotation(Class annotationType); //根据注解查找相关Bean的Map Map getBeansWithAnnotation(Class annotationType) throws BeansException; //查找一个Bean上的注解 A findAnnotationOnBean(String beanName, Class annotationType) throws NoSuchBeanDefinitionException; }

获取bean时,Spring 鼓励使用这个接口定义的api. 主要提供三类方法:
1.获取BeanDefinition
2.批量获取BeanName和Bean(返回数组和Map)
3.注解相关,示例代码如下:
@Controller(value = "https://www.it610.com/article/OK") public class FactoryTest {public static void main(String[] args) { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); RootBeanDefinition definition = new RootBeanDefinition(FactoryTest.class); factory.registerBeanDefinition("test", definition); System.out.println( Arrays.toString( factory.getBeanNamesForAnnotation(Controller.class))); System.out.println(factory.getBeansWithAnnotation(Controller.class)); System.out.println(factory.findAnnotationOnBean("test",Controller.class)); } }

结果如下:
[test] {test=FactoryTest@d041cf} @org.springframework.stereotype.Controller(value=https://www.it610.com/article/OK)

四、AutowireCapableBeanFactory
public interface AutowireCapableBeanFactory extends BeanFactory {int AUTOWIRE_NO = 0; //不使用自动装配 int AUTOWIRE_BY_NAME = 1; //通过名称自动装配 int AUTOWIRE_BY_TYPE = 2; //通过类型自动装配 int AUTOWIRE_CONSTRUCTOR = 3; //构造器装配 @Deprecated int AUTOWIRE_AUTODETECT = 4; //已过时//------ 创建外部Bean实例的典型方法--------------------------- //根据指定Class创建一个全新的Bean实例 T createBean(Class beanClass) throws BeansException; //给定对象,根据注释、后处理器等,进行自动装配 void autowireBean(Object existingBean) throws BeansException; // 根据Bean名的BeanDefinition装配这个未加工的Object,执行回调和各种后处理器。 Object configureBean(Object existingBean, String beanName) throws BeansException; //分解Bean在工厂中定义的这个指定的依赖descriptor Object resolveDependency(DependencyDescriptor descriptor, String beanName) throws BeansException; //-----------Bean实例生命周期相关方法------------------- / 根据给定的类型和指定的装配策略,创建一个新的Bean实例 Object createBean(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException; // Object autowire(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException; //根据名称或类型自动装配 void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException; //自动装配 void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException; //初始化一个Bean... Object initializeBean(Object existingBean, String beanName) throws BeansException; //初始化之前执行BeanPostProcessors Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException; //初始化之后执行BeanPostProcessors Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException; //销毁一个Bean void destroyBean(Object existingBean); //分解指定的依赖 Object resolveDependency(DependencyDescriptor descriptor, String beanName, Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException; }

这个接口定义了将容器中的Bean按某种规则(如按名字,类型的匹配等)进行自动装配的方法。在我们开发的应用中很少用到,像ApplicationContext这样的外观实现类不会实现这个接口。它更多的作用是和其它组件结合,比如Struts2等,把不在spring容器中的bean加入到spring的生命周期中。
五、ConfigurableBeanFactory
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {//常亮-单例 String SCOPE_SINGLETON = "singleton"; //常量-原型 String SCOPE_PROTOTYPE = "prototype"; //设置父BeanFactory void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException; //以下四个:设置和获取BeanClassLoader void setBeanClassLoader(ClassLoader beanClassLoader); ClassLoader getBeanClassLoader(); void setTempClassLoader(ClassLoader tempClassLoader); ClassLoader getTempClassLoader(); //是否需要缓存bean metadata,比如bean difinition 和 解析好的classes.默认开启缓存 void setCacheBeanMetadata(boolean cacheBeanMetadata); boolean isCacheBeanMetadata(); // 定义用于解析bean definition的表达式解析器 void setBeanExpressionResolver(BeanExpressionResolver resolver); BeanExpressionResolver getBeanExpressionResolver(); //类型转化器 void setConversionService(ConversionService conversionService); ConversionService getConversionService(); //属性编辑器 void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar); //BeanFactory用来转换bean属性值或者参数值的自定义转换器 void registerCustomEditor(Class requiredType, Class propertyEditorClass); void copyRegisteredEditorsTo(PropertyEditorRegistry registry); //类型转换器 void setTypeConverter(TypeConverter typeConverter); TypeConverter getTypeConverter(); void addEmbeddedValueResolver(StringValueResolver valueResolver); String resolveEmbeddedValue(String value); //Bean处理器 void addBeanPostProcessor(BeanPostProcessor beanPostProcessor); int getBeanPostProcessorCount(); //作用域定义 void registerScope(String scopeName, Scope scope); String[] getRegisteredScopeNames(); Scope getRegisteredScope(String scopeName); //访问权限控制 AccessControlContext getAccessControlContext(); //合并其他ConfigurableBeanFactory的配置,包括上面说到的BeanPostProcessor,作用域等 void copyConfigurationFrom(ConfigurableBeanFactory otherFactory); //bean定义处理 void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException; void resolveAliases(StringValueResolver valueResolver); BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException; //bean创建状态控制.在解决循环依赖时有使用 void setCurrentlyInCreation(String beanName, boolean inCreation); boolean isCurrentlyInCreation(String beanName); //处理bean依赖问题 void registerDependentBean(String beanName, String dependentBeanName); String[] getDependentBeans(String beanName); String[] getDependenciesForBean(String beanName); //bean生命周期管理-- 销毁bean void destroyBean(String beanName, Object beanInstance); void destroyScopedBean(String beanName); void destroySingletons(); }

ConfigurableBeanFactory同时继承了HierarchicalBeanFactory 和 SingletonBeanRegistry 这两个接口,即同时继承了分层和单例类注册的功能。
六、 ConfigurableListableBeanFactory
public interface ConfigurableListableBeanFactory extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {//设置忽略的依赖关系,注册找到的特殊依赖 void ignoreDependencyType(Class type); void ignoreDependencyInterface(Class ifc); void registerResolvableDependency(Class dependencyType, Object autowiredValue); boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor) throws NoSuchBeanDefinitionException; // 获取bean定义 (可以访问属性值跟构造方法的参数值) BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; //迭代BeanNames Iterator getBeanNamesIterator(); //清除元数据缓存 void clearMetadataCache(); //锁定配置信息.在调用refresh时会使用到. void freezeConfiguration(); boolean isConfigurationFrozen(); //预加载不是懒加载的单例.用于解决循环依赖问题 void preInstantiateSingletons() throws BeansException; }

七、AbstractBeanFactory 这个类主要提供了获取Bean的相关方法
实现了BeanFactory的方法 主要实现了getBean方法
实现了HierarchicalBeanFactory的方法 实现了ConfigurableBeanFactory 留给子类实现的方法
protected abstract boolean containsBeanDefinition(String beanName); protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException; protected abstract Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException;

八、AbstractAutowireCapableBeanFactory 这个类主要实现了创建Bean的相关方法
九、DefaultListableBeanFactory

    推荐阅读