我有一个在 Windows 上开发的 Web 应用程序,然后我将它部署到 Linux(Staging nad Production)。
我为每个环境创建了 3 个 .properties 文件:
- 应用程序-dev.properties
- 应用程序-staging.properties
- 应用程序-prod.properties
我决定实施以下解决方案 - 在每台机器上创建具有相关值(dev / staging / prod)的环境变量,并据此加载正确的 .properties 文件。
该解决方案在 Windows 上完美运行,但我无法让它在 Linux 上以同样的方式运行。
这是我的代码:
Web.xml
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>com.app.server.configuration.ConfigurableApplicationContextInitializer</param-value>
</context-param>
ConfigurableApplicationContextInitializer 类:
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
public class ConfigurableApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext context) {
String APP_ENV = System.getenv("APP_ENV");
context.getEnvironment().setActiveProfiles(APP_ENV);
System.setProperty("spring.profiles.active", APP_ENV);
}
}
上下文配置类:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("classpath:application-${spring.profiles.active}.properties")
public class ContextsConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer configurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Value("${FTPport}")
public String FTPport;
@Value("${FTPserver}")
在 Linux 中,我已经在数百万个地方定义了这个变量 (APP_ENV)。在 .environment 文件中,在 .bash 文件中,在 setenv.sh 文件中。同样当我做 printenv - 我在那里看到它。
我尝试创建简单的 java 类 - main 打印 System.getenv("APP_ENV") 的值和正在打印的 "staging" 值。
但是在我的应用程序中,我总是看到 - 开发而不是登台。
我看到登台的唯一方法是向 web.xml 添加“硬编码”活动配置文件
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
但我真的不想这样工作,我希望它能够被自动识别和动态识别。
请帮忙 :)