-- 笔记
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