Spring Boot Environment From file config

Spring Boot Environment From file config

主要流程

  1. SpringApplication run -> ApplicationEnvironmentPreparedEvent

  2. ApplicationEnvironmentPreparedEvent ->EnvironmentPostProcessor

  3. EnvironmentPostProcessor(ConfigFileApplicationListener) ->Load (application.yml …)

Load Config

Load application.yml … from classpath:/,classpath:/config/,file:./,file:./config/

优先级逆序… StringUtils.commaDelimitedListToStringArray Collections.reverse(list);

  1. query load profiles from
    • JVM arguments: spring.profiles.active |spring.profiles.include
    • Search Location || Load Location
    • Load For prefix(location) + name + fileExtension
    • ResourceLoader.getResource(Location)
    • 顺序加载 application -> spring.profiles.active
    • load DocumentsCache loaded
    • 逆序DocumentsCache 然后逆序加载所有config file

在这里插入图片描述

Search Location
	/**
	 * The "config location" property name.
	 */
	public static final String CONFIG_LOCATION_PROPERTY = "spring.config.location";

	/**
	 * The "config additional location" property name.
	 */
	public static final String CONFIG_ADDITIONAL_LOCATION_PROPERTY = "spring.config.additional-location";

        private Set<String> getSearchLocations() {
            //如果当前的Environment有spring.config.location 此时application.yml尚未加载哦!
			if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) {
				return getSearchLocations(CONFIG_LOCATION_PROPERTY);
			}
            //如果当前的Environment有spring.config.additional-location 则加载
            //Set<String> locations = new LinkedHashSet<>();
			Set<String> locations = getSearchLocations(
					CONFIG_ADDITIONAL_LOCATION_PROPERTY);
            //add `classpath:/,classpath:/config/,file:./,file:./config/`
			locations.addAll(
					asResolvedSet(ConfigFileApplicationListener.this.searchLocations,
							DEFAULT_SEARCH_LOCATIONS));
			return locations;
		}

模拟从classpath || file 加载文件

    @Autowired
    private ResourceLoader resourceLoader;

     //或者new DefaultResourceLoader();
    private Resource getResource(ResourceLoader resourceLoader, String[] certificatePath, String fileName) {
        for (int i = certificatePath.length - 1; i >= 0; i--) {
            Resource resource = resourceLoader.getResource(certificatePath[i] + fileName);
            if (resource.exists()) {
                return resource;
            }
        }
        throw new ResourceRequestDeniedException(fileName + "资源未找到");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值