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

Spring Boot Environment From file config_逆序

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 + "资源未找到");
}