前言
在使用SpringBoot使用过程中
@RestController
、@Service
、@Repository
这几个注解类上都标有@Component
注解
启动类上标有的@SpringBootApplication
注解类上有个@ComponentScan
注解。那么@ComponentScan如何把相关的对象注册到BeanFactory的?
找到处理ComponentScan注解的代码
从启动类找到refresh(context)
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
点击run进入
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class<?>[] { primarySource }, args);
}
点击run进入
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
点击run进入
public ConfigurableApplicationContext run(String... args) {
...
try {
...
refreshContext(context);
...
}
catch (Throwable ex) {
...
}
...
return context;
}
找到refreshContext(context)点击进入
private void refreshContext(ConfigurableApplicationContext context) {
if (this.registerShutdownHook) {
shutdownHook.registerApplicationContext(context);
}
refresh(context);
}
点击进入,在找到接口实现
查看更多refresh(context)方法查看细读Spring Boot源码】重中之重refresh()
从refresh(context)找到处理ComponentScan注解的代码
refresh(context)进入后
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
...
try {
...
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
...
}
catch (BeansException ex) {
...
}
finally {
...
}
}
}
找到invokeBeanFactoryPostProcessors(beanFactory);
进入
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 进入
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
...
}
进入PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors,代码很多任意找到一个invokeBeanDefinitionRegistryPostProcessors()
进入
private static void invokeBeanDefinitionRegistryPostProcessors(
Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {
for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
.tag("postProcessor", postProcessor::toString);
postProcessor.postProcessBeanDefinitionRegistry(registry);
postProcessBeanDefRegistry.end();
}
}
发现是一个BeanFactoryPostProcessor接口类的回调处理
找到进入ConfigurationClassPostProcessor实现类找到postProcessBeanFactory()
方法