복붙노트

[SPRING] 스프링 부트 : 뚱뚱한 항아리가있는 임의의 디렉토리에서 외부 application.properties 파일을 사용할 수 있습니까?

SPRING

스프링 부트 : 뚱뚱한 항아리가있는 임의의 디렉토리에서 외부 application.properties 파일을 사용할 수 있습니까?

여러 application.properties 파일을 가질 수 있습니까? (편집 : 제목에이 질문이 진전되었음을 유의하십시오.)

나는 2 개의 파일을 가지고있다.

2 파일의 이름은 모두 'application.properties'입니다.

두 파일의 내용을 '병합'할 수 있습니까? (두 번째 속성 값이 첫 번째 속성 값보다 우선 함) 또는 하나의 파일이 있으면 다른 파일이 무시됩니까?

업데이트 1 : 내용을 '병합'할 수 있습니다. 어제는 첫 번째 것이 무시당한 것 같았습니다. 그러나 무언가가 깨 졌기 때문입니다. 이제는 잘 작동합니다.

업데이트 2 : 다시 돌아 왔습니다! 다시 두 파일 중 하나만 적용됩니다. 그것은 이상합니다 ... 그것은 Spring Tool Suite를 사용하여 app jar 파일을 만든 후에 시작되었습니다. 그리고 Jar 버전은 STS에서 실행되는 확장 버전의 동작이 다양하지만 두 번째 버전은 클래스 패스에서 항상 무시됩니다. 어디에서 조사를 시작할 수 있습니까?

업데이트 3 :

Jar 버전의 동작은 사실 정확합니다. 그것은 java.exe의 사양입니다. -jar 옵션을 지정하면 java.exe는 -classpath 옵션과 CLASSPATH 환경 변수를 모두 무시하며 클래스 경로에는 jar 파일 만 포함됩니다. 따라서 클래스 경로의 두 번째 application.properties 파일은 무시됩니다.

이제 클래스 패스의 두 번째 application.properties를로드 할 수 있습니까?

업데이트 4 :

-jar 옵션을 사용하는 동안 외부 경로에 application.properties 파일을로드 할 수있었습니다.

열쇠는 PropertiesLauncher였습니다.

PropertiesLauncher를 사용하려면 pom.xml 파일을 다음과 같이 변경해야합니다.

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>  <!-- added -->
                <layout>ZIP</layout> <!-- to use PropertiesLaunchar -->
            </configuration>
        </plugin>
    </plugins>
</build>

