Spring框架原理深度源码级解析

Spring框架原理深度源码级解析

本文将从源码级别深入剖析Spring框架的核心原理,包括IoC容器实现机制、Bean生命周期完整过程、AOP底层实现机制等关键内容,帮助你彻底理解Spring的工作原理。

一、IoC容器深度源码解析

1. IoC容器架构设计

Spring IoC容器基于两个核心接口构建:

BeanFactory接口 - 基础容器
java 复制代码
public interface BeanFactory {
    Object getBean(String name) throws BeansException;
    <T> T getBean(String name, Class<T> requiredType) throws BeansException;
    boolean containsBean(String name);
    boolean isSingleton(String name);
    boolean isPrototype(String name);
    boolean isTypeMatch(String name, Class<?> targetType);
    Class<?> getType(String name);
    String[] getAliases(String name);
}
ApplicationContext接口 - 高级容器
java 复制代码
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
        MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
    // 扩展了BeanFactory,提供更多企业级特性
}

2. IoC容器初始化源码分析

容器初始化的核心是AbstractApplicationContext类的refresh()方法,这是Spring容器启动的关键入口2:

java 复制代码
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // 1. 准备刷新上下文环境
        prepareRefresh();
        
        // 2. 获取告诉子类初始化BeanFactory,解析XML/注解配置
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
        
        // 3. 对BeanFactory进行功能扩展(如设置类加载器、表达式解析器等)
        prepareBeanFactory(beanFactory);
        
        try {
            // 4. 允许子类对BeanFactory进行后置处理
            postProcessBeanFactory(beanFactory);
            
            // 5. 调用BeanFactoryPostProcessor的方法(如属性占位符处理)
            invokeBeanFactoryPostProcessors(beanFactory);
            
            // 6. 注册BeanPostProcessor
            registerBeanPostProcessors(beanFactory);
            
            // 7. 初始化MessageSource(国际化支持)
            initMessageSource();
            
            // 8. 初始化事件多播器
            initApplicationEventMulticaster();
            
            // 9. 子类重写该方法进行特定上下文的初始化
            onRefresh();
            
            // 10. 注册事件监听器
            registerListeners();
            
            // 11. 初始化所有剩余的单例Bean
            finishBeanFactoryInitialization(beanFactory);
            
            // 12. 完成刷新,发布容器刷新完成事件
            finishRefresh();
        } catch (BeansException ex) {
            // 异常处理
            destroyBeans();
            cancelRefresh(ex);
            throw ex;
        }
    }
}

3. BeanDefinition解析过程

Spring通过BeanDefinition接口抽象描述Bean的元数据5:

java 复制代码
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {
    // Bean作用域
    void setScope(String scope);
    String getScope();
    
    // 是否是抽象Bean
    boolean isAbstract();
    void setAbstract(boolean abstractFlag);
    
    // 懒加载
    boolean isLazyInit();
    void setLazyInit(boolean lazyInit);
    
    // 依赖关系
    String[] getDependsOn();
    void setDependsOn(String... dependsOn);
    
    // 构造函数参数和属性值
    ConstructorArgumentValues getConstructorArgumentValues();
    MutablePropertyValues getPropertyValues();
    
    // 其他元数据
}

BeanDefinition的解析过程主要包括:

  1. 资源定位:通过ResourceLoader加载配置文件或扫描注解
  2. 解析:使用BeanDefinitionReader解析配置,生成BeanDefinition
  3. 注册:将BeanDefinition注册到BeanDefinitionRegistry

4. 依赖注入(DI)源码实现

依赖注入的核心逻辑在DefaultListableBeanFactoryresolveDependency方法中:

java 复制代码
public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName, 
        Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
    // 1. 处理@Value注解
    Object result = getAutowireCandidateResolver().getSuggestedValue(descriptor);
    if (result != null) {
        return evaluateBeanDefinitionString(result, descriptor.getDependencyType());
    }
    
    // 2. 按类型查找匹配的Bean
    Map<String, Object> matchingBeans = findAutowireCandidates(requestingBeanName, 
            descriptor.getDependencyType(), descriptor);
    
    // 3. 处理歧义情况(如多个实现类)
    if (matchingBeans.isEmpty()) {
        // 处理required=true的情况,抛出异常
    }
    
    // 4. 选择合适的Bean(处理@Primary等)
    String autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
    
    // 5. 返回依赖对象
    return matchingBeans.get(autowiredBeanName);
}

二、Bean生命周期完整解析

1. Bean生命周期完整流程图

Bean的生命周期从创建到销毁,经历了以下关键阶段:

  1. BeanDefinition注册:将Bean的元数据信息注册到容器
  2. 实例化:通过反射创建Bean实例
  3. 属性注入:设置Bean的属性值和依赖
  4. 初始化前处理:BeanPostProcessor的前置处理
  5. 初始化回调:各种初始化方法的调用
  6. 初始化后处理:BeanPostProcessor的后置处理
  7. 就绪使用:Bean可以被应用程序使用
  8. 销毁前处理:容器关闭时的处理

