您可以根据当前的弹簧轮廓或轮廓加载属性。要设置弹簧轮廓,我主要将名为 spring.profiles.active 的系统属性设置为所需的值,例如development 或 production。
这个概念很简单。从系统属性中读取当前活动的配置文件。使用PropertySourcesPlaceholderConfigurer 构建文件名并加载属性文件。使用PropertySourcesPlaceholderConfigurer 将更容易通过@Value 注释访问这些属性。请注意,此示例假定一个配置文件处于活动状态。当多个配置文件处于活动状态时,它可能需要格外小心。
基于 Java 的配置
@Configuration
public class MyApplicationConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
String activeProfile = System.getProperty("spring.profiles.active", "production");
String propertiesFilename = "app-" + activeProfile + ".properties";
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setLocation(new ClassPathResource(propertiesFilename));
return configurer;
}
}
您还可以导入多个使用@Profile 注释的配置类。 Spring 将根据当前活动的配置文件选择要使用的配置。每个类都可以将它自己的PropertySourcesPlaceholderConfigurer 版本添加到应用程序上下文中。
@Configuration
@Import({Development.class, Production.class})
public class MyApplicationConfiguration {}
@Configuration
@Profile("development")
public class Development {}
@Configuration
@Profile // The default
public class Production {}
正如 Emerson Farrugia 在他的评论中所说,@Profile 每班方法对于选择PropertySourcesPlaceholderConfigurer 有点过激。注释 @Bean 声明会简单得多。
@Configuration
public class MyApplicationConfiguration {
@Bean
@Profile("development")
public static PropertySourcesPlaceholderConfigurer developmentPropertyPlaceholderConfigurer() {
// instantiate and return configurer...
}
@Bean
@Profile // The default
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
// instantiate and return configurer...
}
}