BeanFactory与ApplicationContext容器


本文为学习笔记

1、BeanFactory

1、ctrl+alt+u 查看类图
2、run方法返回一个Spring 容器 ConfigurableApplicationContext 继承自ApplicationContext 继承自 BeanFactory
3、BeanFactory 是 Spring 的核心容器,context 的 getBean()功能的实现来自 BeanFactory
4、context对象包含一个beanFactory对象属性,beanFactory对象中有很多重要属性,比如:单例Bean都在它的singletonObjects属性里面

2、BeanFactory的功能:

1、ctrl+F12 列出BeanFactory的所有方法

2、Bean的实现类 DefaultListableBeanFactory 提供控制反转、依赖注入、Bean的生命周期和各种功能,管理所有单例对象 

3、ApplicationContext接口的功能

继承四个接口:
1、MessageSource:处理国际化资源的能力(翻译)多国语言
context.getMessage():Springboot 默认文件存储在Message打头的文件中。根据键值进行翻译

2、ResourcePatternResolver:通配符匹配资源
classpath代表到项目目中找,file代表到磁盘路径找。这两个算是通配符了。classpath* 代表也到jar包里面找
context.getResources("classpath*:META-INF/spring.factories")

3、ApplicationEventPublisher:事件发布
要有一个时间发布类和一个事件监听类,事件通过context 对象发布,这个对象可以通过 @AutoWire自动注入

4、environment存放配置信息,有的存放在application.properties文件,有的是启动环境变量(java_home)

附:

1、事件发布流程:

Application:
     public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        context.publishEvent(new UserRegisterEvent(context));
    }

component1:
@Component
public class component1 {
    private static final Logger logger = LoggerFactory.getLogger(component1.class);

    @EventListener   //事件监听
    public void aaa(UserRegisterEvent event){
        logger.debug(event.toString());
        logger.debug("发送短信");
    }
}

component2:
@Component
public class component2 {
    private static final Logger logger = LoggerFactory.getLogger(component2.class);

    @Autowired
    private ApplicationContext context;

    public void bbb(){
        System.out.println("bbbb-------");
        System.out.println(context);
        logger.debug("用户注册");
        context.publishEvent(new UserRegisterEvent(this));
    }
}


UserRegisterEvent:
public class UserRegisterEvent extends ApplicationEvent{
    public UserRegisterEvent(Object source) {
        super(source);
    }
}

得到结果:(为了显眼用的 error)。第二次添加component2 测试时,不能再控制台获得数据了,但是debug数据正确