在实践的过程中我们经常会遇到不同的环境需要不同配置文件的情况,如果每换一个环境重新修改配置文件或重新打包一次会比较麻烦,Spring Boot为此提供了Profile配置来解决此问题。

Profile对应中文并没有合适的翻译,它的主要作用就是让Spring Boot可以根据不同环境提供不同的配置功能支持。

我们经常遇到这样的场景:有开发、测试、生产等环境,不同的环境又有不同的配置。如果每个环境在部署时都需要修改配置文件将会非常麻烦,而通过Profile则可以轻松解决改问题。

比如上述环境,我们可以在Spring Boot中创建4个文件:

  • applcation.properties:公共配置
  • application-dev.properties:开发环境配置
  • application-test.properties:测试环境配置
  • application-prod.properties:生产环境配置

在applcation.properties中配置公共配置,然后通过如下配置激活指定环境的配置:

  1. spring.profiles.active = prod

其中“prod”对照文件名中application-prod.properties。Spring Boot在处理时会获取配置文件applcation.properties,然后通过指定的profile的值“prod”进行拼接,获得application-prod.properties文件的名称和路径。

举例说明,比如在开发环境使用服务的端口为8080,而在生产环境中需要使用18080端口。那么,在application-prod.properties中配置如下:

  1. server.port=8080

而在application-prod.properties中配置为:

  1. server.port=18080

在使用不同环境时,可以通过在applcation.properties中配置spring.profiles.active属性值来进行指定(如上面示例),也可以通过启动命令参数进行指定:

  1. java -jar springboot.jar --spring.profiles.active=prod

这样打包后的程序只需通过命令行参数就可以使用不同环境的配置文件。

如果配置文件是基于yml文件类型,还可以将所有的配置放在同一个配置文件中:

  1. spring:
  2. profiles:
  3. active: prod
  4. server:
  5. port: 18080
  6. ---
  7. spring:
  8. profiles: dev
  9. server:
  10. port: 8080
  11. ---
  12. spring:
  13. profiles: test
  14. server:
  15. port: 8081

上述配置以“—”进行分割,其中第一个位置的为默认的profile,比如上述配置启动时,默认使用18080端口。如果想使用指定的端口同样可以采用上述命令启动时指定。

下面带大家简单看一下在Spring Boot中针对Profile的基本处理流程(不会过度细化具体操作)。在Spring Boot启动的过程中执行其run方法时,会执行如下一段代码:

  1. public ConfigurableApplicationContext run(String... args) {
  2. // ...
  3. try {
  4. ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
  5. ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
  6. // ...
  7. }
  8. // ...
  9. }

其中prepareEnvironment方法的相关代码如下:

  1. private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
  2. ApplicationArguments applicationArguments) {
  3. // ...
  4. listeners.environmentPrepared(environment);
  5. // ...
  6. }

在prepareEnvironment方法处理业务的过程中会调用SpringApplicationRunListeners的environmentPrepared方法发布事件。该方法会遍历注册在spring.factories中SpringApplicationRunListener实现类,然后调用其environmentPrepared方法。

其中spring.factories中SpringApplicationRunListener实现类注册为:

  1. # Run Listeners
  2. org.springframework.boot.SpringApplicationRunListener=\
  3. org.springframework.boot.context.event.EventPublishingRunListener

SpringApplicationRunListeners方法中的调用代码如下:

  1. void environmentPrepared(ConfigurableEnvironment environment) {
  2. for (SpringApplicationRunListener listener : this.listeners) {
  3. listener.environmentPrepared(environment);
  4. }
  5. }

其中listeners便是注册的类的集合,这里默认只有EventPublishingRunListener。它的environmentPrepared方法实现为:

  1. @Override
  2. public void environmentPrepared(ConfigurableEnvironment environment) {
  3. this.initialMulticaster
  4. .multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment));
  5. }

其实就是发布了一个监听事件。该事件会被同样注册在spring.factories中的ConfigFileApplicationListener监听到:

  1. # Application Listeners
  2. org.springframework.context.ApplicationListener=\
  3. // ...
  4. org.springframework.boot.context.config.ConfigFileApplicationListener
  5. // ...

关于配置文件的核心处理便在ConfigFileApplicationListener中完成。在该类中我们可以看到很多熟悉的常量:

  1. public class ConfigFileApplicationListener implements EnvironmentPostProcessor, SmartApplicationListener, Ordered {
  2. private static final String DEFAULT_PROPERTIES = "defaultProperties";
  3. // Note the order is from least to most specific (last one wins)
  4. private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";
  5. private static final String DEFAULT_NAMES = "application";
  6. // ...
  7. }

比如Spring Boot默认寻找的配置文件的名称、默认扫描的类路径等。

不仅如此,该类还实现了监听器SmartApplicationListener接口和EnvironmentPostProcessor接口也就是拥有了监听器和环境处理的功能。

其onApplicationEvent方法对接收到事件进行判断,如果是ApplicationEnvironmentPreparedEvent事件则调用onApplicationEnvironmentPreparedEvent方法进行处理,代码如下:

  1. @Override
  2. public void onApplicationEvent(ApplicationEvent event) {
  3. if (event instanceof ApplicationEnvironmentPreparedEvent) {
  4. onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event);
  5. }
  6. if (event instanceof ApplicationPreparedEvent) {
  7. onApplicationPreparedEvent(event);
  8. }
  9. }

onApplicationEnvironmentPreparedEvent会获取到对应的EnvironmentPostProcessor并调用其postProcessEnvironment方法进行处理。而loadPostProcessors方法获取的EnvironmentPostProcessor正是在spring.factories中配置的当前类。

  1. private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
  2. List<EnvironmentPostProcessor> postProcessors = loadPostProcessors();
  3. postProcessors.add(this);
  4. AnnotationAwareOrderComparator.sort(postProcessors);
  5. for (EnvironmentPostProcessor postProcessor : postProcessors) {
  6. postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication());
  7. }
  8. }

经过一系列的调用,最终调用到该类的如下方法:

  1. protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
  2. RandomValuePropertySource.addToEnvironment(environment);
  3. new Loader(environment, resourceLoader).load();
  4. }

其中Loader类为ConfigFileApplicationListener内部类,提供了具体处理配置文件优先级、profile、加载解析等功能。

比如,在Loader类的load方法中便有如下一段代码:

  1. for (PropertySourceLoader loader : this.propertySourceLoaders) {
  2. if (canLoadFileExtension(loader, location)) {
  3. load(loader, location, profile, filterFactory.getDocumentFilter(profile), consumer);
  4. return;
  5. }
  6. }

该代码遍历PropertySourceLoader列表,并进行对应配置文件的解析,而这里的列表中的PropertySourceLoader同样配置在spring.factories中:

  1. # PropertySource Loaders
  2. org.springframework.boot.env.PropertySourceLoader=\
  3. org.springframework.boot.env.PropertiesPropertySourceLoader,\
  4. org.springframework.boot.env.YamlPropertySourceLoader

查看这两PropertySourceLoader的源代码,会发现SpringBoot默认支持的配置文件格式及解析方法。

  1. public class PropertiesPropertySourceLoader implements PropertySourceLoader {
  2. private static final String XML_FILE_EXTENSION = ".xml";
  3. @Override
  4. public String[] getFileExtensions() {
  5. return new String[] { "properties", "xml" };
  6. }
  7. @Override
  8. public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
  9. Map<String, ?> properties = loadProperties(resource);
  10. // ...
  11. }
  12. @SuppressWarnings({ "unchecked", "rawtypes" })
  13. private Map<String, ?> loadProperties(Resource resource) throws IOException {
  14. String filename = resource.getFilename();
  15. if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
  16. return (Map) PropertiesLoaderUtils.loadProperties(resource);
  17. }
  18. return new OriginTrackedPropertiesLoader(resource).load();
  19. }
  20. }

比如PropertiesPropertySourceLoader中支持了xml和properties两种格式的配置文件,并分别提供了PropertiesLoaderUtils和OriginTrackedPropertiesLoader两个类进行相应的处理。

同样的YamlPropertySourceLoader支持yml和yaml格式的配置文件,并且采用OriginTrackedYamlLoader类进行解析。

  1. public class YamlPropertySourceLoader implements PropertySourceLoader {
  2. @Override
  3. public String[] getFileExtensions() {
  4. return new String[] { "yml", "yaml" };
  5. }
  6. @Override
  7. public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
  8. // ...
  9. List<Map<String, Object>> loaded = new OriginTrackedYamlLoader(resource).load();
  10. // ...
  11. }
  12. }

当然,在ConfigFileApplicationListener类中还实现了上面提到的如何拼接默认配置文件和profile的实现,相关代码如下:

  1. private void loadForFileExtension(PropertySourceLoader loader, String prefix, String fileExtension,
  2. Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) {
  3. // ...
  4. if (profile != null) {
  5. String profileSpecificFile = prefix + "-" + profile + fileExtension;
  6. load(loader, profileSpecificFile, profile, defaultFilter, consumer);
  7. load(loader, profileSpecificFile, profile, profileFilter, consumer);
  8. // Try profile specific sections in files we've already processed
  9. for (Profile processedProfile : this.processedProfiles) {
  10. if (processedProfile != null) {
  11. String previouslyLoaded = prefix + "-" + processedProfile + fileExtension;
  12. load(loader, previouslyLoaded, profile, profileFilter, consumer);
  13. }
  14. }
  15. }
  16. // ...
  17. }

ConfigFileApplicationListener类中还实现了其他更多的功能,大家感兴趣的话可以debug进行阅读。

原文链接:《SpringBoot Profile使用详解及配置源码解析

CSDN学院:《Spring Boot 视频教程全家桶》

程序新视界:精彩和成长都不容错过

程序新视界-微信公众号

版权声明:本文为secbro原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/secbro/p/12088267.html