복붙노트

[SPRING] 스프링 부트 어떻게 jar 파일 외부의 특성 파일을 읽는가?

SPRING

스프링 부트 어떻게 jar 파일 외부의 특성 파일을 읽는가?

내 대상 폴더에는 두 개의 폴더, lib 및 conf가 있습니다. 모든 등록 정보 파일은 conf 폴더에 저장되고 jar 파일은 lib 폴더에 저장됩니다.

spring 부트 이전에는 spring.xml의 다음 구성을 사용하여 @value를 사용했습니다.

<context:property-placeholder location="classpath*:*.properties"/>

와 같은 자바 코드에서 :

@Value("${name}")

private String name;

하지만 봄 부팅, 나는 자바 코드에서 어떻게 동일한 일을 해야할지 모르겠다.

나는 다음과 같이 노력했지만 일하지 않았다.

@Configuration
@PropertySource(value = "classpath:aaa.properties")
public class AppConfig {
    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
    }
}

해결법

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

    1.나는 약간의 질문과 설명의 제목으로 혼란스러워. 바라건대 내가 내 의견과 더 이상 당신을 혼동하지 않을 것입니다.

    나는 약간의 질문과 설명의 제목으로 혼란스러워. 바라건대 내가 내 의견과 더 이상 당신을 혼동하지 않을 것입니다.

    일반적으로 스프링 부트는 프로젝트 구조와 생성 된 바이너리에 대해 매우 잘 설명되어 있습니다. 권장 방법 (Spring Boot 의견)은 내부의 모든 의존성 (jar)을 가진 항아리를 만드는 것입니다. 팻 항아리 밖에서 정의 된 설정 속성 (또는 그것이 여러분이 만든 것이면 전쟁)이 필요한 경우, Spring Boot는 많은 옵션을 제공한다 (참고 자료 1 참조). 내 응용 프로그램이 시스템 등록 정보로 설정할 수있는 플래그 (spring.config.location)를 사용하여 외부 파일을 가리키는 것을 좋아합니다.

    java -jar -Dspring.config.location=<path-to-file> myBootProject.jar
    

    환경 변수를 사용하여 외부 파일이있는 위치를 정의하여 비슷한 작업을 수행 할 수 있습니다.

    이게 도움이 되길 바란다!

    참고 문헌 :  1. https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

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

    2.나는 당신이 나보다 같은 상황을 다루고 있는지 확신하지 못한다. 그러나 나의 경우에는 병과 외부에 * .properties 파일이있다. 항아리 외부에있는 * .properties 파일을 얻으려고 다음 작업을 수행했습니다.

    나는 당신이 나보다 같은 상황을 다루고 있는지 확신하지 못한다. 그러나 나의 경우에는 병과 외부에 * .properties 파일이있다. 항아리 외부에있는 * .properties 파일을 얻으려고 다음 작업을 수행했습니다.

    @Configuration
    public class ApplicationContext {
    
      @Bean
      public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
        properties.setLocation(new FileSystemResource("application.properties"));
        properties.setIgnoreResourceNotFound(false);
    
        return properties;
      }
    }
    

    application.properties 파일의 위치를 ​​설정할 때 FileSystemResource 객체를 만들었습니다.이 객체를 사용하면 jar 파일 옆에있는 properties.files 파일을 얻을 수 있습니다. 예를 들어 .properties 파일이 클래스 경로에있는 경우 ClassPathResource와 같은 다른 클래스를 사용할 수 있습니다. org.springframework.core.io 패키지에서 Resource 객체를 얻기 위해 Spring이 제공하는 다른 클래스를 읽을 수 있습니다. .

    이 의견이 도움이되기를 바랍니다.

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

    3.Spring Boot 문서에서 언급했듯이,

    Spring Boot 문서에서 언급했듯이,

    한 가지 방법은 'conf'디렉토리의 이름을 'config'로 바꾸는 것입니다. 그러면 문제없이 작동합니다. 따라서 위에서 언급 한 4 이외의 위치에서 속성 파일을 원할 때까지 추가 구성을 수행 할 필요가 없습니다.

    이 경우 속성 소스를 명시 적으로 정의 할 수 있습니다.

    @PropertySource("classpath:config.properties")
    

    여러 속성 파일의 경우

    @PropertySources({
        @PropertySource("classpath:config.properties"),
        @PropertySource("classpath:logging.properties"),
        @PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)
    })
    
  4. ==============================

    4.해결책을 찾았습니다.

    해결책을 찾았습니다.

    먼저 클래스를 만들고 @ConfigurationProperties를 추가하십시오.

    @ConfigurationProperties(prefix = "asdf", locations = "file:conf/aaa.properties")
    public class ASDF {
        private String name;   
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    위치에 적어주세요, 나는 classpath가 아닌 file을 사용합니다.

    그런 다음 애플리케이션 클래스에서 @EnableConfigurationProperties를 추가한다.

    @SpringBootApplication
    @EnableConfigurationProperties({ASDF.class, BBB.class})
    public class InitialBeanTestApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(InitialBeanTestApplication.class, args);
        }
    }
    

    conf 폴더에있는 config 파일을 읽을 수 있습니다.

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

    5.다른 해결책을 찾았습니다.

    다른 해결책을 찾았습니다.

    하나의 application.properties 파일에 모든 구성을 넣고 @Value ( "$ {name}")를 사용하여 코드를 읽습니다.

    어셈블리 파일을 사용하여 리소스 폴더의 파일을 대상 구성 폴더에 복사합니다.

    배포 후 config 폴더의 application.properties 파일을 변경하고 응용 프로그램을 실행해야합니다.

    이것은 스프링 부트가 application.properties 파일을 순서대로 읽으므로.

    • 현재 디렉토리에있는 / config 하위 디렉토리

    • 현재 디렉토리

    • classpath / config 패키지

    • classpath 루트

    하지만 이것은 하나의 속성 파일에 대해 작동합니다. 여러 속성 파일이 아님

  6. from https://stackoverflow.com/questions/41754459/spring-boot-how-to-read-properties-file-outside-jar by cc-by-sa and MIT license