Java Spring 配置文件在 Linux 中不起作用

Java Spring Profiles not working in Linux

我有一个在 Windows 上开发的 Web 应用程序,然后将其部署到 Linux(暂存和生产)。

我为每个环境创建了 3 个 .properties 文件:

我决定实施以下解决方案 - 在每台机器上创建具有相关值的环境变量 (dev / staging / prod) 并据此加载 corect .properties 文件。

该解决方案在 Windows 上完美运行,但我无法在 Linux 上以同样的方式运行。

这是我的代码:

Web.xml

<context-param>

    <param-name>contextInitializerClasses</param-name>

    <param-value>com.app.server.configuration.ConfigurableApplicationContextInitializer</param-value>

</context-param>

ConfigurableApplicationContextInitializer class:

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);

    }
}

上下文配置class:

    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 class - 主要打印 System.getenv("APP_ENV") 的值和正在打印的 "staging" 值。

但在我的应用程序中,我总是看到 - 开发而不是暂存。

我看到它的唯一方法是将 "hard-coded" 活动配置文件添加到 web.xml

<context-param>  
    <param-name>spring.profiles.active</param-name>  
    <param-value>dev</param-value>  
</context-param>

但我真的不想这样工作,我希望它能被自动识别和动态识别。

请帮忙:)

其中一个原因可能是您的 tomcat 在不同的用户下 运行,因此您可能需要为 that[=16= 设置环境变量] 运行 tomcat.

的用户

您还可以在 $CATALINA_BASE/bin/setenv.sh 文件

中为 tomcat 设置所需的环境变量

显然 setenv.sh 的正确位置是:usr/share/tomcat7/bin 我有一个旧文件 "dev" 值 :) 所以在修复这个文件之后 - 它完美地工作:)