实习之余多学点,希望一个月之内能够完成这个笔记
Spring笔记
- 3-8
- BeanFactory && ApplicationContext
- BeanFactory
- ApplicationContext
3-8
BeanFactory && ApplicationContext
BeanFactory
首先,从SpringBoot的主启动类来看
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
}
}
在IDEA中将光标放到ConfigurableApplication上,ctrl + alt + u。 可查看该类的相关类图如下:
可以看到ConfigurableApplication、ApplicationContext、BeanFactory。从图中可以看出ApplicationContext间接实现了BeanFactory而ConfigurableApplication实现ApplicationContext。也就是更核心的其实就是BeanFactory
使用Debug对ConfigableApplication的实例进行查看,可以看到示例中包含beanFactory对象
然而单纯的看BeanFactory,其名下并没有太多的方法
最主要的其实是BeanFactory的实现类DefaultListableBeanFactory。其继承、实现的接口、类的情况如下
虽然BeanFactory表面上看着比较简单,但是实际上控制反转、依赖注入、Bean的生命周期等功能,都是由他的实现类来提供的
以DefaultListableBeanFactory间接继承的父类DefauleSingletonBeanRegistry为例,获取对应的单例bean
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
System.out.println(run);
//因为singletonObjects是私有的,所以通过反射,获取DefaultSingletonBeanRegistry类中的名为singletonObjects的属性。
Field singletonObjects = DefaultSingletonBeanRegistry.class.getDeclaredField("singletonObjects");
//设置私有属性在类外面允许被访问
singletonObjects.setAccessible(true);
//获取当前Springboot实例的Bean Factory
ConfigurableListableBeanFactory beanFactory = run.getBeanFactory();
//根据beanFactory对象获取其对应的单例Bean的Map 键表示Bean的名称,值表示Bean的实例
Map<String,Object> map = (Map<String, Object>) singletonObjects.get(beanFactory);
//输出key value
map.forEach((k,v)->System.out.println(k + "=" + v));
}
可以使用@commpent @service等注解来注入对应的类,这些注解都会被Spring Boot识别,前提是放到类上,不要放到接口上,接口也不能实例化
ApplicationContext
MessageSource: getMessage().主要是读取对应的properties文件,进行一个语言的转化
ResourcePatternResolver:getResources() 读取对应通配符路径下的文件,参数例classpath:application.properties
,通配符如:classpath: \ filed:
等