spring上下文的創建過程

AnnotationConfigApplicationContext的創建過程

1.AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
	->AbstractApplicationContext 調用父類靜態方法,聲明三個常量
	public static final String MESSAGE_SOURCE_BEAN_NAME = "messageSource";

	public static final String LIFECYCLE_PROCESSOR_BEAN_NAME = "lifecycleProcessor";

	public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
	static {
		// Eagerly load the ContextClosedEvent class to avoid weird classloader issues
		//急切加載ContextClosedEvent避免莫名其妙的事情發生
		ContextClosedEvent.class.getName();
	}
	->GenericApplicationContext的無參構造
		this.beanFactory = new DefaultListableBeanFactory();//返回beanFactory
	->AbstractApplicationContext的無參構造
	this.resourcePatternResolver = getResourcePatternResolver();//返回路徑解析器
		->return new PathMatchingResourcePatternResolver(this)
	->AbstractApplicationContext
	private final Set<ProtocolResolver> protocolResolvers = new LinkedHashSet<>(4);
	private final Map<Class<?>, Map<Resource, ?>> resourceCaches = new ConcurrentHashMap<>(4);
	接着無參構造
		this.classLoader = ClassUtils.getDefaultClassLoader();
		->ClassUtils的getDefaultClassLoader
			默認Thread.currentThread().getContextClassLoader()
			接着ClassUtils.class.getClassLoader()
			接着ClassLoader.getSystemClassLoader()
	AbstractApplicationContext裏面的屬性初始化	
    GenericApplicationContext的屬性初始化
			

在這裏插入圖片描述

2.AnnotatedBeanDefinitionReader的創建


AnnotatedBeanDefinitionReader一個裸類
1.getOrCreateEnvironment(registry)

private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		//通過繼承圖就看出爲true
		if (registry instanceof EnvironmentCapable) {
			return ((EnvironmentCapable) registry).getEnvironment();
		}
		return new StandardEnvironment();
	}
	
	
返回的代碼
protected ConfigurableEnvironment createEnvironment() {
		return new StandardEnvironment();
	}
->AbstractEnvironment 幾個環境參數

	public static final String IGNORE_GETENV_PROPERTY_NAME = "spring.getenv.ignore";
	public static final String ACTIVE_PROFILES_PROPERTY_NAME = "spring.profiles.active";
	public static final String DEFAULT_PROFILES_PROPERTY_NAME = "spring.profiles.default";
	protected static final String RESERVED_DEFAULT_PROFILE_NAME = "default";
	//默認是default環境
private final MutablePropertySources propertySources = new MutablePropertySources();
	後面兩個路徑解析器
	private final MutablePropertySources propertySources = new MutablePropertySources();

	private final ConfigurablePropertyResolver propertyResolver =
			new PropertySourcesPropertyResolver(this.propertySources);
	
	customizePropertySources(this.propertySources);構造裏面的方法
	給propertySources裏面放了兩個環境
		->systemProperties
			-> System.getProperties()
		->stemEnvironment
			->System.getenv()
	
	

2.構造裏面屬性賦值
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;//bean定義註冊
		this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
		AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
	}
	
	
3.new ConditionEvaluator
	ConditionEvaluator是spring4.0新增的條件處理器
	

	public ConditionEvaluator(@Nullable BeanDefinitionRegistry registry,
			@Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {
		//初始化private final ConditionContextImpl context
		this.context = new ConditionContextImpl(registry, environment, resourceLoader);
	}
	
	ConditionContextImpl是ConditionEvaluator的內部類
	實現了ConditionContext接口
	
	構造
	public ConditionContextImpl(@Nullable BeanDefinitionRegistry registry,
				@Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {

			this.registry = registry;//註冊器有的
			this.beanFactory = deduceBeanFactory(registry);//返回上下文裏面的beanFactory
			this.environment = (environment != null ? environment : deduceEnvironment(registry));//環境
			this.resourceLoader = (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry));//resourceLoader
			this.classLoader = deduceClassLoader(resourceLoader, this.beanFactory);//classLoader
		}
4.註冊
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);

//這裏註冊,放回的是set集合
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {
		//此時source=null
		//獲取beanFactory
		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {//不爲空進入
		//不爲AnnotationAwareOrderComparator就設置爲
		//AnnotationAwareOrderComparator是OrderComparator的子類,用來支持Spring的Ordered類、@Order註解和@Priority註解。
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				//進入設置
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
			}
			//不是ContextAnnotationAutowireCandidateResolver後選擇解析器就設置
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
			//進入設置
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}
		//bean定義默認8
		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
		//判斷有沒有@Confgiratuon的bean定義,沒有給一個
		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));
		}
		//有沒有@Autowire的bean定義信息
		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));
		}
		
		//檢查jsr250支持,biru @Resource等
		// 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));
		}
		//檢查jps支持
		// 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));
		}

		//事件監聽工廠
		if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
		}

		return beanDefs;
	}
到此框架自身的bean定義加載完畢

this.scanner = new ClassPathBeanDefinitionScanner(this);


public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
			Environment environment, @Nullable ResourceLoader resourceLoader) {

		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		this.registry = registry;

		if (useDefaultFilters) {//這裏默認爲true
			registerDefaultFilters();
		}
		setEnvironment(environment);
		setResourceLoader(resourceLoader);
	}

	//過濾增加@Component
//jar250標準 @ManagedBean,jsr330標準@Inject
->protected void registerDefaultFilters() {
		this.includeFilters.add(new AnnotationTypeFilter(Component.class));
		ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
		try {
			this.includeFilters.add(new AnnotationTypeFilter(
					((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
			logger.trace("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
		}
		catch (ClassNotFoundException ex) {
			// JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.
		}
		try {
			this.includeFilters.add(new AnnotationTypeFilter(
					((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
			logger.trace("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
		}
		catch (ClassNotFoundException ex) {
			// JSR-330 API not available - simply skip.
		}
	}







在這裏插入圖片描述

在這裏插入圖片描述

spring容器的refresh()方法

spring容器的refresh()方法

當spring程序換這麼長時間,都不敢說懂他,crud傷不起

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章