public class SpringClient { public static void main(String[] args) { //相当于xml方式的工厂,内置了reader和scanner AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); //相当于xml的读取器要读取的位置 annotationConfigApplicationContext.register(PersonConfiguration.class); //刷新工厂 annotationConfigApplicationContext.refresh(); Person person = (Person)annotationConfigApplicationContext.getBean("person"); System.out.println(person.getId()); System.out.println(person.getName()); } }
输出: 222 kkkk
bean对象创建时机
AnnotationConfigApplicationContext的构造器:
1 2 3 4 5 6 7 8 9
private final AnnotatedBeanDefinitionReader reader;
private final ClassPathBeanDefinitionScanner scanner; public AnnotationConfigApplicationContext() { //读取器 this.reader = new AnnotatedBeanDefinitionReader(this); //扫描器 this.scanner = new ClassPathBeanDefinitionScanner(this); }
AnnotatedBeanDefinitionReader
AnnotatedBeanDefinitionReader构造器:
1 2 3 4 5 6 7 8 9 10 11
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) { this(registry, getOrCreateEnvironment(registry)); } //Environment封装了properties和profile public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); Assert.notNull(environment, "Environment must not be null"); this.registry = registry; this.conditionEvaluator = new ConditionEvaluator(registry, environment, null); AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); }
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) { registerAnnotationConfigProcessors(registry, null); }
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors( BeanDefinitionRegistry registry, @Nullable Object source) { //得到工厂 DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry); if (beanFactory != null) { if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) { beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); } if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) { beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver()); } }
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8); //各种注册处理器的注册 if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)); }
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); }
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor. if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); }
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor. if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(); try { def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, AnnotationConfigUtils.class.getClassLoader())); } catch (ClassNotFoundException ex) { throw new IllegalStateException( "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex); } def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)); }
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME)); }
//注册一个或多个组件到读取器上,注册完毕之后要调用一下refresh方法 public void register(Class<?>... componentClasses) { Assert.notEmpty(componentClasses, "At least one component class must be specified"); this.reader.register(componentClasses); }
public class SpringClient { public static void main(String[] args) { //相当于xml方式的工厂,内置了reader和scanner AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); //相当于xml的读取器 annotationConfigApplicationContext.register(PersonConfiguration.class); //刷新工厂 annotationConfigApplicationContext.refresh(); PersonConfiguration personConfiguration = (PersonConfiguration)annotationConfigApplicationContext.getBean("personConfiguration"); Person person = (Person)annotationConfigApplicationContext.getBean("person"); System.out.println(personConfiguration.getClass()); System.out.println(person.getClass()); } }
打印: class com.tdl.spring.anotation.PersonConfiguration$$EnhancerBySpringCGLIB$$8455c0b9 class com.tdl.spring.anotation.Person 由此可以看到得到的personConfiguration是一个PersonConfiguration的子类,是在运行的时候生成的一个子类(代理类),并且将这个子类放在spring的工厂里边。 refresh方法实现: org.springframework.context.support.AbstractApplicationContext
// public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. //注册监听器、环境的校验、占位符 prepareRefresh();
// Tell the subclass to refresh the internal bean factory. //返回一个bean工厂,DefaultListableBeanFactory(和xml的方式殊途同归) ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context. //配置上下文、bean的类加载器之类的(appClassLoader),一些处理器等 prepareBeanFactory(beanFactory);
try { // Allows post-processing of the bean factory in context subclasses. //bean工厂创建的后置处理器 postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context. //自定义bean的BeanDefinationn被注入(但是没有实例化) invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation. //bean的后置处理器 registerBeanPostProcessors(beanFactory);
// Initialize message source for this context. //初始化消息源 initMessageSource();
// Initialize event multicaster for this context. initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses. onRefresh();
// Check for listener beans and register them. registerListeners();
// Instantiate all remaining (non-lazy-init) singletons. //bean的实例初始化和创建。对应PersonConfiguration.getPerson()方法会执行 finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event. finishRefresh(); }
// Destroy already created singletons to avoid dangling resources. destroyBeans();
// Reset 'active' flag. cancelRefresh(ex);
// Propagate exception to caller. throw ex; }
finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
//完成bean工厂的初始化,初始化所有的单例的bean protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); }
// Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); }
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); }
// Stop using the temporary ClassLoader for type matching. beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes. beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons. //初始化单例bean beanFactory.preInstantiateSingletons(); }
public void preInstantiateSingletons() throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); }
// Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);