從spring3.0版本引入註解容器類以後,Spring註解的使用就變得異常的普遍起來,到現在流行的SpringBoot中,幾乎是所有使用了註解。Spring的經常使用註解有不少,有@Bean,@Compont,@Autowired等。這些註解的使用和基於xml文件的使用的方式一模一樣,只是一個是用註解一個是用配置文件而已。那麼要學習Spring註解的原理,那麼咱們就得從基於註解spring容器類AnnotationConfigApplicationContext開始,接下來咱們來分析:spring
第一步:看他的構造器app
public AnnotationConfigApplicationContext() { this.reader = new AnnotatedBeanDefinitionReader(this); this.scanner = new ClassPathBeanDefinitionScanner(this); }
//給定一個beanFactory
public AnnotationConfigApplicationContext(DefaultListableBeanFactory beanFactory) {
super(beanFactory);
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
//用一個被註解的類建立一個AnonotationConfigApplicationContext public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) { this(); register(annotatedClasses); refresh(); } //掃描包名及子包類的被註解的類 public AnnotationConfigApplicationContext(String... basePackages) { this(); scan(basePackages); refresh(); }
第二步:實際分析,咱們構造一個AnnotationConfigApplicationContext對象,內部會作什麼具體的操做。
post
我寫了一個測試類,代碼以下:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyBeanConfig.class);
他調用的構造器是這個:學習
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
//初始化了AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner
this();
//註冊類 register(annotatedClasses);
//刷新 refresh(); }
重點就是register方法和refresh方法分別都作了什麼。測試
先來看register方法,點進去以後的代碼以下:this
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name, @Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) { //用於分析我傳入的類的註解的信息 AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass); if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) { return; } //Supplier有返回值無參數的接口 abd.setInstanceSupplier(instanceSupplier);
//檢查scope,實例中沒有指定,默認是singleton ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd); abd.setScope(scopeMetadata.getScopeName());
//獲取bean的名字,實例中這裏是MyBeanConfig String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry)); //對因而否是@lazy,是否使用了@primary AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
//是否使用了@qualifier if (qualifiers != null) { for (Class<? extends Annotation> qualifier : qualifiers) { if (Primary.class == qualifier) { abd.setPrimary(true); } else if (Lazy.class == qualifier) { abd.setLazyInit(true); } else { abd.addQualifier(new AutowireCandidateQualifier(qualifier)); } } }
for (BeanDefinitionCustomizer customizer : definitionCustomizers) { customizer.customize(abd); } BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
//根據Bean的做用域,建立相應的代理對象 definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
//將Bean加入到beanDefinitionMap中 BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry); }
到這裏register方法就介紹完了。lua
而後看refresh方法:spa
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // 刷新前的準備 prepareRefresh(); // 建立並獲取一個beanFanctory ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // 使用beanfactory以前的準備 prepareBeanFactory(beanFactory); try { //給子類實現用的,默認是空方法 postProcessBeanFactory(beanFactory); //執行beanfactory的後處理 invokeBeanFactoryPostProcessors(beanFactory); // 註冊BeanPostProcessor,對bean進行初始化的先後能夠調用 registerBeanPostProcessors(beanFactory); // 初始化MessageSource initMessageSource(); // 初始化application事件派發器 initApplicationEventMulticaster(); // 預留給子類來實現 onRefresh(); // 添加application監聽器 registerListeners(); //初始化最後全部剩下的單實例bean finishBeanFactoryInitialization(beanFactory); // 完成bean和beanfactory初始化。 finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // 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(); } } }
全部的bean都放入到了容器中了。還有部份內容不許確不詳盡,等之後埋坑。。。代理