几个常见概念的简单介绍:
1、ApplicationContext,BeanFactory
ApplicationContext:spring框架本身,IOC,AOP等核心功能都是在这里面实现的。
BeanFactory:ApplicationContext 是 BeanFactory 的子接口,BeanFactory 中实现了bean对象的定义信息保存,单例对象保存,获取(依据beanName,类或接口类型获取)。
如果说BeanFactory是Sping的心脏,那么ApplicationContext就是完整的身躯了。
BeanFactory的三个子接口:
* HierarchicalBeanFactory:提供父容器的访问功能
* ListableBeanFactory:提供了批量获取Bean的方法(最常见)
* AutowireCapableBeanFactory:在BeanFactory基础上实现对已存在实例的管理
2、BeanDefinition
1 /** 2 * A BeanDefinition describes a bean instance, which has property values, 3 * constructor argument values, and further information supplied by 4 * concrete implementations. 5 * 6 * <p>This is just a minimal interface: The main intention is to allow a 7 * {@link BeanFactoryPostProcessor} to introspect and modify property values 8 * and other bean metadata. 9 * 10 * @author Juergen Hoeller 11 * @author Rob Harrop 12 * @since 19.03.2004 13 * @see ConfigurableListableBeanFactory#getBeanDefinition 14 * @see org.springframework.beans.factory.support.RootBeanDefinition 15 * @see org.springframework.beans.factory.support.ChildBeanDefinition 16 */ 17 public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement { 18 19 /** 20 * Scope identifier for the standard singleton scope: "singleton". 21 * <p>Note that extended bean factories might support further scopes. 22 * @see #setScope 23 */ 24 String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON; 25 26 /** 27 * Scope identifier for the standard prototype scope: "prototype". 28 * <p>Note that extended bean factories might support further scopes. 29 * @see #setScope 30 */ 31 String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE; 32 33 34 /** 35 * Role hint indicating that a {@code BeanDefinition} is a major part 36 * of the application. Typically corresponds to a user-defined bean. 37 */ 38 int ROLE_APPLICATION = 0; 39 40 /** 41 * Role hint indicating that a {@code BeanDefinition} is a supporting 42 * part of some larger configuration, typically an outer 43 * {@link org.springframework.beans.factory.parsing.ComponentDefinition}. 44 * {@code SUPPORT} beans are considered important enough to be aware 45 * of when looking more closely at a particular 46 * {@link org.springframework.beans.factory.parsing.ComponentDefinition}, 47 * but not when looking at the overall configuration of an application. 48 */ 49 int ROLE_SUPPORT = 1; 50 51 /** 52 * Role hint indicating that a {@code BeanDefinition} is providing an 53 * entirely background role and has no relevance to the end-user. This hint is 54 * used when registering beans that are completely part of the internal workings 55 * of a {@link org.springframework.beans.factory.parsing.ComponentDefinition}. 56 */ 57 int ROLE_INFRASTRUCTURE = 2; 58 59 60 // Modifiable attributes 61 62 /** 63 * Set the name of the parent definition of this bean definition, if any. 64 */ 65 void setParentName(@Nullable String parentName); 66 67 /** 68 * Return the name of the parent definition of this bean definition, if any. 69 */ 70 @Nullable 71 String getParentName(); 72 73 /** 74 * Specify the bean class name of this bean definition. 75 * <p>The class name can be modified during bean factory post-processing, 76 * typically replacing the original class name with a parsed variant of it. 77 * @see #setParentName 78 * @see #setFactoryBeanName 79 * @see #setFactoryMethodName 80 */ 81 void setBeanClassName(@Nullable String beanClassName); 82 83 /** 84 * Return the current bean class name of this bean definition. 85 * <p>Note that this does not have to be the actual class name used at runtime, in 86 * case of a child definition overriding/inheriting the class name from its parent. 87 * Also, this may just be the class that a factory method is called on, or it may 88 * even be empty in case of a factory bean reference that a method is called on. 89 * Hence, do <i>not</i> consider this to be the definitive bean type at runtime but 90 * rather only use it for parsing purposes at the individual bean definition level. 91 * @see #getParentName() 92 * @see #getFactoryBeanName() 93 * @see #getFactoryMethodName() 94 */ 95 @Nullable 96 String getBeanClassName(); 97 98 /** 99 * Override the target scope of this bean, specifying a new scope name. 100 * @see #SCOPE_SINGLETON 101 * @see #SCOPE_PROTOTYPE 102 */ 103 void setScope(@Nullable String scope); 104 105 /** 106 * Return the name of the current target scope for this bean, 107 * or {@code null} if not known yet. 108 */ 109 @Nullable 110 String getScope(); 111 112 /** 113 * Set whether this bean should be lazily initialized. 114 * <p>If {@code false}, the bean will get instantiated on startup by bean 115 * factories that perform eager initialization of singletons. 116 */ 117 void setLazyInit(boolean lazyInit); 118 119 /** 120 * Return whether this bean should be lazily initialized, i.e. not 121 * eagerly instantiated on startup. Only applicable to a singleton bean. 122 */ 123 boolean isLazyInit(); 124 125 /** 126 * Set the names of the beans that this bean depends on being initialized. 127 * The bean factory will guarantee that these beans get initialized first. 128 */ 129 void setDependsOn(@Nullable String... dependsOn); 130 131 /** 132 * Return the bean names that this bean depends on. 133 */ 134 @Nullable 135 String[] getDependsOn(); 136 137 /** 138 * Set whether this bean is a candidate for getting autowired into some other bean. 139 * <p>Note that this flag is designed to only affect type-based autowiring. 140 * It does not affect explicit references by name, which will get resolved even 141 * if the specified bean is not marked as an autowire candidate. As a consequence, 142 * autowiring by name will nevertheless inject a bean if the name matches. 143 */ 144 void setAutowireCandidate(boolean autowireCandidate); 145 146 /** 147 * Return whether this bean is a candidate for getting autowired into some other bean. 148 */ 149 boolean isAutowireCandidate(); 150 151 /** 152 * Set whether this bean is a primary autowire candidate. 153 * <p>If this value is {@code true} for exactly one bean among multiple 154 * matching candidates, it will serve as a tie-breaker. 155 */ 156 void setPrimary(boolean primary); 157 158 /** 159 * Return whether this bean is a primary autowire candidate. 160 */ 161 boolean isPrimary(); 162 163 /** 164 * Specify the factory bean to use, if any. 165 * This the name of the bean to call the specified factory method on. 166 * @see #setFactoryMethodName 167 */ 168 void setFactoryBeanName(@Nullable String factoryBeanName); 169 170 /** 171 * Return the factory bean name, if any. 172 */ 173 @Nullable 174 String getFactoryBeanName(); 175 176 /** 177 * Specify a factory method, if any. This method will be invoked with 178 * constructor arguments, or with no arguments if none are specified. 179 * The method will be invoked on the specified factory bean, if any, 180 * or otherwise as a static method on the local bean class. 181 * @see #setFactoryBeanName 182 * @see #setBeanClassName 183 */ 184 void setFactoryMethodName(@Nullable String factoryMethodName); 185 186 /** 187 * Return a factory method, if any. 188 */ 189 @Nullable 190 String getFactoryMethodName(); 191 192 /** 193 * Return the constructor argument values for this bean. 194 * <p>The returned instance can be modified during bean factory post-processing. 195 * @return the ConstructorArgumentValues object (never {@code null}) 196 */ 197 ConstructorArgumentValues getConstructorArgumentValues(); 198 199 /** 200 * Return if there are constructor argument values defined for this bean. 201 * @since 5.0.2 202 */ 203 default boolean hasConstructorArgumentValues() { 204 return !getConstructorArgumentValues().isEmpty(); 205 } 206 207 /** 208 * Return the property values to be applied to a new instance of the bean. 209 * <p>The returned instance can be modified during bean factory post-processing. 210 * @return the MutablePropertyValues object (never {@code null}) 211 */ 212 MutablePropertyValues getPropertyValues(); 213 214 /** 215 * Return if there are property values values defined for this bean. 216 * @since 5.0.2 217 */ 218 default boolean hasPropertyValues() { 219 return !getPropertyValues().isEmpty(); 220 } 221 222 /** 223 * Set the name of the initializer method. 224 * @since 5.1 225 */ 226 void setInitMethodName(@Nullable String initMethodName); 227 228 /** 229 * Return the name of the initializer method. 230 * @since 5.1 231 */ 232 @Nullable 233 String getInitMethodName(); 234 235 /** 236 * Set the name of the destroy method. 237 * @since 5.1 238 */ 239 void setDestroyMethodName(@Nullable String destroyMethodName); 240 241 /** 242 * Return the name of the destroy method. 243 * @since 5.1 244 */ 245 @Nullable 246 String getDestroyMethodName(); 247 248 /** 249 * Set the role hint for this {@code BeanDefinition}. The role hint 250 * provides the frameworks as well as tools with an indication of 251 * the role and importance of a particular {@code BeanDefinition}. 252 * @since 5.1 253 * @see #ROLE_APPLICATION 254 * @see #ROLE_SUPPORT 255 * @see #ROLE_INFRASTRUCTURE 256 */ 257 void setRole(int role); 258 259 /** 260 * Get the role hint for this {@code BeanDefinition}. The role hint 261 * provides the frameworks as well as tools with an indication of 262 * the role and importance of a particular {@code BeanDefinition}. 263 * @see #ROLE_APPLICATION 264 * @see #ROLE_SUPPORT 265 * @see #ROLE_INFRASTRUCTURE 266 */ 267 int getRole(); 268 269 /** 270 * Set a human-readable description of this bean definition. 271 * @since 5.1 272 */ 273 void setDescription(@Nullable String description); 274 275 /** 276 * Return a human-readable description of this bean definition. 277 */ 278 @Nullable 279 String getDescription(); 280 281 282 // Read-only attributes 283 284 /** 285 * Return a resolvable type for this bean definition, 286 * based on the bean class or other specific metadata. 287 * <p>This is typically fully resolved on a runtime-merged bean definition 288 * but not necessarily on a configuration-time definition instance. 289 * @return the resolvable type (potentially {@link ResolvableType#NONE}) 290 * @since 5.2 291 * @see ConfigurableBeanFactory#getMergedBeanDefinition 292 */ 293 ResolvableType getResolvableType(); 294 295 /** 296 * Return whether this a <b>Singleton</b>, with a single, shared instance 297 * returned on all calls. 298 * @see #SCOPE_SINGLETON 299 */ 300 boolean isSingleton(); 301 302 /** 303 * Return whether this a <b>Prototype</b>, with an independent instance 304 * returned for each call. 305 * @since 3.0 306 * @see #SCOPE_PROTOTYPE 307 */ 308 boolean isPrototype(); 309 310 /** 311 * Return whether this bean is "abstract", that is, not meant to be instantiated. 312 */ 313 boolean isAbstract(); 314 315 /** 316 * Return a description of the resource that this bean definition 317 * came from (for the purpose of showing context in case of errors). 318 */ 319 @Nullable 320 String getResourceDescription(); 321 322 /** 323 * Return the originating BeanDefinition, or {@code null} if none. 324 * Allows for retrieving the decorated bean definition, if any. 325 * <p>Note that this method returns the immediate originator. Iterate through the 326 * originator chain to find the original BeanDefinition as defined by the user. 327 */ 328 @Nullable 329 BeanDefinition getOriginatingBeanDefinition(); 330 331 }
从BeanDefinition源码可以看出,BeanDefinition保存了Bean的所有定义信息,包括类名,scope,属性,构造函数列表,是否单例,是否懒加载等等。其实spring后续创建对象bean,就是通过拿到BeanDefinition,然后通过反射创建而成。
实现类:ChildBeanDefinition、RootBeanDefinition、GenericBeanDefinition等。
3、BeanDefinitionRegistry
1 /** 2 * Interface for registries that hold bean definitions, for example RootBeanDefinition 3 * and ChildBeanDefinition instances. Typically implemented by BeanFactories that 4 * internally work with the AbstractBeanDefinition hierarchy. 5 * 6 * <p>This is the only interface in Spring's bean factory packages that encapsulates 7 * <i>registration</i> of bean definitions. The standard BeanFactory interfaces 8 * only cover access to a <i>fully configured factory instance</i>. 9 * 10 * <p>Spring's bean definition readers expect to work on an implementation of this 11 * interface. Known implementors within the Spring core are DefaultListableBeanFactory 12 * and GenericApplicationContext. 13 * 14 * @author Juergen Hoeller 15 * @since 26.11.2003 16 * @see org.springframework.beans.factory.config.BeanDefinition 17 * @see AbstractBeanDefinition 18 * @see RootBeanDefinition 19 * @see ChildBeanDefinition 20 * @see DefaultListableBeanFactory 21 * @see org.springframework.context.support.GenericApplicationContext 22 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader 23 * @see PropertiesBeanDefinitionReader 24 */ 25 public interface BeanDefinitionRegistry extends AliasRegistry { 26 27 /** 28 * Register a new bean definition with this registry. 29 * Must support RootBeanDefinition and ChildBeanDefinition. 30 * @param beanName the name of the bean instance to register 31 * @param beanDefinition definition of the bean instance to register 32 * @throws BeanDefinitionStoreException if the BeanDefinition is invalid 33 * @throws BeanDefinitionOverrideException if there is already a BeanDefinition 34 * for the specified bean name and we are not allowed to override it 35 * @see GenericBeanDefinition 36 * @see RootBeanDefinition 37 * @see ChildBeanDefinition 38 */ 39 void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) 40 throws BeanDefinitionStoreException; 41 42 /** 43 * Remove the BeanDefinition for the given name. 44 * @param beanName the name of the bean instance to register 45 * @throws NoSuchBeanDefinitionException if there is no such bean definition 46 */ 47 void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; 48 49 /** 50 * Return the BeanDefinition for the given bean name. 51 * @param beanName name of the bean to find a definition for 52 * @return the BeanDefinition for the given name (never {@code null}) 53 * @throws NoSuchBeanDefinitionException if there is no such bean definition 54 */ 55 BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; 56 57 /** 58 * Check if this registry contains a bean definition with the given name. 59 * @param beanName the name of the bean to look for 60 * @return if this registry contains a bean definition with the given name 61 */ 62 boolean containsBeanDefinition(String beanName); 63 64 /** 65 * Return the names of all beans defined in this registry. 66 * @return the names of all beans defined in this registry, 67 * or an empty array if none defined 68 */ 69 String[] getBeanDefinitionNames(); 70 71 /** 72 * Return the number of beans defined in the registry. 73 * @return the number of beans defined in the registry 74 */ 75 int getBeanDefinitionCount(); 76 77 /** 78 * Determine whether the given bean name is already in use within this registry, 79 * i.e. whether there is a local bean or alias registered under this name. 80 * @param beanName the name to check 81 * @return whether the given bean name is already in use 82 */ 83 boolean isBeanNameInUse(String beanName); 84 85 }
接口类,BeanDefinition增删改查操作。可以看出容器中每一个BeanDefinition都有一个对应的beanName,事实上BeanFactory内部保存BeanDefinition的结构就是一个ConcurrentHashMap<String, BeanDefinition>
4、XxxMetadata
元数据:与之相关的所有信息的集合体,常用于接口之间的参数传递
AnnotationMetadata:注解的元数据
1 /** 2 * Interface that defines abstract access to the annotations of a specific 3 * class, in a form that does not require that class to be loaded yet. 4 * 5 * @author Juergen Hoeller 6 * @author Mark Fisher 7 * @author Phillip Webb 8 * @author Sam Brannen 9 * @since 2.5 10 * @see StandardAnnotationMetadata 11 * @see org.springframework.core.type.classreading.MetadataReader#getAnnotationMetadata() 12 * @see AnnotatedTypeMetadata 13 */ 14 public interface AnnotationMetadata extends ClassMetadata, AnnotatedTypeMetadata { 15 16 /** 17 * Get the fully qualified class names of all annotation types that 18 * are <em>present</em> on the underlying class. 19 * @return the annotation type names 20 */ 21 default Set<String> getAnnotationTypes() { 22 return getAnnotations().stream() 23 .filter(MergedAnnotation::isDirectlyPresent) 24 .map(annotation -> annotation.getType().getName()) 25 .collect(Collectors.toCollection(LinkedHashSet::new)); 26 } 27 28 /** 29 * Get the fully qualified class names of all meta-annotation types that 30 * are <em>present</em> on the given annotation type on the underlying class. 31 * @param annotationName the fully qualified class name of the meta-annotation 32 * type to look for 33 * @return the meta-annotation type names, or an empty set if none found 34 */ 35 default Set<String> getMetaAnnotationTypes(String annotationName) { 36 MergedAnnotation<?> annotation = getAnnotations().get(annotationName, MergedAnnotation::isDirectlyPresent); 37 if (!annotation.isPresent()) { 38 return Collections.emptySet(); 39 } 40 return MergedAnnotations.from(annotation.getType(), SearchStrategy.INHERITED_ANNOTATIONS).stream() 41 .map(mergedAnnotation -> mergedAnnotation.getType().getName()) 42 .collect(Collectors.toCollection(LinkedHashSet::new)); 43 } 44 45 /** 46 * Determine whether an annotation of the given type is <em>present</em> on 47 * the underlying class. 48 * @param annotationName the fully qualified class name of the annotation 49 * type to look for 50 * @return {@code true} if a matching annotation is present 51 */ 52 default boolean hasAnnotation(String annotationName) { 53 return getAnnotations().isDirectlyPresent(annotationName); 54 } 55 56 /** 57 * Determine whether the underlying class has an annotation that is itself 58 * annotated with the meta-annotation of the given type. 59 * @param metaAnnotationName the fully qualified class name of the 60 * meta-annotation type to look for 61 * @return {@code true} if a matching meta-annotation is present 62 */ 63 default boolean hasMetaAnnotation(String metaAnnotationName) { 64 return getAnnotations().get(metaAnnotationName, 65 MergedAnnotation::isMetaPresent).isPresent(); 66 } 67 68 /** 69 * Determine whether the underlying class has any methods that are 70 * annotated (or meta-annotated) with the given annotation type. 71 * @param annotationName the fully qualified class name of the annotation 72 * type to look for 73 */ 74 default boolean hasAnnotatedMethods(String annotationName) { 75 return !getAnnotatedMethods(annotationName).isEmpty(); 76 } 77 78 /** 79 * Retrieve the method metadata for all methods that are annotated 80 * (or meta-annotated) with the given annotation type. 81 * <p>For any returned method, {@link MethodMetadata#isAnnotated} will 82 * return {@code true} for the given annotation type. 83 * @param annotationName the fully qualified class name of the annotation 84 * type to look for 85 * @return a set of {@link MethodMetadata} for methods that have a matching 86 * annotation. The return value will be an empty set if no methods match 87 * the annotation type. 88 */ 89 Set<MethodMetadata> getAnnotatedMethods(String annotationName); 90 91 92 /** 93 * Factory method to create a new {@link AnnotationMetadata} instance 94 * for the given class using standard reflection. 95 * @param type the class to introspect 96 * @return a new {@link AnnotationMetadata} instance 97 * @since 5.2 98 */ 99 static AnnotationMetadata introspect(Class<?> type) { 100 return StandardAnnotationMetadata.from(type); 101 } 102 103 }
5、BeanPostProcessor
bean初始化的后置处理器
1 /** 2 * Factory hook that allows for custom modification of new bean instances — 3 * for example, checking for marker interfaces or wrapping beans with proxies. 4 * 5 * <p>Typically, post-processors that populate beans via marker interfaces 6 * or the like will implement {@link #postProcessBeforeInitialization}, 7 * while post-processors that wrap beans with proxies will normally 8 * implement {@link #postProcessAfterInitialization}. 9 * 10 * <h3>Registration</h3> 11 * <p>An {@code ApplicationContext} can autodetect {@code BeanPostProcessor} beans 12 * in its bean definitions and apply those post-processors to any beans subsequently 13 * created. A plain {@code BeanFactory} allows for programmatic registration of 14 * post-processors, applying them to all beans created through the bean factory. 15 * 16 * <h3>Ordering</h3> 17 * <p>{@code BeanPostProcessor} beans that are autodetected in an 18 * {@code ApplicationContext} will be ordered according to 19 * {@link org.springframework.core.PriorityOrdered} and 20 * {@link org.springframework.core.Ordered} semantics. In contrast, 21 * {@code BeanPostProcessor} beans that are registered programmatically with a 22 * {@code BeanFactory} will be applied in the order of registration; any ordering 23 * semantics expressed through implementing the 24 * {@code PriorityOrdered} or {@code Ordered} interface will be ignored for 25 * programmatically registered post-processors. Furthermore, the 26 * {@link org.springframework.core.annotation.Order @Order} annotation is not 27 * taken into account for {@code BeanPostProcessor} beans. 28 * 29 * @author Juergen Hoeller 30 * @author Sam Brannen 31 * @since 10.10.2003 32 * @see InstantiationAwareBeanPostProcessor 33 * @see DestructionAwareBeanPostProcessor 34 * @see ConfigurableBeanFactory#addBeanPostProcessor 35 * @see BeanFactoryPostProcessor 36 */ 37 public interface BeanPostProcessor { 38 39 /** 40 * Apply this {@code BeanPostProcessor} to the given new bean instance <i>before</i> any bean 41 * initialization callbacks (like InitializingBean's {@code afterPropertiesSet} 42 * or a custom init-method). The bean will already be populated with property values. 43 * The returned bean instance may be a wrapper around the original. 44 * <p>The default implementation returns the given {@code bean} as-is. 45 * @param bean the new bean instance 46 * @param beanName the name of the bean 47 * @return the bean instance to use, either the original or a wrapped one; 48 * if {@code null}, no subsequent BeanPostProcessors will be invoked 49 * @throws org.springframework.beans.BeansException in case of errors 50 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet 51 */ 52 @Nullable 53 default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 54 return bean; 55 } 56 57 /** 58 * Apply this {@code BeanPostProcessor} to the given new bean instance <i>after</i> any bean 59 * initialization callbacks (like InitializingBean's {@code afterPropertiesSet} 60 * or a custom init-method). The bean will already be populated with property values. 61 * The returned bean instance may be a wrapper around the original. 62 * <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean 63 * instance and the objects created by the FactoryBean (as of Spring 2.0). The 64 * post-processor can decide whether to apply to either the FactoryBean or created 65 * objects or both through corresponding {@code bean instanceof FactoryBean} checks. 66 * <p>This callback will also be invoked after a short-circuiting triggered by a 67 * {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method, 68 * in contrast to all other {@code BeanPostProcessor} callbacks. 69 * <p>The default implementation returns the given {@code bean} as-is. 70 * @param bean the new bean instance 71 * @param beanName the name of the bean 72 * @return the bean instance to use, either the original or a wrapped one; 73 * if {@code null}, no subsequent BeanPostProcessors will be invoked 74 * @throws org.springframework.beans.BeansException in case of errors 75 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet 76 * @see org.springframework.beans.factory.FactoryBean 77 */ 78 @Nullable 79 default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 80 return bean; 81 } 82 83 }
spring的钩子接口之一,在每一个bean初始化前后分别调用 所有BeanPostProcessor的postProcessBeforeInitialization,postProcessAfterInitialization两个函数。在bean已经被实例化,属性值也被赋值以后,在调用bean指定的初始化方法前后会被调用。
6、 XxxAware
Spring中提供了各种Aware接口,方便从上下文中获取当前的运行环境,比较常见的几个子接口有:
BeanFactoryAware,BeanNameAware,ApplicationContextAware,EnvironmentAware,BeanClassLoaderAware等,这些Aware的作用都可以从命名得知,并且其使用也是十分简单。
1 /** 2 * Interface to be implemented by any object that wishes to be notified 3 * of the {@link ApplicationContext} that it runs in. 4 * 5 * <p>Implementing this interface makes sense for example when an object 6 * requires access to a set of collaborating beans. Note that configuration 7 * via bean references is preferable to implementing this interface just 8 * for bean lookup purposes. 9 * 10 * <p>This interface can also be implemented if an object needs access to file 11 * resources, i.e. wants to call {@code getResource}, wants to publish 12 * an application event, or requires access to the MessageSource. However, 13 * it is preferable to implement the more specific {@link ResourceLoaderAware}, 14 * {@link ApplicationEventPublisherAware} or {@link MessageSourceAware} interface 15 * in such a specific scenario. 16 * 17 * <p>Note that file resource dependencies can also be exposed as bean properties 18 * of type {@link org.springframework.core.io.Resource}, populated via Strings 19 * with automatic type conversion by the bean factory. This removes the need 20 * for implementing any callback interface just for the purpose of accessing 21 * a specific file resource. 22 * 23 * <p>{@link org.springframework.context.support.ApplicationObjectSupport} is a 24 * convenience base class for application objects, implementing this interface. 25 * 26 * <p>For a list of all bean lifecycle methods, see the 27 * {@link org.springframework.beans.factory.BeanFactory BeanFactory javadocs}. 28 * 29 * @author Rod Johnson 30 * @author Juergen Hoeller 31 * @author Chris Beams 32 * @see ResourceLoaderAware 33 * @see ApplicationEventPublisherAware 34 * @see MessageSourceAware 35 * @see org.springframework.context.support.ApplicationObjectSupport 36 * @see org.springframework.beans.factory.BeanFactoryAware 37 */ 38 public interface ApplicationContextAware extends Aware { 39 40 /** 41 * Set the ApplicationContext that this object runs in. 42 * Normally this call will be used to initialize the object. 43 * <p>Invoked after population of normal bean properties but before an init callback such 44 * as {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()} 45 * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader}, 46 * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and 47 * {@link MessageSourceAware}, if applicable. 48 * @param applicationContext the ApplicationContext object to be used by this object 49 * @throws ApplicationContextException in case of context initialization errors 50 * @throws BeansException if thrown by application context methods 51 * @see org.springframework.beans.factory.BeanInitializationException 52 */ 53 void setApplicationContext(ApplicationContext applicationContext) throws BeansException; 54 55 }
1 /** 2 * A marker superinterface indicating that a bean is eligible to be notified by the 3 * Spring container of a particular framework object through a callback-style method. 4 * The actual method signature is determined by individual subinterfaces but should 5 * typically consist of just one void-returning method that accepts a single argument. 6 * 7 * <p>Note that merely implementing {@link Aware} provides no default functionality. 8 * Rather, processing must be done explicitly, for example in a 9 * {@link org.springframework.beans.factory.config.BeanPostProcessor}. 10 * Refer to {@link org.springframework.context.support.ApplicationContextAwareProcessor} 11 * for an example of processing specific {@code *Aware} interface callbacks. 12 * 13 * @author Chris Beams 14 * @author Juergen Hoeller 15 * @since 3.1 16 */ 17 public interface Aware { 18 19 }
1 /** 2 * {@link BeanPostProcessor} implementation that supplies the {@code ApplicationContext}, 3 * {@link org.springframework.core.env.Environment Environment}, or 4 * {@link StringValueResolver} for the {@code ApplicationContext} to beans that 5 * implement the {@link EnvironmentAware}, {@link EmbeddedValueResolverAware}, 6 * {@link ResourceLoaderAware}, {@link ApplicationEventPublisherAware}, 7 * {@link MessageSourceAware}, and/or {@link ApplicationContextAware} interfaces. 8 * 9 * <p>Implemented interfaces are satisfied in the order in which they are 10 * mentioned above. 11 * 12 * <p>Application contexts will automatically register this with their 13 * underlying bean factory. Applications do not use this directly. 14 * 15 * @author Juergen Hoeller 16 * @author Costin Leau 17 * @author Chris Beams 18 * @since 10.10.2003 19 * @see org.springframework.context.EnvironmentAware 20 * @see org.springframework.context.EmbeddedValueResolverAware 21 * @see org.springframework.context.ResourceLoaderAware 22 * @see org.springframework.context.ApplicationEventPublisherAware 23 * @see org.springframework.context.MessageSourceAware 24 * @see org.springframework.context.ApplicationContextAware 25 * @see org.springframework.context.support.AbstractApplicationContext#refresh() 26 */ 27 class ApplicationContextAwareProcessor implements BeanPostProcessor { 28 29 private final ConfigurableApplicationContext applicationContext; 30 31 private final StringValueResolver embeddedValueResolver; 32 33 34 /** 35 * Create a new ApplicationContextAwareProcessor for the given context. 36 */ 37 public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) { 38 this.applicationContext = applicationContext; 39 this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory()); 40 } 41 42 43 @Override 44 @Nullable 45 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 46 if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware || 47 bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware || 48 bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){ 49 return bean; 50 } 51 52 AccessControlContext acc = null; 53 54 if (System.getSecurityManager() != null) { 55 acc = this.applicationContext.getBeanFactory().getAccessControlContext(); 56 } 57 58 if (acc != null) { 59 AccessController.doPrivileged((PrivilegedAction<Object>) () -> { 60 invokeAwareInterfaces(bean); 61 return null; 62 }, acc); 63 } 64 else { 65 invokeAwareInterfaces(bean); 66 } 67 68 return bean; 69 } 70 71 private void invokeAwareInterfaces(Object bean) { 72 if (bean instanceof EnvironmentAware) { 73 ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment()); 74 } 75 if (bean instanceof EmbeddedValueResolverAware) { 76 ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver); 77 } 78 if (bean instanceof ResourceLoaderAware) { 79 ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext); 80 } 81 if (bean instanceof ApplicationEventPublisherAware) { 82 ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext); 83 } 84 if (bean instanceof MessageSourceAware) { 85 ((MessageSourceAware) bean).setMessageSource(this.applicationContext); 86 } 87 if (bean instanceof ApplicationContextAware) { 88 ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); 89 } 90 } 91 92 }
钩子接口,可以看到XxxAware本质上是利用了ApplicationContextAwareProcessor(BeanPostProcessor的实现类)实现 BeanFactory,BeanName,ApplicationContext,Environment,BeanClassLoader等spring框架相关对象向子对象的传递。
7、BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
先看各自接口源码:
1 /** 2 * Allows for custom modification of an application context's bean definitions, 3 * adapting the bean property values of the context's underlying bean factory. 4 * 5 * <p>Application contexts can auto-detect BeanFactoryPostProcessor beans in 6 * their bean definitions and apply them before any other beans get created. 7 * 8 * <p>Useful for custom config files targeted at system administrators that 9 * override bean properties configured in the application context. 10 * 11 * <p>See PropertyResourceConfigurer and its concrete implementations 12 * for out-of-the-box solutions that address such configuration needs. 13 * 14 * <p>A BeanFactoryPostProcessor may interact with and modify bean 15 * definitions, but never bean instances. Doing so may cause premature bean 16 * instantiation, violating the container and causing unintended side-effects. 17 * If bean instance interaction is required, consider implementing 18 * {@link BeanPostProcessor} instead. 19 * 20 * @author Juergen Hoeller 21 * @since 06.07.2003 22 * @see BeanPostProcessor 23 * @see PropertyResourceConfigurer 24 */ 25 @FunctionalInterface 26 public interface BeanFactoryPostProcessor { 27 28 /** 29 * Modify the application context's internal bean factory after its standard 30 * initialization. All bean definitions will have been loaded, but no beans 31 * will have been instantiated yet. This allows for overriding or adding 32 * properties even to eager-initializing beans. 33 * @param beanFactory the bean factory used by the application context 34 * @throws org.springframework.beans.BeansException in case of errors 35 */ 36 void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException; 37 38 }
1 /** 2 * Extension to the standard {@link BeanFactoryPostProcessor} SPI, allowing for 3 * the registration of further bean definitions <i>before</i> regular 4 * BeanFactoryPostProcessor detection kicks in. In particular, 5 * BeanDefinitionRegistryPostProcessor may register further bean definitions 6 * which in turn define BeanFactoryPostProcessor instances. 7 * 8 * @author Juergen Hoeller 9 * @since 3.0.1 10 * @see org.springframework.context.annotation.ConfigurationClassPostProcessor 11 */ 12 public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor { 13 14 /** 15 * Modify the application context's internal bean definition registry after its 16 * standard initialization. All regular bean definitions will have been loaded, 17 * but no beans will have been instantiated yet. This allows for adding further 18 * bean definitions before the next post-processing phase kicks in. 19 * @param registry the bean definition registry used by the application context 20 * @throws org.springframework.beans.BeansException in case of errors 21 */ 22 void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException; 23 24 }
钩子接口,可以看出BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的扩展接口,下文会介绍到,在Spring容器初始化过程中(beanFactory准备好,但是任何bean还未实例化的时候),会按顺序回调每一个BeanDefinitionRegistryPostProcessor的 postProcessBeanDefinitionRegistry 和 postProcessBeanFactory 方法,再回调每一个 BeanFactoryPostProcessor 的 postProcessBeanFactory 方法。
需要注意的是,BeanDefinitionRegistryPostProcessor 一般用于往 BeanDefinitionRegister里面注入新的BeanDefinition,事实上这也是@Import内部实现的原理。
8、InstantiationAwareBeanPostProcessor
1 /** 2 * Subinterface of {@link BeanPostProcessor} that adds a before-instantiation callback, 3 * and a callback after instantiation but before explicit properties are set or 4 * autowiring occurs. 5 * 6 * <p>Typically used to suppress default instantiation for specific target beans, 7 * for example to create proxies with special TargetSources (pooling targets, 8 * lazily initializing targets, etc), or to implement additional injection strategies 9 * such as field injection. 10 * 11 * <p><b>NOTE:</b> This interface is a special purpose interface, mainly for 12 * internal use within the framework. It is recommended to implement the plain 13 * {@link BeanPostProcessor} interface as far as possible, or to derive from 14 * {@link InstantiationAwareBeanPostProcessorAdapter} in order to be shielded 15 * from extensions to this interface. 16 * 17 * @author Juergen Hoeller 18 * @author Rod Johnson 19 * @since 1.2 20 * @see org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#setCustomTargetSourceCreators 21 * @see org.springframework.aop.framework.autoproxy.target.LazyInitTargetSourceCreator 22 */ 23 public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor { 24 25 /** 26 * Apply this BeanPostProcessor <i>before the target bean gets instantiated</i>. 27 * The returned bean object may be a proxy to use instead of the target bean, 28 * effectively suppressing default instantiation of the target bean. 29 * <p>If a non-null object is returned by this method, the bean creation process 30 * will be short-circuited. The only further processing applied is the 31 * {@link #postProcessAfterInitialization} callback from the configured 32 * {@link BeanPostProcessor BeanPostProcessors}. 33 * <p>This callback will be applied to bean definitions with their bean class, 34 * as well as to factory-method definitions in which case the returned bean type 35 * will be passed in here. 36 * <p>Post-processors may implement the extended 37 * {@link SmartInstantiationAwareBeanPostProcessor} interface in order 38 * to predict the type of the bean object that they are going to return here. 39 * <p>The default implementation returns {@code null}. 40 * @param beanClass the class of the bean to be instantiated 41 * @param beanName the name of the bean 42 * @return the bean object to expose instead of a default instance of the target bean, 43 * or {@code null} to proceed with default instantiation 44 * @throws org.springframework.beans.BeansException in case of errors 45 * @see #postProcessAfterInstantiation 46 * @see org.springframework.beans.factory.support.AbstractBeanDefinition#getBeanClass() 47 * @see org.springframework.beans.factory.support.AbstractBeanDefinition#getFactoryMethodName() 48 */ 49 @Nullable 50 default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { 51 return null; 52 } 53 54 /** 55 * Perform operations after the bean has been instantiated, via a constructor or factory method, 56 * but before Spring property population (from explicit properties or autowiring) occurs. 57 * <p>This is the ideal callback for performing custom field injection on the given bean 58 * instance, right before Spring's autowiring kicks in. 59 * <p>The default implementation returns {@code true}. 60 * @param bean the bean instance created, with properties not having been set yet 61 * @param beanName the name of the bean 62 * @return {@code true} if properties should be set on the bean; {@code false} 63 * if property population should be skipped. Normal implementations should return {@code true}. 64 * Returning {@code false} will also prevent any subsequent InstantiationAwareBeanPostProcessor 65 * instances being invoked on this bean instance. 66 * @throws org.springframework.beans.BeansException in case of errors 67 * @see #postProcessBeforeInstantiation 68 */ 69 default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { 70 return true; 71 } 72 73 /** 74 * Post-process the given property values before the factory applies them 75 * to the given bean, without any need for property descriptors. 76 * <p>Implementations should return {@code null} (the default) if they provide a custom 77 * {@link #postProcessPropertyValues} implementation, and {@code pvs} otherwise. 78 * In a future version of this interface (with {@link #postProcessPropertyValues} removed), 79 * the default implementation will return the given {@code pvs} as-is directly. 80 * @param pvs the property values that the factory is about to apply (never {@code null}) 81 * @param bean the bean instance created, but whose properties have not yet been set 82 * @param beanName the name of the bean 83 * @return the actual property values to apply to the given bean (can be the passed-in 84 * PropertyValues instance), or {@code null} which proceeds with the existing properties 85 * but specifically continues with a call to {@link #postProcessPropertyValues} 86 * (requiring initialized {@code PropertyDescriptor}s for the current bean class) 87 * @throws org.springframework.beans.BeansException in case of errors 88 * @since 5.1 89 * @see #postProcessPropertyValues 90 */ 91 @Nullable 92 default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) 93 throws BeansException { 94 95 return null; 96 } 97 }
继承接口BeanPostProcessor。bean实例化的后置处理器,代表了bean的另一端生命周期;在bean实例化到初始化过程中,会优先调用 InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation();如果这个接口返回对象且不为Null,则直接调用 InstantiationAwareBeanPostProcessor.postProcessAfterInitialization(),完成这个对象的初始化-实例化过程(也就是跳过了后续初始化过程,BeanPostProcessor、初始化等等都不再起作用)。这个也常被用于生成代理对象,完成动态代理的过程。
9、bean自定义初始化和销毁方法
- 通过@Bean指定init-method和destroy-method;
- 通过让Bean实现InitializingBean(定义初始化逻辑),DisposableBean(定义销毁逻辑);
- 可以使用JSR250;
- @PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
- @PreDestroy:在容器销毁bean之前通知我们进行清理工作
Spring初始化背后原理介绍:
1、简述
解析@Configuration配置类、文件、xml、web.xml (具体解析哪个,依据ApplicationContext类型,比如AnnotationConfigApplicationContext肯定是来解析配置文件,ClassPathXmlApplicationContext是用来解析xml等等 来决定的),将上述解析得到的所有bean信息都保存成一个个BeanDefinition,并且与beanName组合成key-value对保存到 DefaultListableBeanFactory 中的 beanDefinitionMap中,同时将beanName存入beanDefinitionNames(List 类型) 中,然后按照顺序(InstantionAwareBeanPostProcessor -> BeanPostProcessor -> ApplicationListenerDetector -> initApplicationEventMulticaster -> 其他的单实例bean)实例化bean,实例化完成后的bean放入单实例bean的缓存(private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);)中,调用getBean方法,返回缓存中的单实例。
2、Spring容器初始化过程
定位代码容器的主要初始化过程在refresh() 创建刷新方法上,所以接下来只介绍这个方法的过程。
1 @Override 2 public void refresh() throws BeansException, IllegalStateException { 3 synchronized (this.startupShutdownMonitor) { 4 //容器预先准备,记录容器启动时间和标记 5 prepareRefresh(); 6 7 //创建bean工厂,里面实现了BeanDefinition的装载 8 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); 9 10 //配置bean工厂的上下文信息,如类装载器等 11 prepareBeanFactory(beanFactory); 12 13 try { 14 //在BeanDefinition被装载后,提供一个修改BeanFactory的入口 15 postProcessBeanFactory(beanFactory); 16 17 //在bean初始化之前,提供对BeanDefinition修改入口,PropertyPlaceholderConfigurer 在这里被调用 18 invokeBeanFactoryPostProcessors(beanFactory); 19 20 //注册各种 BeanPostProcessors,用于在bean被初始化时进行拦截,进行额外初始化操作 21 registerBeanPostProcessors(beanFactory); 22 23 //初始化MessageSource 24 initMessageSource(); 25 26 //初始化上下文事件广播 27 initApplicationEventMulticaster(); 28 29 //这是一个模板方法 30 onRefresh(); 31 32 //注册监听器 33 registerListeners(); 34 35 //初始化所有未初始化的非懒加载的单例Bean 36 finishBeanFactoryInitialization(beanFactory); 37 38 //发布事件通知 39 finishRefresh(); 40 } 41 42 catch (BeansException ex) { 43 if (logger.isWarnEnabled()) { 44 logger.warn("Exception encountered during context initialization - " + 45 "cancelling refresh attempt: " + ex); 46 } 47 48 // Destroy already created singletons to avoid dangling resources. 49 destroyBeans(); 50 51 // Reset 'active' flag. 52 cancelRefresh(ex); 53 54 // Propagate exception to caller. 55 throw ex; 56 } 57 58 finally { 59 // Reset common introspection caches in Spring's core, since we 60 // might not ever need metadata for singleton beans anymore... 61 resetCommonCaches(); 62 } 63 } 64 }
(1)prepareRefresh()刷新前的预处理;
1 /** 2 * Prepare this context for refreshing, setting its startup date and 3 * active flag as well as performing any initialization of property sources. 4 */ 5 protected void prepareRefresh() { 6 // Switch to active. 7 this.startupDate = System.currentTimeMillis(); 8 this.closed.set(false); 9 this.active.set(true); 10 11 if (logger.isDebugEnabled()) { 12 if (logger.isTraceEnabled()) { 13 logger.trace("Refreshing " + this); 14 } 15 else { 16 logger.debug("Refreshing " + getDisplayName()); 17 } 18 } 19 20 // 初始化一些属性设置;子类自定义个性化的属性设置方法; 21 initPropertySources(); 22 23 // Validate that all properties marked as required are resolvable: 24 // see ConfigurablePropertyResolver#setRequiredProperties 25 // 检验属性的合法等 26 getEnvironment().validateRequiredProperties(); 27 28 // 保存容器中的一些早期的事件; 29 if (this.earlyApplicationListeners == null) { 30 this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); 31 } 32 else { 33 // Reset local application listeners to pre-refresh state. 34 this.applicationListeners.clear(); 35 this.applicationListeners.addAll(this.earlyApplicationListeners); 36 } 37 38 // Allow for the collection of early ApplicationEvents, 39 // to be published once the multicaster is available... 40 this.earlyApplicationEvents = new LinkedHashSet<>(); 41 }
(2)obtainFreshBeanFactory(); 获取BeanFactory;
1 /** 2 * Tell the subclass to refresh the internal bean factory. 3 * @return the fresh BeanFactory instance 4 * @see #refreshBeanFactory() 5 * @see #getBeanFactory() 6 */ 7 protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { 8 refreshBeanFactory(); 9 return getBeanFactory(); 10 }
1 /** 2 * This implementation performs an actual refresh of this context's underlying 3 * bean factory, shutting down the previous bean factory (if any) and 4 * initializing a fresh bean factory for the next phase of the context's lifecycle. 5 */ 6 @Override 7 protected final void refreshBeanFactory() throws BeansException { 8 if (hasBeanFactory()) { 9 destroyBeans(); 10 closeBeanFactory(); 11 } 12 try { 13 DefaultListableBeanFactory beanFactory = createBeanFactory(); 14 beanFactory.setSerializationId(getId()); 15 customizeBeanFactory(beanFactory); 16 loadBeanDefinitions(beanFactory); 17 synchronized (this.beanFactoryMonitor) { 18 this.beanFactory = beanFactory; 19 } 20 } 21 catch (IOException ex) { 22 throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); 23 } 24 } 25 26 27 protected DefaultListableBeanFactory createBeanFactory() { 28 return new DefaultListableBeanFactory(getInternalParentBeanFactory()); 29 }
总结:创建BeanFactory[DefaultListableBeanFactory] 并返回
(3)prepareBeanFactory(beanFactory);BeanFactory的预准备工作(BeanFactory进行一些设置)
1 /** 2 * Configure the factory's standard context characteristics, 3 * such as the context's ClassLoader and post-processors. 4 * @param beanFactory the BeanFactory to configure 5 */ 6 protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { 7 // 设置BeanFactory的类加载器、支持表达式解析器... 8 beanFactory.setBeanClassLoader(getClassLoader()); 9 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); 10 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); 11 12 // 添加部分BeanPostProcessor【ApplicationContextAwareProcessor】 13 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); 14 //ignoreDependencyInterface:表示自动注入时忽略以下接口类型 15 beanFactory.ignoreDependencyInterface(EnvironmentAware.class); 16 beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); 17 beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); 18 beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); 19 beanFactory.ignoreDependencyInterface(MessageSourceAware.class); 20 beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); 21 22 // 注册可以解析的自动装配;我们能直接在任何组件中自动注入: 23 // BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext 24 beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); 25 beanFactory.registerResolvableDependency(ResourceLoader.class, this); 26 beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); 27 beanFactory.registerResolvableDependency(ApplicationContext.class, this); 28 29 // 添加BeanPostProcessor【ApplicationListenerDetector】 30 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); 31 32 // Detect a LoadTimeWeaver and prepare for weaving, if found. 33 // 添加编译时的AspectJ; 34 if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { 35 beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); 36 // Set a temporary ClassLoader for type matching. 37 beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); 38 } 39 40 // 给BeanFactory中注册一些能用的组件;environment【ConfigurableEnvironment】、systemProperties【Map<String, Object>】、systemEnvironment【Map<String, Object>】 41 if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { 42 beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); 43 } 44 if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { 45 beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); 46 } 47 if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { 48 beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); 49 } 50 }
(4)postProcessBeanFactory(beanFactory); BeanFactory准备工作完成后进行的后置处理工作;
1 /** 2 * Modify the application context's internal bean factory after its standard 3 * initialization. All bean definitions will have been loaded, but no beans 4 * will have been instantiated yet. This allows for registering special 5 * BeanPostProcessors etc in certain ApplicationContext implementations. 6 * @param beanFactory the bean factory used by the application context 7 */ 8 protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { 9 }
子类通过重写这个方法来在BeanFactory创建并预准备完成以后做进一步的设置
(5)invokeBeanFactoryPostProcessors(beanFactory);执行BeanFactoryPostProcessor的方法;
直接看代码:
1 public static void invokeBeanFactoryPostProcessors( 2 ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { 3 4 // Invoke BeanDefinitionRegistryPostProcessors first, if any. 5 Set<String> processedBeans = new HashSet<>(); 6 7 if (beanFactory instanceof BeanDefinitionRegistry) { 8 BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; 9 List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>(); 10 List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); 11 12 for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { 13 if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { 14 BeanDefinitionRegistryPostProcessor registryProcessor = 15 (BeanDefinitionRegistryPostProcessor) postProcessor; 16 registryProcessor.postProcessBeanDefinitionRegistry(registry); 17 registryProcessors.add(registryProcessor); 18 } 19 else { 20 regularPostProcessors.add(postProcessor); 21 } 22 } 23 24 // Do not initialize FactoryBeans here: We need to leave all regular beans 25 // uninitialized to let the bean factory post-processors apply to them! 26 // Separate between BeanDefinitionRegistryPostProcessors that implement 27 // PriorityOrdered, Ordered, and the rest. 28 List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>(); 29 30 // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered. 31 String[] postProcessorNames = 32 beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); 33 for (String ppName : postProcessorNames) { 34 if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { 35 currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); 36 processedBeans.add(ppName); 37 } 38 } 39 sortPostProcessors(currentRegistryProcessors, beanFactory); 40 registryProcessors.addAll(currentRegistryProcessors); 41 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); 42 currentRegistryProcessors.clear(); 43 44 // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. 45 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); 46 for (String ppName : postProcessorNames) { 47 if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { 48 currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); 49 processedBeans.add(ppName); 50 } 51 } 52 sortPostProcessors(currentRegistryProcessors, beanFactory); 53 registryProcessors.addAll(currentRegistryProcessors); 54 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); 55 currentRegistryProcessors.clear(); 56 57 // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. 58 boolean reiterate = true; 59 while (reiterate) { 60 reiterate = false; 61 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); 62 for (String ppName : postProcessorNames) { 63 if (!processedBeans.contains(ppName)) { 64 currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); 65 processedBeans.add(ppName); 66 reiterate = true; 67 } 68 } 69 sortPostProcessors(currentRegistryProcessors, beanFactory); 70 registryProcessors.addAll(currentRegistryProcessors); 71 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); 72 currentRegistryProcessors.clear(); 73 } 74 75 // Now, invoke the postProcessBeanFactory callback of all processors handled so far. 76 invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); 77 invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); 78 } 79 80 else { 81 // Invoke factory processors registered with the context instance. 82 invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); 83 } 84 85 // Do not initialize FactoryBeans here: We need to leave all regular beans 86 // uninitialized to let the bean factory post-processors apply to them! 87 String[] postProcessorNames = 88 beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); 89 90 // Separate between BeanFactoryPostProcessors that implement PriorityOrdered, 91 // Ordered, and the rest. 92 List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); 93 List<String> orderedPostProcessorNames = new ArrayList<>(); 94 List<String> nonOrderedPostProcessorNames = new ArrayList<>(); 95 for (String ppName : postProcessorNames) { 96 if (processedBeans.contains(ppName)) { 97 // skip - already processed in first phase above 98 } 99 else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { 100 priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); 101 } 102 else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { 103 orderedPostProcessorNames.add(ppName); 104 } 105 else { 106 nonOrderedPostProcessorNames.add(ppName); 107 } 108 } 109 110 // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. 111 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); 112 invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); 113 114 // Next, invoke the BeanFactoryPostProcessors that implement Ordered. 115 List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); 116 for (String postProcessorName : orderedPostProcessorNames) { 117 orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); 118 } 119 sortPostProcessors(orderedPostProcessors, beanFactory); 120 invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); 121 122 // Finally, invoke all other BeanFactoryPostProcessors. 123 List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); 124 for (String postProcessorName : nonOrderedPostProcessorNames) { 125 nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); 126 } 127 invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); 128 129 // Clear cached merged bean definitions since the post-processors might have 130 // modified the original metadata, e.g. replacing placeholders in values... 131 beanFactory.clearMetadataCache(); 132 }
梳理一下BeanFactoryPostProcessor的方法流程:
- 先执行BeanDefinitionRegistryPostProcessor
- 获取所有的BeanDefinitionRegistryPostProcessor;
- 先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor; postProcessor.postProcessBeanDefinitionRegistry(registry)
- 再执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor;
- 最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors;
- 再执行BeanFactoryPostProcessor的方法
- 获取所有的BeanFactoryPostProcessor
- 看先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor; postProcessor.postProcessBeanFactory()
- 在执行实现了Ordered顺序接口的BeanFactoryPostProcessor;
- 最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor;
(6)registerBeanPostProcessors(beanFactory);注册BeanPostProcessor(Bean的后置处理器)
将bean后置处理器实例化之后注册进beanFactory中,后续任何其他单实例bean实例化,初始化都会再次用到这些后置处理器的
1 public static void registerBeanPostProcessors( 2 ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { 3 4 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); 5 6 // Register BeanPostProcessorChecker that logs an info message when 7 // a bean is created during BeanPostProcessor instantiation, i.e. when 8 // a bean is not eligible for getting processed by all BeanPostProcessors. 9 int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; 10 beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); 11 12 // Separate between BeanPostProcessors that implement PriorityOrdered, 13 // Ordered, and the rest. 14 List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); 15 List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); 16 List<String> orderedPostProcessorNames = new ArrayList<>(); 17 List<String> nonOrderedPostProcessorNames = new ArrayList<>(); 18 for (String ppName : postProcessorNames) { 19 if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { 20 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); 21 priorityOrderedPostProcessors.add(pp); 22 if (pp instanceof MergedBeanDefinitionPostProcessor) { 23 internalPostProcessors.add(pp); 24 } 25 } 26 else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { 27 orderedPostProcessorNames.add(ppName); 28 } 29 else { 30 nonOrderedPostProcessorNames.add(ppName); 31 } 32 } 33 34 // First, register the BeanPostProcessors that implement PriorityOrdered. 35 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); 36 registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); 37 38 // Next, register the BeanPostProcessors that implement Ordered. 39 List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); 40 for (String ppName : orderedPostProcessorNames) { 41 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); 42 orderedPostProcessors.add(pp); 43 if (pp instanceof MergedBeanDefinitionPostProcessor) { 44 internalPostProcessors.add(pp); 45 } 46 } 47 sortPostProcessors(orderedPostProcessors, beanFactory); 48 registerBeanPostProcessors(beanFactory, orderedPostProcessors); 49 50 // Now, register all regular BeanPostProcessors. 51 List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); 52 for (String ppName : nonOrderedPostProcessorNames) { 53 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); 54 nonOrderedPostProcessors.add(pp); 55 if (pp instanceof MergedBeanDefinitionPostProcessor) { 56 internalPostProcessors.add(pp); 57 } 58 } 59 registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); 60 61 // Finally, re-register all internal BeanPostProcessors. 62 sortPostProcessors(internalPostProcessors, beanFactory); 63 registerBeanPostProcessors(beanFactory, internalPostProcessors); 64 65 // Re-register post-processor for detecting inner beans as ApplicationListeners, 66 // moving it to the end of the processor chain (for picking up proxies etc). 67 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); 68 }
流程梳理:获取所有BeanPostProcessor,按照PriorityOrdered、Ordered、无优先级的顺序注册到beanFactory中,最后再分别注册 MergedBeanDefinitionPostProcessor,ApplicationListenerDetector。
几个特别的BeanPostProcessor:
- DestructionAwareBeanPostProcessor
- InstantiationAwareBeanPostProcessor
- SmartInstantiationAwareBeanPostProcessor
- MergedBeanDefinitionPostProcessor【internalPostProcessors】
(7)initMessageSource();初始化MessageSource组件(做国际化功能;消息绑定,消息解析)
1 /** 2 * Initialize the MessageSource. 3 * Use parent's if none defined in this context. 4 */ 5 protected void initMessageSource() { 6 ConfigurableListableBeanFactory beanFactory = getBeanFactory(); 7 if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { 8 this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); 9 // Make MessageSource aware of parent MessageSource. 10 if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { 11 HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; 12 if (hms.getParentMessageSource() == null) { 13 // Only set parent context as parent MessageSource if no parent MessageSource 14 // registered already. 15 hms.setParentMessageSource(getInternalParentMessageSource()); 16 } 17 } 18 if (logger.isTraceEnabled()) { 19 logger.trace("Using MessageSource [" + this.messageSource + "]"); 20 } 21 } 22 else { 23 // Use empty MessageSource to be able to accept getMessage calls. 24 DelegatingMessageSource dms = new DelegatingMessageSource(); 25 dms.setParentMessageSource(getInternalParentMessageSource()); 26 this.messageSource = dms; 27 beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); 28 if (logger.isTraceEnabled()) { 29 logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]"); 30 } 31 } 32 }
(8)initApplicationEventMulticaster();初始化事件派发器;
事件派发器主要是用于ApplicationListener,spring容器的监听功能服务的。
spring监听功能的使用步骤:
- 写一个监听器(ApplicationListener实现类)来监听某个事件(ApplicationEvent及其子类):
- 写一个ApplicationListener的实现类放入容器中
- 使用@EventListener(原理:使用EventListenerMethodProcessor处理器来解析方法上的@EventListener)
- 容器发布相关事件:applicationContext.publishEvent();
1 /** 2 * 第一种发布ApplicationListener方法 3 */ 4 @Component 5 public class MyApplicationListener implements ApplicationListener<ApplicationEvent> { 6 7 //当容器中发布此事件以后,方法触发 8 @Override 9 public void onApplicationEvent(ApplicationEvent event) { 10 // TODO Auto-generated method stub 11 System.out.println("收到事件:"+event); 12 } 13 14 } 15 16 /** 17 * 第二种发布ApplicationListener方法 18 */ 19 @Service 20 public class UserService { 21 22 @EventListener(classes={ApplicationEvent.class}) 23 public void listen(ApplicationEvent event){ 24 System.out.println("UserService。。监听到的事件:"+event); 25 } 26 27 } 28 29 /** 30 * 事件发布 31 */ 32 public class IOCTest_Ext { 33 34 @Test 35 public void test01(){ 36 AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExtConfig.class); 37 38 39 //发布事件; 40 applicationContext.publishEvent(new ApplicationEvent(new String("我发布的时间")) { 41 }); 42 43 applicationContext.close(); 44 } 45 46 }
(9)onRefresh(); 留给子容器(子类)
子类重写这个方法,在容器刷新的时候可以自定义逻辑;
1 /** 2 * Template method which can be overridden to add context-specific refresh work. 3 * Called on initialization of special beans, before instantiation of singletons. 4 * <p>This implementation is empty. 5 * @throws BeansException in case of errors 6 * @see #refresh() 7 */ 8 protected void onRefresh() throws BeansException { 9 // For subclasses: do nothing by default. 10 }
(10)registerListeners();给容器中将所有项目里面的ApplicationListener注册进来;
1 /** 2 * Add beans that implement ApplicationListener as listeners. 3 * Doesn't affect other listeners, which can be added without being beans. 4 */ 5 protected void registerListeners() { 6 // Register statically specified listeners first. 7 for (ApplicationListener<?> listener : getApplicationListeners()) { 8 getApplicationEventMulticaster().addApplicationListener(listener); 9 } 10 11 // Do not initialize FactoryBeans here: We need to leave all regular beans 12 // uninitialized to let post-processors apply to them! 13 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); 14 for (String listenerBeanName : listenerBeanNames) { 15 getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); 16 } 17 18 // Publish early application events now that we finally have a multicaster... 19 Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; 20 this.earlyApplicationEvents = null; 21 if (earlyEventsToProcess != null) { 22 for (ApplicationEvent earlyEvent : earlyEventsToProcess) { 23 getApplicationEventMulticaster().multicastEvent(earlyEvent); 24 } 25 } 26 }
(11)finishBeanFactoryInitialization(beanFactory);初始化所有剩下的单实例bean;
介绍了单实例bean的实例化——初始化的整个过程
populateBean、initializeBean源码:
1 /** 2 * Populate the bean instance in the given BeanWrapper with the property values 3 * from the bean definition. 4 * @param beanName the name of the bean 5 * @param mbd the bean definition for the bean 6 * @param bw the BeanWrapper with bean instance 7 */ 8 @SuppressWarnings("deprecation") // for postProcessPropertyValues 9 protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { 10 if (bw == null) { 11 if (mbd.hasPropertyValues()) { 12 throw new BeanCreationException( 13 mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); 14 } 15 else { 16 // Skip property population phase for null instance. 17 return; 18 } 19 } 20 21 // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the 22 // state of the bean before properties are set. This can be used, for example, 23 // to support styles of field injection. 24 boolean continueWithPropertyPopulation = true; 25 26 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { 27 for (BeanPostProcessor bp : getBeanPostProcessors()) { 28 if (bp instanceof InstantiationAwareBeanPostProcessor) { 29 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; 30 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { 31 continueWithPropertyPopulation = false; 32 break; 33 } 34 } 35 } 36 } 37 38 if (!continueWithPropertyPopulation) { 39 return; 40 } 41 42 PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); 43 44 int resolvedAutowireMode = mbd.getResolvedAutowireMode(); 45 if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { 46 MutablePropertyValues newPvs = new MutablePropertyValues(pvs); 47 // Add property values based on autowire by name if applicable. 48 if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { 49 autowireByName(beanName, mbd, bw, newPvs); 50 } 51 // Add property values based on autowire by type if applicable. 52 if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { 53 autowireByType(beanName, mbd, bw, newPvs); 54 } 55 pvs = newPvs; 56 } 57 58 boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); 59 boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); 60 61 PropertyDescriptor[] filteredPds = null; 62 if (hasInstAwareBpps) { 63 if (pvs == null) { 64 pvs = mbd.getPropertyValues(); 65 } 66 for (BeanPostProcessor bp : getBeanPostProcessors()) { 67 if (bp instanceof InstantiationAwareBeanPostProcessor) { 68 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; 69 PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); 70 if (pvsToUse == null) { 71 if (filteredPds == null) { 72 filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); 73 } 74 pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); 75 if (pvsToUse == null) { 76 return; 77 } 78 } 79 pvs = pvsToUse; 80 } 81 } 82 } 83 if (needsDepCheck) { 84 if (filteredPds == null) { 85 filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); 86 } 87 checkDependencies(beanName, mbd, filteredPds, pvs); 88 } 89 90 if (pvs != null) { 91 applyPropertyValues(beanName, mbd, bw, pvs); 92 } 93 } 94 95 96 /** 97 * Initialize the given bean instance, applying factory callbacks 98 * as well as init methods and bean post processors. 99 * <p>Called from {@link #createBean} for traditionally defined beans, 100 * and from {@link #initializeBean} for existing bean instances. 101 * @param beanName the bean name in the factory (for debugging purposes) 102 * @param bean the new bean instance we may need to initialize 103 * @param mbd the bean definition that the bean was created with 104 * (can also be {@code null}, if given an existing bean instance) 105 * @return the initialized bean instance (potentially wrapped) 106 * @see BeanNameAware 107 * @see BeanClassLoaderAware 108 * @see BeanFactoryAware 109 * @see #applyBeanPostProcessorsBeforeInitialization 110 * @see #invokeInitMethods 111 * @see #applyBeanPostProcessorsAfterInitialization 112 */ 113 protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) { 114 if (System.getSecurityManager() != null) { 115 AccessController.doPrivileged((PrivilegedAction<Object>) () -> { 116 invokeAwareMethods(beanName, bean); 117 return null; 118 }, getAccessControlContext()); 119 } 120 else { 121 invokeAwareMethods(beanName, bean); 122 } 123 124 Object wrappedBean = bean; 125 if (mbd == null || !mbd.isSynthetic()) { 126 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); 127 } 128 129 try { 130 invokeInitMethods(beanName, wrappedBean, mbd); 131 } 132 catch (Throwable ex) { 133 throw new BeanCreationException( 134 (mbd != null ? mbd.getResourceDescription() : null), 135 beanName, "Invocation of init method failed", ex); 136 } 137 if (mbd == null || !mbd.isSynthetic()) { 138 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); 139 } 140 141 return wrappedBean; 142 }
总结下:在bean创建过程中会以此出现几个“拦路虎”接口:InstantiationAwareBeanPostProcessor、MergedBeanDefinitionPostProcessor、xxxAware接口的方法 BeanNameAwareBeanClassLoaderAwareBeanFactoryAware 、BeanPostProcessor、SmartInitializingSingleton ,这些“拦路虎”接口就是spring预留的bean创建过程中的钩子接口,正是这些钩子接口为那些依赖spring的框架或者组件化开发提供了便利。
(12)finishRefresh();完成BeanFactory的初始化创建工作;IOC容器就创建完成;
1 /** 2 * Finish the refresh of this context, invoking the LifecycleProcessor's 3 * onRefresh() method and publishing the 4 * {@link org.springframework.context.event.ContextRefreshedEvent}. 5 */ 6 protected void finishRefresh() { 7 // Clear context-level resource caches (such as ASM metadata from scanning). 8 clearResourceCaches(); 9 10 // 初始化和生命周期有关的后置处理器;LifecycleProcessor 11 // 默认从容器中找是否有lifecycleProcessor的组件【LifecycleProcessor】;如果没有new DefaultLifecycleProcessor();加入到容器; 12 initLifecycleProcessor(); 13 14 // Propagate refresh to lifecycle processor first. 15 getLifecycleProcessor().onRefresh(); 16 17 // 发布容器刷新完成事件; 18 publishEvent(new ContextRefreshedEvent(this)); 19 20 // Participate in LiveBeansView MBean, if active. 21 LiveBeansView.registerApplicationContext(this); 22 }