簡體   English   中英

如何在 spring 引導中從不同位置讀取活動配置文件?

[英]how to read active profile from different location in spring boot?

我在 src/main/resources 中有我的 application.properties 文件,並且在不同的目錄中有不同的活動配置文件(application-dev.properties 和 application-prod.properties)作為 src/main/resources/properties。

我正在使用 springboot 版本 2.7.5

我試圖在 directory-src/main/resources spring.profiles.active=dev 中的 application.properties 文件中配置它

但它沒有從目錄 src/main/resources/properties 中讀取 application-dev.properties

為了解決這個問題,我創建了兩個 class

@Configuration
public class ActiveProfileConfiguration extends AbstractSecurityWebApplicationInitializer{

    private static final Logger log = LoggerFactory.getLogger(ApplicationJPAConfiguration.class);
    private static final String SPRING_PROFILES_ACTIVE = "SPRING_PROFILES_ACTIVE";
    String profile;
        protected void setSpringProfile(ServletContext servletContext) {
    if(null!= System.getenv(SPRING_PROFILES_ACTIVE)){
        profile=System.getenv(SPRING_PROFILES_ACTIVE);
    }else if(null!= System.getProperty(SPRING_PROFILES_ACTIVE)){
        profile=System.getProperty(SPRING_PROFILES_ACTIVE);
    }else{
        profile="local";
    }
    log.info("***** Profile configured  is  ****** "+ profile);

    servletContext.setInitParameter("spring.profiles.active", profile);
    }
    
}

@Configuration
@Profile("local")
public class DevPropertyReader {

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
    Resource[] resources = new ClassPathResource[] { new ClassPathResource("application.properties"), new ClassPathResource("EnvironmentProfiles/application-local.properties") };
    ppc.setLocations(resources);
    ppc.setIgnoreUnresolvablePlaceholders(true);
    System.out.println("env active profile");
    return ppc;
    }
    
}

但是仍然無法解決這個問題。

Spring 不會在您的自定義/properties文件夾中查找屬性文件:

21.2 應用程序屬性文件 SpringApplication將從以下位置的application.properties文件中加載屬性,並將它們添加到Spring Environment中:

  • 當前目錄的 /config 子目錄。
  • 當前目錄
  • 一個配置 package
  • 類路徑根

https://docs.spring.io/spring-boot/docs/1.0.1.RELEASE/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files

最簡單的解決方案是將其移動到src/main/resources文件夾的根目錄下。

Place.properties 結構如下:

src/
├─ main/
│  ├─ resources/
│  │  ├─ application.properties
│  │  ├─ application-dev.properties
│  │  ├─ application-prod.properties

下面的 Dockerfile 示例在運行您的應用程序時設置了正確的 Spring 配置文件:

ENTRYPOINT java -Dspring.profiles.active=prod -jar /app.jar

但是通過 WebApplicationInitializer、Beans XML、Maven 配置文件等還有許多其他選項...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM