SpringBoot扩展篇:@Scope和@Lazy源码解析
1. 研究主题及Demo
A class
@Component
public class A {
@Lazy
@Autowired
public B b;
public B getB() {
return b;
}
}
B class
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
public class B {
}
测试类
@SpringBootApplication
public class WebApplication{
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(WebApplication.class, args);
A a = run.getBean(A.class);
System.out.println(a.b);
System.out.println(a.b);
System.out.println(a.b);
}
}
研究问题1:为什么打印三次b对象的地址值不一样,从源码角度分析Spring是如何实现的?

研究问题2:为什么会debug看到的是代理对象,而打印出来的不是代理对象?

2. 注册BeanDefinition
在Spring对@Component扫描的时候,会调用ClassPathBeanDefinitionScanner#doScan生成beandefinition对象,可参考:
SpringBoot 源码解析5:ConfigurationClassPostProcessor整体流程和@ComponentScan源码分析
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
for (String basePackage : basePackages) {
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
for (BeanDefinition candidate : candidates) {
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;

最低0.47元/天 解锁文章
1136






