public class Teacher {
@PostConstruct
private void init() {
System.out.println("Teacher===>init()" +System.currentTimeMillis());
}
}
public class TeacherConfig implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
if (registry.containsBeanDefinition(Teacher.class.getName())) {
return;
}
String[] candidates = registry.getBeanDefinitionNames();
for (String candidate : candidates) {
BeanDefinition beanDefinition = registry.getBeanDefinition(candidate);
if (Objects.equals(beanDefinition.getBeanClassName(), Teacher.class.getName())) {
return;
}
if (Objects.equals(beanDefinition.getBeanClassName(), Student.class.getName())) {
return;
}
}
BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(Teacher.class).getBeanDefinition();
registry.registerBeanDefinition(Teacher.class.getName(), beanDefinition);
}
}
@Configuration
@Import(value = {TeacherConfig.class})
public class MyConfiguration {
}
ImportBeanDefinitionRegistrar接口在Spring的所有配置类解析完毕后会触发回调,通过回调将手动注入的BeanDefinition加入 DefinitionRegistre注册器中
调用注册方法指调用所有实现了 ImportBeanDefinitionRegistrar 接口的 registerBeanDefinitions()方法