1. 优秀源码点
1.1 给一个对象设置属性
ReflectUtil.setFieldValue(bean, fieldNameOrIndex, value);
1.2 先instanceOf 再强转
if (value instanceof BeanReference) {
// A 依赖 B,获取 B 的实例化
BeanReference beanReference = (BeanReference) value;
value = getBean(beanReference.getBeanName());
}
1.3 泛型定义一个接口
public interface BeanFactory {
Object getBean(String name) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
}
1.4 自定义异常
public class BeansException extends RuntimeException {
public BeansException(String msg) {
super(msg);
}
public BeansException(String msg, Throwable cause) {
super(msg, cause);
}
}
1.5 流读取文件
String content = IoUtil.readUtf8(inputStream);
public InputStream getInputStream() throws IOException {
InputStream is = classLoader.getResourceAsStream(path);
if (is == null) {
throw new FileNotFoundException(
this.path + " cannot be opened because it does not exist");
}
return is;
}
1.6 判断beanClass是不是type的子类
type.isAssignableFrom(beanClass)
1.7 注册jvm关闭的钩子
Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("close!")));
2. 源码总结
2.1 源码中重要的接口
定义标记接口
在 Spring 中有特别多类似这样的标记接口的设计方式,它们的存在就像是一种标 签一样,可以方便统一摘取出属于此类接口的实现类,通常会有 instanceof 一起 判断使用
public interface Aware {
}
2.2 源码中重要的map
单例池,一级缓存singletonObjects
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {
private Map<String, Object> singletonObjects = new HashMap<>();
}
bean的定义map beanDefinitionMap
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry, ConfigurableListableBeanFactory {
private Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
}
3. 需要记住的地方
1. AbstractAutowireCapableBeanFactory 的方法createBean
AbstractBeanFactory的方法getBean
2. AbstractApplicationContext的refresh方法
3. AbstractBeanFactory
private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();