本地和产品环境的不同属性变量(春季)


问题内容

我正在一个Spring Web应用程序上工作,在该应用程序中我需要具有在本地环境中具有不同价值而在生产环境中具有其他价值的变量。

例如,(文件上传目录)。对于本地环境和产品环境,我的文件上传目录不同。

目前,我正在通过检查主机名(如果为“
localhost”,然后为A,否则为B)并采用此方法来做到这一点。还有另一种通过属性文件解决此问题的方法,是否有人为我提供了解决方法?


问题答案:

您可以基于当前的一个或多个弹簧轮廓来加载属性。要设置弹簧轮廓,我主要将系统属性设置为spring.profiles.active所需的值,例如developmentproduction

这个概念很简单。从系统属性中读取当前活动的配置文件。生成文件名并使用加载属性文件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...
    }
}