> Java > java지도 시간 > springboot가 컨텍스트 로더를 개선하는 방법

springboot가 컨텍스트 로더를 개선하는 방법

王林
풀어 주다: 2023-05-11 14:34:11
앞으로
1019명이 탐색했습니다.

1. prepareContext

소스코드 :

```
 private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
    //注入环境属性
    context.setEnvironment(environment);
    //上下文后置处理
    this.postProcessApplicationContext(context);
    //完善初始化类的属性
    this.applyInitializers(context);
    //发送监听事件
    listeners.contextPrepared(context);
    //日志
    if (this.logStartupInfo) {
        this.logStartupInfo(context.getParent() == null);
        this.logStartupProfileInfo(context);
    }
    //注册传入的配置参数为bean,这里将传入的参数封装成applicationArguments,内部类似命令行
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
    //banner打印
    if (printedBanner != null) {
        beanFactory.registerSingleton("springBootBanner", printedBanner);
    }
    //这里默认情况下bean定义不允许重复
    if (beanFactory instanceof DefaultListableBeanFactory) {
        ((DefaultListableBeanFactory)beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
    }
    //默认不开启延迟加载
    if (this.lazyInitialization) {
        context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
    }
    //获取全部的资源
    //这里获取了启动类的资源和 当前SpringApplication中的source资源。
    //到目前来说实际上只有启动类资源
    Set<Object> sources = this.getAllSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    this.load(context, sources.toArray(new Object[0]));
    listeners.contextLoaded(context);
}
```
로그인 후 복사

평소대로 하나씩 분석해보세요. 하지만 이 방법은 복잡하지 않고, 컨텍스트와 팩토리 클래스의 전체적인 구성이 개선되었습니다.

1.1 postProcessApplicationContext 메소드

소스 코드:

   protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
        //  是否自定义bean名称生成类
        if (this.beanNameGenerator != null) {
            context.getBeanFactory().registerSingleton("org.springframework.context.annotation.internalConfigurationBeanNameGenerator", this.beanNameGenerator);
        }
        //是否指定类加载器
        if (this.resourceLoader != null) {
            if (context instanceof GenericApplicationContext) {
                ((GenericApplicationContext)context).setResourceLoader(this.resourceLoader);
            }

            if (context instanceof DefaultResourceLoader) {
                ((DefaultResourceLoader)context).setClassLoader(this.resourceLoader.getClassLoader());
            }
        }
        
        //是否添加数据转换器 
        //在初始化环境对象的时候也有用到,这里可以直接通过 context.getEnvironment().getConversionService()获取到
        if (this.addConversionService) {
            context.getBeanFactory().setConversionService(ApplicationConversionService.getSharedInstance());
        }
    }
로그인 후 복사

1.2 applyInitializers

ApplicationContextInitializer 인터페이스와 관련된 객체 속성을 개선합니다. 이러한 객체는 this.initializers에 있으며 SpringApplication 초기화 초기에 로드되었습니다. 초기화된 컨텍스트를 통해 관련 클래스를 개선합니다. 인터페이스의 초기화 메소드를 호출하십시오.

1.3 load

소스 코드:

	protected void load(ApplicationContext context, Object[] sources) {
		if (logger.isDebugEnabled()) {
			logger.debug("Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
		}
		//构建一个bean定义的加载器
		BeanDefinitionLoader loader = createBeanDefinitionLoader(getBeanDefinitionRegistry(context), sources);
		if (this.beanNameGenerator != null) {
			loader.setBeanNameGenerator(this.beanNameGenerator);
		}
		if (this.resourceLoader != null) {
			loader.setResourceLoader(this.resourceLoader);
		}
		if (this.environment != null) {
			loader.setEnvironment(this.environment);
		}
		//将资源加载成bean
		loader.load();
	}
	
	void load() {
		for (Object source : this.sources) {
			load(source);
		}
	}
    //按资源类型分别进行加载,
	private void load(Object source) {
		Assert.notNull(source, "Source must not be null");
		if (source instanceof Class<?>) {
			load((Class<?>) source);
			return;
		}
		if (source instanceof Resource) {
			load((Resource) source);
			return;
		}
		if (source instanceof Package) {
			load((Package) source);
			return;
		}
		if (source instanceof CharSequence) {
			load((CharSequence) source);
			return;
		}
		throw new IllegalArgumentException("Invalid source type " + source.getClass());
	}
로그인 후 복사

Bean으로 등록될 시작 클래스 xxApplication을 포함하여 SpringApplication에서 초기화된 리소스를 주로 로드합니다.

위 내용은 springboot가 컨텍스트 로더를 개선하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