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 + "資源未找到");
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章