// 自身定义@NullableprivatestaticClass<?> javaxInjectProviderClass;
static {
try {
javaxInjectProviderClass =ClassUtils.forName("javax.inject.Provider", DefaultListableBeanFactory.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - Provider interface simply not supported then.
javaxInjectProviderClass = null;
}
}
/** Map from serialized id to factory instance. */privatestaticfinalMap<String, Reference<DefaultListableBeanFactory>> serializableFactories =
new ConcurrentHashMap<>(8);
/** Optional id for this factory, for serialization purposes. */@NullableprivateString serializationId;
/** Whether to allow re-registration of a different definition with the same name. */private boolean allowBeanDefinitionOverriding =true;
/** Whether to allow eager class loading even for lazy-init beans. */private boolean allowEagerClassLoading =true;
/** Optional OrderComparator for dependency Lists and arrays. */@NullableprivateComparator<Object> dependencyComparator;
/** Resolver to use for checking if a bean definition is an autowire candidate. */privateAutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver();
/** Map from dependency type to corresponding autowired value. */privatefinalMap<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);
/** Map of bean definition objects, keyed by bean name. */privatefinalMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
/** Map of singleton and non-singleton bean names, keyed by dependency type. */privatefinalMap<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);
/** Map of singleton-only bean names, keyed by dependency type. */privatefinalMap<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);
/** List of bean definition names, in registration order. */private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
///** List of names of manually registered singletons, in registration order. */private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);
/** Cached array of bean definition names in case of frozen configuration. */@Nullableprivate volatile String[] frozenBeanDefinitionNames;
/** Whether bean definition metadata may be cached for all beans. */private volatile boolean configurationFrozen =false;
//继承自AbstractAutowireCapableBeanFactory/** Strategy for creating bean instances. */privateInstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
/** Resolver strategy for method parameter names. */@NullableprivateParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
/** Whether to automatically try to resolve circular references between beans. */private boolean allowCircularReferences =true;
/**
* Whether to resort to injecting a raw bean instance in case of circular reference,
* even if the injected bean eventually got wrapped.
*/private boolean allowRawInjectionDespiteWrapping =false;
/**
* Dependency types to ignore on dependency check and autowire, as Set of
* Class objects: for example, String. Default is none.
*/privatefinalSet<Class<?>> ignoredDependencyTypes = new HashSet<>();
/**
* Dependency interfaces to ignore on dependency check and autowire, as Set of
* Class objects. By default, only the BeanFactory interface is ignored.
*/privatefinalSet<Class<?>> ignoredDependencyInterfaces = new HashSet<>();
/**
* The name of the currently created bean, for implicit dependency registration
* on getBean etc invocations triggered from a user-specified Supplier callback.
*/privatefinalNamedThreadLocal<String> currentlyCreatedBean = new NamedThreadLocal<>("Currently created bean");
/** Cache of unfinished FactoryBean instances: FactoryBean name to BeanWrapper. */privatefinalConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>();
/** Cache of candidate factory methods per factory class. */privatefinalConcurrentMap<Class<?>, Method[]> factoryMethodCandidateCache = new ConcurrentHashMap<>();
/** Cache of filtered PropertyDescriptors: bean Class to PropertyDescriptor array. */privatefinalConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache =
new ConcurrentHashMap<>();
//继承自AbstractBeanFactory/** Parent bean factory, for bean inheritance support. */@NullableprivateBeanFactory parentBeanFactory;
/** ClassLoader to resolve bean class names with, if necessary. */@NullableprivateClassLoader beanClassLoader =ClassUtils.getDefaultClassLoader();
/** ClassLoader to temporarily resolve bean class names with, if necessary. */@NullableprivateClassLoader tempClassLoader;
/** Whether to cache bean metadata or rather reobtain it for every access. */private boolean cacheBeanMetadata =true;
/** Resolution strategy for expressions in bean definition values. */@NullableprivateBeanExpressionResolver beanExpressionResolver;
/** Spring ConversionService to use instead of PropertyEditors. */@NullableprivateConversionService conversionService;
/** Custom PropertyEditorRegistrars to apply to the beans of this factory. */privatefinalSet<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<>(4);
/** Custom PropertyEditors to apply to the beans of this factory. */privatefinalMap<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>(4);
/** A custom TypeConverter to use, overriding the default PropertyEditor mechanism. */@NullableprivateTypeConverter typeConverter;
/** String resolvers to apply e.g. to annotation attribute values. */privatefinalList<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList<>();
/** BeanPostProcessors to apply in createBean. */privatefinalList<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();
/** Indicates whether any InstantiationAwareBeanPostProcessors have been registered. */private volatile boolean hasInstantiationAwareBeanPostProcessors;
/** Indicates whether any DestructionAwareBeanPostProcessors have been registered. */private volatile boolean hasDestructionAwareBeanPostProcessors;
/** Map from scope identifier String to corresponding Scope. */privatefinalMap<String, Scope> scopes = new LinkedHashMap<>(8);
/** Security context used when running with a SecurityManager. */@NullableprivateSecurityContextProvider securityContextProvider;
/** Map from bean name to merged RootBeanDefinition. */privatefinalMap<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256);
/** Names of beans that have already been created at least once. */privatefinalSet<String> alreadyCreated =Collections.newSetFromMap(new ConcurrentHashMap<>(256));
/** Names of beans that are currently in creation. */privatefinalThreadLocal<Object> prototypesCurrentlyInCreation =
new NamedThreadLocal<>("Prototype beans currently in creation");
//继承自FactoryBeanRegistrySupport/** Cache of singleton objects created by FactoryBeans: FactoryBean name to object. */privatefinalMap<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);
//继承自DefaultSingletonBeanRegistry/** Cache of singleton objects: bean name to bean instance. */privatefinalMap<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */privatefinalMap<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */privatefinalMap<String, Object> earlySingletonObjects = new HashMap<>(16);
/** Set of registered singletons, containing the bean names in registration order. */privatefinalSet<String> registeredSingletons = new LinkedHashSet<>(256);
/** Names of beans that are currently in creation. */privatefinalSet<String> singletonsCurrentlyInCreation =Collections.newSetFromMap(new ConcurrentHashMap<>(16));
/** Names of beans currently excluded from in creation checks. */privatefinalSet<String> inCreationCheckExclusions =Collections.newSetFromMap(new ConcurrentHashMap<>(16));
/** List of suppressed Exceptions, available for associating related causes. */@NullableprivateSet<Exception> suppressedExceptions;
/** Flag that indicates whether we're currently within destroySingletons. */private boolean singletonsCurrentlyInDestruction =false;
/** Disposable bean instances: bean name to disposable instance. */privatefinalMap<String, Object> disposableBeans = new LinkedHashMap<>();
/** Map between containing bean names: bean name to Set of bean names that the bean contains. */privatefinalMap<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);
/** Map between dependent bean names: bean name to Set of dependent bean names. */privatefinalMap<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);
/** Map between depending bean names: bean name to Set of bean names for the bean's dependencies. */privatefinalMap<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);
//继承自SimpleAliasRegistry/** Map from alias to canonical name. */privatefinalMap<String, String> aliasMap = new ConcurrentHashMap<>(16);
构造方法的调用
//SpringBoot的启动方法run方法中,创建AnnotationConfigServletWebServerApplicationContext过程中初始化,实际由父类GenericApplicationContext类创建//递归调用父类的构造函数
public DefaultListableBeanFactory() {
super();
}
//手动添加自动装配过程中排除实现了特定接口的类
public AbstractAutowireCapableBeanFactory() {
super();
ignoreDependencyInterface(BeanNameAware.class);
ignoreDependencyInterface(BeanFactoryAware.class);
ignoreDependencyInterface(BeanClassLoaderAware.class);
}
单例注册方法
//由实例自己调用注册自己public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
super.registerSingleton(beanName, singletonObject);
//用来判断当前启动的时机if (hasBeanCreationStarted()) {
// 看似都是往手动添加的单例集合末尾添加元素,但操作不同,给出的理由很有意思:固定启动时的集合避免修改// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
if (!this.beanDefinitionMap.containsKey(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames.size() + 1);
updatedSingletons.addAll(this.manualSingletonNames);
updatedSingletons.add(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
// Still in startup registration phaseif (!this.beanDefinitionMap.containsKey(beanName)) {
this.manualSingletonNames.add(beanName);
}
}
clearByTypeCache();
}
//父类实现,主要是检查,锁定并调用添加方法public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
Assert.notNull(beanName, "Bean name must not be null");
Assert.notNull(singletonObject, "Singleton object must not be null");
synchronized (this.singletonObjects) {
Object oldObject = this.singletonObjects.get(beanName);
if (oldObject != null) {
throw new IllegalStateException("Could not register object [" + singletonObject +
"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
}
addSingleton(beanName, singletonObject);
}
}
//核心方法,可以看到注入一个完成单例的时候需要基于双重检查锁,同时消除2级缓存和三级缓存的信息protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
beanDefinition注册
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
//AbstractBeanDefinition的实现需要做早期校验if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
//如果map中已经存在同名的情况下的处理逻辑
BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
if (existingDefinition != null) {
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
}
elseif (existingDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTUREif (logger.isInfoEnabled()) {
logger.info("Overriding user-defined bean definition for bean '" + beanName +
"' with a framework-generated bean definition: replacing [" +
existingDefinition + "] with [" + beanDefinition + "]");
}
}
//这里还要判断一次是否equalelseif (!beanDefinition.equals(existingDefinition)) {
if (logger.isDebugEnabled()) {
logger.debug("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
//启动周期判断if (hasBeanCreationStarted()) {
//和之前方法一样,选择新构建一个list记录updatedDefinitions// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
if (this.manualSingletonNames.contains(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
updatedSingletons.remove(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
// Still in startup registration phasethis.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
this.manualSingletonNames.remove(beanName);
}
this.frozenBeanDefinitionNames = null;
}
if (existingDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用