2. Bean实例化源码分析

Bean实例化的核心方法在AbstractAutowireCapableBeanFactory中:

java 复制代码
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) 
        throws BeanCreationException {
    RootBeanDefinition mbdToUse = mbd;
    
    // 1. 解析Bean的Class
    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }
    
    // 2. 准备方法重写(CGLIB增强)
    try {
        mbdToUse.prepareMethodOverrides();
    }
    
    // 3. 实例化前的后置处理器
    Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
    if (bean != null) {
        return bean;
    }
    
    // 4. 创建Bean实例
    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
    return beanInstance;
}

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) 
        throws BeanCreationException {
    // 1. 创建Bean实例
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    
    // 2. 提前曝光单例(解决循环依赖)
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
            isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }
    
    // 3. 初始化Bean实例
    Object exposedObject = bean;
    try {
        // 3.1 属性注入
        populateBean(beanName, mbd, instanceWrapper);
        // 3.2 初始化
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    
    // 4. 处理循环依赖
    if (earlySingletonExposure) {
        Object earlySingletonReference = getSingleton(beanName, false);
        // ...处理循环引用逻辑
    }
    
    // 5. 注册DisposableBean(用于销毁)
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    
    return exposedObject;
}

3. 属性注入源码解析

属性注入的核心逻辑在populateBean方法中:

java 复制代码
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    // 获取属性值
    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
    
    // 处理自动注入(byName或byType)
    int resolvedAutowireMode = mbd.getResolvedAutowireMode();
    if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
        
        // 按名称自动注入
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
            autowireByName(beanName, mbd, bw, newPvs);
        }
        // 按类型自动注入
        if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
            autowireByType(beanName, mbd, bw, newPvs);
        }
        pvs = newPvs;
    }
    
    // 应用BeanPostProcessor进行属性注入前处理
    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    boolean needsDepCheck = (mbd.getDependencyCheck() != DependencyDescriptor.INJECTED_OBJECT_NOT_FOUND);
    
    // 应用InstantiationAwareBeanPostProcessor处理属性
    PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {
                    filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                    pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        return;
                    }
                }
                pvs = pvsToUse;
            }
        }
    }
    
    // 应用属性值到Bean实例
    if (pvs != null) {
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

4. Bean初始化过程详解

初始化过程在initializeBean方法中实现:

java 复制代码
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    // 1. 激活Aware接口回调
    invokeAwareMethods(beanName, bean);
    
    // 2. 应用BeanPostProcessor的前置处理
    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }
    
    // 3. 调用初始化方法
    try {
        invokeInitMethods(beanName, wrappedBean, mbd);
    } catch (Throwable ex) {
        throw new BeanCreationException(
                (mbd != null ? mbd.getResourceDescription() : null),
                beanName, "Invocation of init method failed", ex);
    }
    
    // 4. 应用BeanPostProcessor的后置处理
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
    
    return wrappedBean;
}

protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd) 
        throws Throwable {
    // 1. 先调用InitializingBean接口的afterPropertiesSet方法
    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        ((InitializingBean) bean).afterPropertiesSet();
    }
    
    // 2. 再调用自定义的init-method
    if (mbd != null && bean.getClass() != NullBean.class) {
        String initMethodName = mbd.getInitMethodName();
        if (StringUtils.hasLength(initMethodName) &&
                !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}

三、AOP深度源码解析

1. AOP核心概念与设计

AOP的核心组件包括:

java 复制代码
// 切面接口
public interface Aspect {
    // 定义切面相关的信息
}

// 通知接口
public interface Advice {
    // 通知是切面的具体实现
}

// 切入点接口
public interface Pointcut {
    ClassFilter getClassFilter();
    MethodMatcher getMethodMatcher();
}

// 顾问接口,组合了切入点和通知
public interface Advisor {
    Advice getAdvice();
    boolean isPerInstance();
}

2. AOP代理创建机制

Spring AOP的核心代理创建逻辑在DefaultAopProxyFactory中:

java 复制代码
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    // 决定使用JDK动态代理还是CGLIB代理
    if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
        Class<?> targetClass = config.getTargetClass();
        if (targetClass == null) {
            throw new AopConfigException("TargetSource cannot determine target class: " +
                    "Either an interface or a target is required for proxy creation.");
        }
        // 如果目标类是接口或代理类本身,使用JDK动态代理
        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
            return new JdkDynamicAopProxy(config);
        }
        // 否则使用CGLIB代理
        return new ObjenesisCglibAopProxy(config);
    } else {
        // 默认使用JDK动态代理
        return new JdkDynamicAopProxy(config);
    }
}

