一、何时所有bean创建完
- 1.所有bean创建完:new ApplicationContext()->refresh()->finishBeanFactoryInitialization(循环所有的BeanDefinition,通过BeanFactory.getBean()生成所有的Bean),循环结束后所有的Bean创建完
二、扩展方式
- 1.扩展方式一:基于SmartInitializingSingleton接口,在finishBeanFactoryInitialization(beanFactory); (源码在DefaultListableBeanFactory.java的preInstantiateSingletons()方法中),实现SmartInitializingSingleton接口,可以在所有单例bean全部实例化以后回调
- 2.扩展方式二:在AbstractApplicationContext.java中的finishRefresh()方法中,发布了一个最后的事件,publishEvent(new ContextRefreshedEvent(this));监听事件@EventListener(ContextRefreshedEvent.class)
三、示例截图
四、代码示例
package com.learning.beanCreationExtension;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.stereotype.Component;
/**
* @Author wangyouhui
* @Description 实现SmartInitializingSingleton接口
**/
@Component
public class SmartInitializingSingletonExtend implements SmartInitializingSingleton {
@Override
public void afterSingletonsInstantiated() {
System.out.println("SmartInitializingSingleton");
}
}
package com.learning.beanCreationExtension;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* @Author wangyouhui
* @Description 监听器
**/
@Component
public class ContextRefreshedEventListener {
@EventListener(ContextRefreshedEvent.class)
public void onApplicationEvent(ContextRefreshedEvent event){
System.out.println("contextRefreshEvent");
}
}
package com.learning.beanCreationExtension;
import org.springframework.stereotype.Component;
/**
* @Author wangyouhui
* @Description bean
**/
@Component
public class UserService {
public UserService(){
System.out.println("对象实例化完成");
}
}
package com.learning.beanCreationExtension;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author wangyouhui
* @Description 配置类
**/
@Configuration
public class BeanConfig {
@Bean
public UserService userService(){
return new UserService();
}
@Bean
public ContextRefreshedEventListener contextRefreshedEventListener(){
return new ContextRefreshedEventListener();
}
@Bean
public SmartInitializingSingletonExtend smartInitializingSingletonExtend(){
return new SmartInitializingSingletonExtend();
}
}
package com.learning.beanCreationExtension;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @Author wangyouhui
* @Description 启动类
**/
public class Applicaiton {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
applicationContext.getBean(UserService.class);
}
}