SpringBoot中为不同环境配置ApplicationContext

在Spring框架中,ApplicationContext可以使用配置文件针对不同的环境进行配置。配置文件提供了一种对特定配置或组件进行分组的机制,并根据环境或特定条件激活它们。

例如,我们可能需要在生产和开发环境中连接不同的数据库。通过为每个环境创建两个不同的配置文件,我们可以根据环境激活特定的配置文件。

注解@Profile用于将组件分组到特定的配置文件中,然后使用 的setActiveProfiles()方法ConfigurableEnvironment来激活该配置文件。 
此外,该@Profile注释还可以应用于任何 Spring 组件和 bean 方法。在本教程中,我们的重点是根据@Configuration注释创建配置文件。开始吧…

首先,创建一个组件类和带有注释的注释字段,@Value如下所示。

@Component
public class MailServerProperties {

 @Value("${jdon.mail.host}")
 private String host;

 @Value(
"${jdon.mail.port}")
 private int port;

 
//Getter methods
}

占位符值将由默认占位符解析程序根据活动配置文件进行解析。

在本教程中,我们将为两个环境(即生产环境和开发环境)创建两个配置文件。
我们期望每个环境都有不同的邮件服务器配置。因此,我们可以创建两个属性文件来存储各自的邮件服务设置,如下所示。

  • 应用程序-dev.properties

jdon.mail.host=smtp.stage.example.com jdon.mail.port=587
  • 应用程序产品属性

jdon.mail.host=smtp.example.com jdon.mail.port=587
根据活动配置文件,jdon.mail.host和 的值jdon.mail.port 将被注入到MailServerProperties' 字段中。

定义不同环境的配置
创建组件和属性文件后,让我们为生产和开发环境创建基于 Java 的配置。

@Configuration
@PropertySource("classpath:application-prod.properties")
@Profile(
"production")
public class ProdAppConfig {}
@Configuration
@Profile(
"development")
@PropertySource(
"classpath:application-dev.properties")
public class DevAppConfig {}

该@PropertySource注释将文件中的属性加载到 Spring 的环境中。

注释@Profile 可以在类级别或方法级别使用,将组件分组到特定的配置文件中。

现在,我们可以将两个配置导入到一个配置中,并同时启用带有注释的组件扫描,@ComponentScan如下所示。

@Configuration
@ComponentScan(basePackages = "com.jdon.spring.beans")
@Import({DevAppConfig.class, ProdAppConfig.class})
public class AppConfig {}

这里的@Import用于导入一个或多个@Configuration类。

启用特定于环境的配置文件
ConfigurableEnvironment 的 setActiveProfiles() 方法可用于激活配置文件。您可以从 ApplicationContext 或注入组件中获取 ConfigurableEnvironment。

下面的代码片段演示了如何激活开发配置文件。

AnnotationConfigApplicationContext applicationContext =
   new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().setActiveProfiles("development");
applicationContext.register(AppConfig.class);
applicationContext.refresh();

MailServerProperties mailServerProperties =
   applicationContext.getBean(MailServerProperties.class);
Assertions.assertEquals(
"smtp.stage.example.com", mailServerProperties.getHost());
Assertions.assertEquals(587, mailServerProperties.getPort());

结论
在本教程中,我们学习了为 Spring 应用程序中的不同环境创建和激活配置文件。我们还探索了 @Profile 注解的用法,以便将组件分组到特定的配置文件中。