- 创建自定义BeanFactory的后置处理器
并设置MyLog为懒加载
/**
* 在类的定义加载完但是没有初始化是对类定义做除修改
*/
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("IOC 容器调用了 MyBeanFactoryPostProcessor 的 MyBeanFactoryPostProcessor 方法");
for (String beanName: beanFactory.getBeanDefinitionNames()) {
if ("myLog".equals(beanName)) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
beanDefinition.setLazyInit(true);
}
}
}
}
public class MyLog {
public MyLog() {
System.out.println("MyLog 构造方法");
}
}
- 配置类中配置bean
@Configuration
@ComponentScan(value = {"com.dgr.spring.bean_factory_post_processor"})
public class MainConfig {
@Bean
public MyLog myLog() {
return new MyLog();
}
}
- 初始化IOC容器
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
// MyLog myLog = (MyLog) context.getBean("myLog");
}
MyLog类的构造方法并没有被调用
21:18:12.770 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
IOC 容器调用了 MyBeanFactoryPostProcessor 的 MyBeanFactoryPostProcessor 方法
21:18:12.773 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
21:18:12.774 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
21:18:12.779 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'mainConfig'