이를 위해 다음 StackOverflow 질문을 참조했습니다. 스프링 부트 속성 시작 프로그램을 사용할 수 없습니다. BTW, Spring Boot Maven Plugin 문서 (http://docs.spring.io/spring-boot/docs/1.1.7.RELEASE/maven-plugin/repackage-mojo.html)에는 ZIP 트리거를 지정하는 언급이 없습니다. PropertiesLauncher가 사용됩니다. (아마 다른 문서에서?)

jar 파일이 빌드 된 후에 PropertiesLauncher가 항아리의 META-INF / MENIFEST.MF에서 Main-Class 속성을 검사하여 사용된다는 것을 알 수있었습니다.

자, 다음과 같이 항아리를 실행할 수 있습니다 (Windows의 경우).

java -Dloader.path=file:///C:/My/External/Dir,MyApp-0.0.1-SNAPSHOT.jar -jar MyApp-0.0.1-SNAPSHOT.jar

응용 프로그램 jar 파일은 loader.path에 포함되어 있습니다.

이제 C : \ My \ External \ Dir \ config의 application.properties 파일이로드됩니다.

보너스로, 해당 디렉토리의 모든 파일 (예 : 고정 html 파일)은 로더 경로에 있기 때문에 jar에서 액세스 할 수도 있습니다.

업데이트 2에서 언급 한 비 jar (확장) 버전의 경우 클래스 경로 순서 문제가있을 수 있습니다.

(BTW, 질문 제목을이 문제에보다 구체적으로 변경했습니다.)

해결법

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

    1.Spring 부트의 기본값 (@EnableAutoConfiguration 또는 @SpringBootApplication을 사용 중이며 속성 소스 처리를 변경하지 않았 음을 의미)을 변경하지 않은 경우 다음 순서 (가장 높은 우선 순위가 가장 낮습니다)로 속성을 찾습니다.

    Spring 부트의 기본값 (@EnableAutoConfiguration 또는 @SpringBootApplication을 사용 중이며 속성 소스 처리를 변경하지 않았 음을 의미)을 변경하지 않은 경우 다음 순서 (가장 높은 우선 순위가 가장 낮습니다)로 속성을 찾습니다.

    위 목록은이 문서의 일부로 언급되어 있습니다.

    즉, 속성이 발견되면 src / resources 아래에있는 application.properties는 / config 디렉토리의 application.properties에있는 패키지 된 jar의 "다음"과 동일한 이름의 속성에 의해 무시됩니다.

    Spring Boot가 사용하는이 기본 명령은 매우 쉬운 설정 외부화를 허용하여 응용 프로그램을 여러 환경 (dev, staging, production, cloud 등)에서 쉽게 구성 할 수있게합니다.

    속성 읽기를 위해 Spring Boot에서 제공하는 모든 기능을 보려면 (힌트 : application.properties에서 읽는 것보다 더 많은 기능이 있음) 문서의이 부분을 확인하십시오.

    위의 짧은 설명이나 전체 문서에서 볼 수 있듯이, Spring Boot 애플 리케이션은 매우 개발 친화적입니다!

  2. ==============================

    2.여기에 모두 문서에 설명되어 있습니다.

    여기에 모두 문서에 설명되어 있습니다.

    http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

    이것이 우선 순위라고 설명합니다.

    또한 다음과 같이 재정의 추가 속성 파일을 정의 할 수 있다고 지적합니다.

    java -jar myproject.jar 
        --spring.config.location=classpath:/overrides.properties
    

    spring.config.location을 사용하면 application.properties의 모든 기본 위치도 포함됩니다. 즉, application.properties에 기본값을 설정하고 특정 환경에 필요한대로 재정의 할 수 있습니다.

  3. ==============================

    3.다음과 같이 외부 속성 파일 경로를 사용하여 스프링 부팅 응용 프로그램을 시작할 수 있습니다.

    다음과 같이 외부 속성 파일 경로를 사용하여 스프링 부팅 응용 프로그램을 시작할 수 있습니다.

    java -jar {jar-file-name}.jar 
    --spring.config.location=file:///C:/{file-path}/{file-name}.properties
    
  4. ==============================

    4.-jar 옵션을 사용하는 동안 외부 경로에 application.properties 파일을로드 할 수있었습니다.

    -jar 옵션을 사용하는 동안 외부 경로에 application.properties 파일을로드 할 수있었습니다.

    열쇠는 PropertiesLauncher였습니다.

    PropertiesLauncher를 사용하려면 pom.xml 파일을 다음과 같이 변경해야합니다.

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>  <!-- added -->
                    <layout>ZIP</layout> <!-- to use PropertiesLaunchar -->
                </configuration>
            </plugin>
        </plugins>
    </build>
    

    이를 위해 다음 StackOverflow 질문을 참조했습니다. 스프링 부트 속성 시작 프로그램을 사용할 수 없습니다. BTW, Spring Boot Maven Plugin 문서 (http://docs.spring.io/spring-boot/docs/1.1.7.RELEASE/maven-plugin/repackage-mojo.html)에는 ZIP 트리거를 지정하는 언급이 없습니다. PropertiesLauncher가 사용됩니다. (아마 다른 문서에서?)

    jar 파일이 빌드 된 후에 PropertiesLauncher가 항아리의 META-INF / MENIFEST.MF에서 Main-Class 속성을 검사하여 사용된다는 것을 알 수있었습니다.

    자, 다음과 같이 항아리를 실행할 수 있습니다 (Windows의 경우).

    java -Dloader.path=file:///C:/My/External/Dir,MyApp-0.0.1-SNAPSHOT.jar -jar MyApp-0.0.1-SNAPSHOT.jar
    

    응용 프로그램 jar 파일은 loader.path에 포함되어 있습니다.

    이제 C : \ My \ External \ Dir \ config의 application.properties 파일이로드됩니다.

    보너스로, 해당 디렉토리의 모든 파일 (예 : 고정 html 파일)은 로더 경로에 있기 때문에 jar에서 액세스 할 수도 있습니다.

    업데이트 2에서 언급 한 비 jar (확장) 버전의 경우 클래스 경로 순서 문제가있을 수 있습니다.

  5. ==============================

    5.

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <layout>ZIP</layout> 
                </configuration>
            </plugin>
        </plugins>
    </build>
    
    java -Dloader.path=file:///absolute_path/external.jar -jar example.jar
    
  6. ==============================

    6.이것은 늦게 올 것 같지만 외부 구성을로드하는 가장 좋은 방법은 @propertySource ( "classpath : some.properties") 대신 java jar myapp.war을 사용하여 스프링 부트 응용 프로그램을 실행할 때 특히 유용하다고 생각합니다.

    이것은 늦게 올 것 같지만 외부 구성을로드하는 가장 좋은 방법은 @propertySource ( "classpath : some.properties") 대신 java jar myapp.war을 사용하여 스프링 부트 응용 프로그램을 실행할 때 특히 유용하다고 생각합니다.

    구성은 프로젝트의 루트 또는 war / jar 파일이 실행되는 위치에서로드됩니다.

    public class Application implements EnvironmentAware {
    
        public static void main(String[] args) throws Exception {
            SpringApplication.run(Application.class, args);
        }
    
        @Override
        public void setEnvironment(Environment environment) {
            //Set up Relative path of Configuration directory/folder, should be at the root of the project or the same folder where the jar/war is placed or being run from
            String configFolder = "config";
            //All static property file names here
            List<String> propertyFiles = Arrays.asList("application.properties","server.properties");
            //This is also useful for appending the profile names
            Arrays.asList(environment.getActiveProfiles()).stream().forEach(environmentName -> propertyFiles.add(String.format("application-%s.properties", environmentName))); 
            for (String configFileName : propertyFiles) {
                File configFile = new File(configFolder, configFileName);
                LOGGER.info("\n\n\n\n");
                LOGGER.info(String.format("looking for configuration %s from %s", configFileName, configFolder));
                FileSystemResource springResource = new FileSystemResource(configFile);
                LOGGER.log(Level.INFO, "Config file : {0}", (configFile.exists() ? "FOund" : "Not Found"));
                if (configFile.exists()) {
                    try {
                        LOGGER.info(String.format("Loading configuration file %s", configFileName));
                        PropertiesFactoryBean pfb = new PropertiesFactoryBean();
                        pfb.setFileEncoding("UTF-8");
                        pfb.setLocation(springResource);
                        pfb.afterPropertiesSet();
                        Properties properties = pfb.getObject();
                        PropertiesPropertySource externalConfig = new PropertiesPropertySource("externalConfig", properties);
                        ((ConfigurableEnvironment) environment).getPropertySources().addFirst(externalConfig);
                    } catch (IOException ex) {
                        LOGGER.log(Level.SEVERE, null, ex);
                    }
                } else {
                    LOGGER.info(String.format("Cannot find Configuration file %s... \n\n\n\n", configFileName));
    
                }
    
            }
        }
    
    }
    

    희망이 도움이됩니다.

  7. ==============================

    7.fat jar (-cp fat.jar) 또는 모든 jar (-cp "$ JARS_DIR / *")를 포함하는 클래스 경로와 다른 구성 설정 파일을 포함하는 다른 사용자 정의 구성 클래스 경로 또는 폴더를 사용하는 또 다른 유연한 방법입니다. 따라서 제한된 java -jar 대신 다음과 같이보다 유연한 클래스 경로 방법을 사용하십시오.

    fat jar (-cp fat.jar) 또는 모든 jar (-cp "$ JARS_DIR / *")를 포함하는 클래스 경로와 다른 구성 설정 파일을 포함하는 다른 사용자 정의 구성 클래스 경로 또는 폴더를 사용하는 또 다른 유연한 방법입니다. 따라서 제한된 java -jar 대신 다음과 같이보다 유연한 클래스 경로 방법을 사용하십시오.

    java \
       -cp fat_app.jar \ 
       -Dloader.path=<path_to_your_additional_jars or config folder> \
       org.springframework.boot.loader.PropertiesLauncher
    

    Spring-boot 실행 가능한 jar 문서와이 링크를 참조하십시오.

    일반적인 MainApps가 여러 개있는 경우 Spring Boot에게 어떤 메인 클래스를 실행 가능한 jar 파일로 사용할 지 알려주려면 어떻게해야합니까?

    loader.properties (아카이브 내의 디렉토리, 아카이브 또는 디렉토리의 쉼표로 구분 된 목록)에 환경 변수 LOADER_PATH 또는 loader.path를 설정하여 추가 위치를 추가 할 수 있습니다. 기본적으로 loader.path는 java -jar 또는 java -cp way 모두에서 작동합니다.

    언제나 그렇듯이 디버깅 목적으로 픽업해야하는 application.yml을 무시하고 정확하게 지정할 수 있습니다.

    --spring.config.location=/some-location/application.yml --debug
    
  8. ==============================

    8.yml 파일의 해결책 :

    yml 파일의 해결책 :

    1. yml을 jar 응용 프로그램과 동일한 디렉토리에 복사합니다.

    2. 실행 명령, xxx.yml의 예 :

    java -jar app.jar --spring.config.location=xxx.yml
    

    괜찮아요,하지만 시작 로거 정보 :

    No active profile set .........
    
  9. from https://stackoverflow.com/questions/26140784/spring-boot-is-it-possible-to-use-external-application-properties-files-in-arbi by cc-by-sa and MIT license