/*标签:01,beanFactory,实现,BeanFactory,class,bean,Bean2,Bean1,public From: https://www.cnblogs.com/Fei-Gao/p/16824295.html
* beanFactory 不会做的事:
* 1.不会主动调用BeanFactory 后处理器
* 2.不会主动添加Bean后处理器
* 3.不会主动初始化单例(懒加载)
* 4.不会解析beanFactory 还不会解析 ${} 与 #{}
* */
@Slf4j
@SpringBootApplication
public class SpringbootSsmApplication {
public static void main(String[] args){
ConfigurableApplicationContext context = SpringApplication.run(SpringbootSsmApplication.class, args);
// DefaultListableBeanFactory 是 BeanFactory 的一个实现类
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// bean定义
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(Config.class).setScope("singleton").getBeanDefinition();
beanFactory.registerBeanDefinition("config", beanDefinition);
// 给 beanFactory 添加一些常用的后处理器
AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory);
// 解析bean
beanFactory.getBeansOfType(BeanFactoryPostProcessor.class).values().stream().forEach(beanFactoryPostProcessor -> {
beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
});
for (String name : beanFactory.getBeanDefinitionNames()) {
System.out.println(name);
}
// Bean 后处理器,针对bean的生命周期的各个阶段提供扩展,例如@Autowired、@Resource....
beanFactory.getBeansOfType(BeanPostProcessor.class).values().forEach(beanFactory::addBeanPostProcessor);
// 准备好初始化所有单例bean对象
beanFactory.preInstantiateSingletons();
System.out.println("-------------------");
System.out.println(beanFactory.getBean(Bean1.class).getBean2());
}
@Configuration
static class Config{
@Bean
public Bean1 bean1(){
return new Bean1();
}
@Bean
public Bean2 bean2(){
return new Bean2();
}
}
static class Bean1{
@Autowired
private Bean2 bean2;
public Bean1(){
log.debug("bean1构造");
}
public Bean2 getBean2(){
return bean2;
}
}
static class Bean2{
public Bean2(){
log.debug("bean2构造");
}
}
}