3. JDK动态代理源码分析

JDK动态代理的核心实现在JdkDynamicAopProxy中:

java 复制代码
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {
    private final AdvisedSupport advised;
    
    @Override
    public Object getProxy() {
        return getProxy(ClassUtils.getDefaultClassLoader());
    }
    
    @Override
    public Object getProxy(@Nullable ClassLoader classLoader) {
        // 获取目标类实现的所有接口
        Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
        findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
        // 创建JDK动态代理实例
        return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MethodInvocation invocation;
        Object oldProxy = null;
        boolean setProxyContext = false;
        
        TargetSource targetSource = this.advised.targetSource;
        Object target = null;
        
        try {
            // 处理Object类的方法
            if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
                return equals(args[0]);
            }
            else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
                return hashCode();
            }
            else if (method.getDeclaringClass() == DecoratingProxy.class) {
                return AopProxyUtils.ultimateTargetClass(this.advised);
            }
            else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
                    method.getDeclaringClass().isAssignableFrom(Advised.class)) {
                return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
            }
            
            Object retVal;
            
            // 设置代理上下文(如果需要)
            if (this.advised.exposeProxy) {
                oldProxy = AopContext.setCurrentProxy(proxy);
                setProxyContext = true;
            }
            
            // 获取目标对象
            target = targetSource.getTarget();
            Class<?> targetClass = (target != null ? target.getClass() : null);
            
            // 获取适合此方法的拦截器链
            List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
            
            // 如果没有拦截器,直接调用目标方法
            if (chain.isEmpty()) {
                Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
                retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
            }
            else {
                // 创建方法调用
                invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
                // 执行拦截器链
                retVal = invocation.proceed();
            }
            
            // 处理返回值
            Class<?> returnType = method.getReturnType();
            if (retVal != null && retVal == target && returnType != Object.class &&
                    returnType.isInstance(proxy) && !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
                retVal = proxy;
            }
            return retVal;
        }
        finally {
            if (target != null && !targetSource.isStatic()) {
                targetSource.releaseTarget(target);
            }
            if (setProxyContext) {
                AopContext.setCurrentProxy(oldProxy);
            }
        }
    }
}

4. CGLIB代理源码分析

CGLIB代理的核心实现在CglibAopProxy中:

java 复制代码
public class CglibAopProxy implements AopProxy {
    private final AdvisedSupport advised;
    
    @Override
    public Object getProxy(@Nullable ClassLoader classLoader) {
        // 创建Enhancer实例
        Enhancer enhancer = createEnhancer();
        if (classLoader != null) {
            enhancer.setClassLoader(classLoader);
            if (classLoader instanceof SmartClassLoader &&
                    ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
                enhancer.setUseCache(false);
            }
        }
        
        // 设置父类和接口
        enhancer.setSuperclass(proxySuperClass);
        enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
        enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));
        
        // 创建回调
        Callback[] callbacks = getCallbacks(rootClass);
        enhancer.setCallbacks(callbacks);
        enhancer.setCallbackFilter(new ProxyCallbackFilter(
                this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
        
        // 创建代理实例
        return createProxyClassAndInstance(enhancer, callbacks);
    }
    
    // 内部类MethodInterceptor实现了CGLIB的MethodInterceptor接口
    private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable {
        private final AdvisedSupport advised;
        
        @Override
        public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
            Object oldProxy = null;
            boolean setProxyContext = false;
            Object target = null;
            TargetSource targetSource = this.advised.getTargetSource();
            try {
                // 类似JDK动态代理的逻辑
                // 设置代理上下文
                if (this.advised.exposeProxy) {
                    oldProxy = AopContext.setCurrentProxy(proxy);
                    setProxyContext = true;
                }
                
                // 获取目标对象
                target = targetSource.getTarget();
                Class<?> targetClass = (target != null ? target.getClass() : null);
                
                // 获取拦截器链
                List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
                Object retVal;
                
                // 执行拦截器链或直接调用目标方法
                if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
                    retVal = methodProxy.invoke(target, args);
                }
                else {
                    retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
                }
                
                return retVal;
            }
            finally {
                // 清理工作
                if (target != null && !targetSource.isStatic()) {
                    targetSource.releaseTarget(target);
                }
                if (setProxyContext) {
                    AopContext.setCurrentProxy(oldProxy);
                }
            }
        }
    }
}

5. 通知执行机制

通知执行的核心逻辑在ReflectiveMethodInvocation类的proceed方法中:

java 复制代码
public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {
    protected final Object proxy;
    @Nullable
    protected final Object target;
    protected final Method method;
    protected Object[] arguments;
    @Nullable
    private final Class<?> targetClass;
    protected final List<Object> interceptorsAndDynamicMethodMatchers;
    private int currentInterceptorIndex = -1;
    
    @Override
    public Object proceed() throws Throwable {
        // 执行到了最后一个拦截器,直接调用目标方法
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
            return invokeJoinpoint();
        }
        
        // 获取下一个拦截器
        Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
        
        // 如果是动态方法匹配器,需要判断是否匹配
        if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
            InterceptorAndDynamicMethodMatcher dm = (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
            Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
            if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
                return dm.interceptor.invoke(this);
            } else {
                // 不匹配,跳过此拦截器
                return proceed();
            }
        } else {
            // 静态拦截器,直接执行
            return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
        }
    }
    
    protected Object invokeJoinpoint() throws Throwable {
        return AopUtils.invokeJoinpointUsingReflection(this.target, this.method, this.arguments);
    }
}

四、Spring核心扩展点

1. BeanPostProcessor详解

BeanPostProcessor是Spring最强大的扩展点之一,允许在Bean初始化前后进行自定义处理:

java 复制代码
public interface BeanPostProcessor {
    // Bean初始化前调用
    @Nullable
    default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
    
    // Bean初始化后调用
    @Nullable
    default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

常见的实现类包括:

  • AutowiredAnnotationBeanPostProcessor:处理@Autowired注解
  • RequiredAnnotationBeanPostProcessor:处理@Required注解
  • AnnotationAwareAspectJAutoProxyCreator:创建AOP代理

2. BeanFactoryPostProcessor详解

BeanFactoryPostProcessor允许在容器实例化Bean之前修改Bean的定义信息:

java 复制代码
public interface BeanFactoryPostProcessor {
    // 在BeanFactory加载完所有Bean定义但未实例化Bean之前调用
    void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}

常见的实现类包括:

  • PropertySourcesPlaceholderConfigurer:处理属性占位符
  • ConfigurationClassPostProcessor:处理@Configuration类

3. FactoryBean详解

FactoryBean是一个特殊的Bean,可以用来创建复杂的Bean:

java 复制代码
public interface FactoryBean<T> {
    // 获取由FactoryBean创建的Bean实例
    @Nullable
    T getObject() throws Exception;
    
    // 获取FactoryBean创建的Bean的类型
    @Nullable
    Class<?> getObjectType();
    
    // 是单例吗
    default boolean isSingleton() {
        return true;
    }
}

常见的实现类包括:

  • ProxyFactoryBean:创建AOP代理
  • JndiObjectFactoryBean:从JNDI获取对象

五、Spring框架设计思想与最佳实践

1. 依赖倒置原则在Spring中的体现

Spring的IoC容器完美体现了依赖倒置原则3:

  • 高层模块不依赖低层模块的具体实现
  • 高层模块和低层模块都依赖抽象
  • 抽象不依赖细节
  • 细节依赖抽象

2. 循环依赖问题解决机制

Spring通过三级缓存机制解决循环依赖问题:

java 复制代码
// DefaultSingletonBeanRegistry中的三级缓存
// 一级缓存:存储已初始化完成的单例Bean
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

// 二级缓存:存储早期暴露的Bean引用(已创建实例但未完成初始化)
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);

// 三级缓存:存储Bean工厂函数,用于提前暴露Bean
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

// 添加单例工厂函数
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
    Assert.notNull(singletonFactory, "Singleton factory must not be null");
    synchronized (this.singletonObjects) {
        if (!this.singletonObjects.containsKey(beanName)) {
            this.singletonFactories.put(beanName, singletonFactory);
            this.earlySingletonObjects.remove(beanName);
            this.registeredSingletons.add(beanName);
        }
    }
}

总结

Spring框架通过IoC和AOP两大核心机制,实现了对象管理和横切关注点的解耦。从源码层面来看,Spring的设计非常优雅,通过大量的抽象和扩展点,既保证了框架的灵活性,又提供了丰富的功能支持。

深入理解Spring的这些核心原理,不仅有助于我们更好地使用Spring框架,也能让我们在设计自己的应用时,借鉴这些优秀的设计思想和模式,提升代码质量和可维护性。

相关推荐
回忆是昨天里的海2 小时前
k8s安装-kubeadm join,将工作节点加入k8s集群
java·服务器·kubernetes
yinke小琪2 小时前
谈谈项目中单点登录的实现原理
java·后端
浪飘3 小时前
k8s device plugin
java·docker·kubernetes
brzhang3 小时前
我且问你,如果有人用 AI 抄你的产品,爱卿又当如何应对?
前端·后端·架构
渣哥3 小时前
面试必问:Spring Bean 的作用域类型有多少种?
javascript·后端·面试
一只游鱼3 小时前
maven简介与安装
java·maven
KIKIiiiiiiii3 小时前
微信个人号开发中如何高效实现API二次开发
java·前端·python·微信
胡八一3 小时前
30 分钟上手 exp4j:在 Java 中安全、灵活地计算数学表达式
java·开发语言·安全