Spring IOC 原理

本文深入探讨了Spring框架中Bean的注入过程,包括组件扫描、Bean定义的存储、实例化及自定义BeanFactoryPostProcessor的使用。通过示例代码展示了如何手动修改Bean的类型,实现OrderService的注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-- 笔记

package com.hang.rpc.spring;

import com.hang.rpc.business.OrderService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.stereotype.Component;

/**
 * BeanFactoryPostProcessor bean 工厂后置处理器
 *
 * spring 注解注入原理
 * 1.spring 会扫描 ComponentScan (具体通过 ClassPathBeanDefinitionServer 这个对象完成的) 指定包下符合的类(包含@Component注解的类)
 * 2.然后将类信息封装到 DefaultListableBeanFactory 类的 map属性中,Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap(256);
 * 3.key 就是 @Component 类名小写
 * 4.value 就是 BeanDefinition 的子类 GenericBeanDefinition
 * 5.GenericBeanDefinition 对象封装了类的信息
 *      beanClass ------ bean 类对象
 *      scope ------ 作用域
 *      lazyInit ------ 懒加载
 *      dependsOn ------ 依赖其他类的加载
 *      ... ...
 *
 * 6.然后 spring 调用 preInstanceSingletons() 方法,遍历 beanDefinitionMap 拿出信息,然后 new object new出对象,放入到 spring 单例池中
 *      创建一个对象的方式(new, 反射,序列化,克隆)
 * 7.未完,待续... ...
 *
 */
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

        GenericBeanDefinition userService = (GenericBeanDefinition) configurableListableBeanFactory.getBeanDefinition("userService");
        // 从 map 中取出 spring 扫描的对象,修改其类型
        userService.setBeanClass(OrderService.class);
    }
}

-- Junit

package com.hang.rpc.test;

import com.hang.rpc.business.OrderService;
import com.hang.rpc.business.UserService;
import com.hang.rpc.producer.RpcProducerApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringTest {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(RpcProducerApplication.class);

        /*UserService userService = (UserService) applicationContext.getBean("userService");

        int result = userService.calculate();

        System.out.println(result);*/

        OrderService orderService = (OrderService) applicationContext.getBean("userService");

        int order = orderService.order();

        System.out.println(order);

    }

}

分析:即使没有注入 OrderService,也可以手动将其注入到 spring

-- 未完,待续... ...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值