복붙노트

[SPRING] 지역 및 제품 환경 (Spring)에 대한 다른 속성 변수

SPRING

지역 및 제품 환경 (Spring)에 대한 다른 속성 변수

Spring 환경에서 다른 값을 가질 변수가 필요한 곳에서 Spring 웹 애플리케이션을 만들고 있습니다.

예를 들면 (파일 업로드 디렉토리). 내 파일 업로드 디렉토리는 지역 및 제품 환경에 따라 다릅니다.

현재 나는 호스트 이름 ( 'localhost'가 A else B라면)을 검사하고이 접근법을 취함으로써이를 수행하고있다. 거기에 속성 파일을 통해이 문제를 해결할 수있는 또 다른 방법이 있습니다, 나에게 접근 방법에 대한 조언을 해주는 사람이 있습니까?

해결법

  1. ==============================

    1.현재 스프링 프로파일 또는 프로파일을 기반으로 특성을로드 할 수 있습니다. 스프링 프로파일을 설정하기 위해 대부분 spring.profiles.active라는 시스템 속성을 원하는 값으로 설정했습니다. 개발 또는 생산.

    현재 스프링 프로파일 또는 프로파일을 기반으로 특성을로드 할 수 있습니다. 스프링 프로파일을 설정하기 위해 대부분 spring.profiles.active라는 시스템 속성을 원하는 값으로 설정했습니다. 개발 또는 생산.

    개념은 매우 간단합니다. 시스템 프로퍼티에서 현재 활성화 된 프로파일을 읽는다. 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 per class 접근법은 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...
        }
    }
    
  2. ==============================

    2.스프링 프로파일을 전혀 사용하지 않는 한 가지 해결책은 다음과 같은 것을 사용하는 것입니다 :

    스프링 프로파일을 전혀 사용하지 않는 한 가지 해결책은 다음과 같은 것을 사용하는 것입니다 :

    <context:property-placeholder location="classpath*:config.properties,file:/path/config/config.properties"
                                  ignore-unresolvable="false" ignore-resource-not-found="true"/>
    

    이것은 Spring이 jar / war에있는 두 파일과 파일 시스템의 어느 위치 에나있을 수있는 파일을 사용하여 속성을 찾도록 지시합니다. ignore-resource-not-found는 파일 중 하나가 발견되지 않으면 Spring이 불평하지 않는다는 것을 의미합니다.

    이 설정을 사용하면 두 번째 파일을 개발자 작업자가 제어 할 수 있으며 원하는 항목을 포함 할 수 있으므로 클래스 경로 속성 파일 파일의 모든 속성을 재정의 할 수 있습니다.

    최신 정보:

    구성 클래스에서 다음 bean을 사용하여 Java Config에서도 동일한 작업을 수행 할 수 있습니다.

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        final PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
    
        Resource[] resources = new Resource[ ] {
                new ClassPathResource( "config.properties" ),
                new FileSystemResource("/path/config/config.properties")
        };
    
        pspc.setLocations( resources );
        pspc.setIgnoreResourceNotFound(true);
        pspc.setIgnoreUnresolvablePlaceholders(false);
        return pspc;
    }
    
  3. ==============================

    3.나는 반나절 동안이 일을 끝내고 있었고, 내가 끝내는 해결책은 다른 해답들의 조합이다.

    나는 반나절 동안이 일을 끝내고 있었고, 내가 끝내는 해결책은 다른 해답들의 조합이다.

    Bart의 솔루션은 동적 인 소품 파일을 사용하는 단점을 가지고있어서 IDE가 "잊어 버렸습니다"모든 것을 잊었고 어떤 속성을 사용했는지, 어디에서 사용했는지 제안 할 수 없었습니다. Geoand 솔루션에는 구성 파일이 "어딘가에 있어야합니다"라는 단점이있었습니다. 특정 시나리오에서는 이것이 왜 편리한 지 알 수 있지만 어떤 환경에서도 단일 아티팩트를 배포 할 수 있기를 선호하므로 앱을 전략적 장소에 "파킹"할 필요가 없습니다.

    그러므로 나를위한 해결책은 다음과 같습니다.

    - config.properties (default properties, usually local development env)
    - config.staging.properties (overrides depending on the env)
    - config.prod.properties (overrides depending on the env)
    
    <context:property-placeholder ignore-resource-not-found="true"
                                  location="config.properties,
                                            config-${profile}.properties"/>
    

    마법은 ignore-resource-not-found = "true"로 특별한 프로필 변수를 설정하지 않고도 내 지역 개발 환경을 실행할 수있게 해줍니다. 누락 된 파일은 무시됩니다.

    대신 다양한 배포 환경에서 해당 변수를 설정합니다. -Dprofile = staging을 입력하면 파일이 발견되고 재정의가 적용됩니다.

  4. ==============================

    4.서버를 시작할 때 스프링 부트 응용 프로그램에 -Dspring.profile.active = local을 추가 할 수 있습니다. application-local.properties를 선택합니다.

    서버를 시작할 때 스프링 부트 응용 프로그램에 -Dspring.profile.active = local을 추가 할 수 있습니다. application-local.properties를 선택합니다.

  5. from https://stackoverflow.com/questions/22757318/different-property-variable-for-local-and-prod-environment-spring by cc-by-sa and MIT license