programing

스프링 부트 및 여러 외부 구성 파일

sourcetip 2022. 7. 15. 23:23
반응형

스프링 부트 및 여러 외부 구성 파일

클래스 경로에서 로드하려는 속성 파일이 여러 개 있습니다.[ 1 ] [ 1 ]아래에 ./src/main/resources의 일부입니다.myapp.jarspringcontext는 파일이 패스에 있을 파일은 클래스 패스에 .

<util:properties id="Job1Props"
    location="classpath:job1.properties"></util:properties>

<util:properties id="Job2Props"
    location="classpath:job2.properties"></util:properties>

이러한 속성을 외부 세트로 재정의하는 옵션도 필요합니다..cwd있어야 spring boot doc config "classpath" "classpath" 입니다., 이 단지 「Doc」의 「Doc」의 「Doc」의 「Doc」의 「.applicaiton.properties【설정하다

했을 때는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★.application.properties픽업되고 나머지 자산은 여전히 픽업됩니다./src/main/resourcesspring.config.location디폴트 세트는 아직 덮어쓰지 않았습니다.

여러 외부 구성 파일을 기본 설정 파일보다 우선하도록 하려면 어떻게 해야 합니까?

으로서 현재 것은 「 」입니다.app.config.location) (

java -jar myapp.jar app.config.location=file:./config

는 내 마음을 바꿨다.applicationcontext로로 합니다.

<util:properties id="Job2Props"
    location="{app.config.location}/job2.properties"></util:properties>

어플리케이션을 로드하는 동안 파일과 클래스 패스를 구분합니다.
★★★★

//psuedo code

if (StringUtils.isBlank(app.config.location)) {
            System.setProperty(APP_CONFIG_LOCATION, "classpath:");
}

하지 않고 패스상의 싶습니다. 하면 은 spring으로 덮어쓰게 됩니다.application.propertiesfilename을 클릭합니다.

업데이트: spring.config.location의 동작이 기본값을 추가하는 대신 덮어쓰게 되었습니다.기본값을 유지하려면 를 사용해야 합니다.이는 1.x에서 2.x로의 동작 변경입니다.


스프링 부트를 사용하는 경우 속성은 다음 순서로 로드됩니다(스프링 부트 참조 가이드의 외부 설정 참조).

  1. 명령줄 인수
  2. Java 시스템 속성(System.getProperties()).
  3. OS 환경 변수
  4. java로부터의 JNDI 어트리뷰트: comp/env
  5. 랜덤 속성만 있는 Random Value Property Source.*.
  6. 패키지화된 항아리 이외의 응용 프로그램 속성(AML 및 프로파일 배리언트를 포함한 application.properties).
  7. 항아리 내에 패키지된 응용 프로그램 속성(AML 및 프로파일 배리언트를 포함한 application.properties).
  8. @PropertySource는 @Configuration 클래스의 주석입니다.
  9. 기본 속성(Spring Application을 사용하여 지정).setDefaultProperties).

때 " " )@Value("${myprop}")해결은 역순으로 이루어집니다(9부터 시작).

하려면 을 합니다.spring.config.location속성 파일 또는 파일 위치(디렉토리)의 쉼표로 구분된 목록을 사용하는 속성입니다.

-Dspring.config.location=your/config/dir/

되어 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★application.propertiesfiles.complete files files files files files files files files.

-Dspring.config.location=classpath:job1.properties,classpath:job2.properties

그러면 로드된 파일에 2개의 속성 파일이 추가됩니다.

및 시 됩니다.spring.config.location즉, 후자가 항상 이전 속성에 설정된 속성을 덮어씁니다.('Spring Boot Reference Guide'의 이 섹션도 참조하십시오).

ifspring.config.location(파일이/로또, /로). /로 끝납니다(또, /로 ).spring.config.name디폴트 검색 경로 " " " "」classpath:,classpath:/config,file:,file:config/의 값에 관계없이 항상 사용됩니다.spring.config.location 응용 할 수 application.properties('Basename'('Basename'))spring.config.name실행 시 다른 파일로 덮어쓰고 기본값을 유지합니다.

Spring boot에서는 spring.config.location이 동작합니다.단, 쉼표로 구분된 속성 파일을 제공합니다.

아래 코드를 참조해 주세요.

@PropertySource(ignoreResourceNotFound=true,value="classpath:jdbc-${spring.profiles.active}.properties")
public class DBConfig{

     @Value("${jdbc.host}")
        private String jdbcHostName;
     }
}

기본 버전의 jdbc.properties를 응용 프로그램 내부에 넣을 수 있습니다.외부 버전은 다음과 같이 설정할 수 있습니다.

java -jar target/myapp.jar --spring.config.location=classpath:file:///C:/Apps/springtest/jdbc.properties,classpath:file:///C:/Apps/springtest/jdbc-dev.properties

jdbc 값인 spring.profiles.active 속성을 사용하여 설정된 프로파일 값을 기반으로 합니다.호스트가 픽업됩니다.그래서 (창에서)

set spring.profiles.active=dev

jdbc.host는 jdbc-dev.properties에서 값을 가져옵니다.

위해서

set spring.profiles.active=default

jdbc.host는 jdbc.properties에서 값을 가져옵니다.

Spring Boot 1.X 및 Spring Boot 2.X는 에 대해 동일한 옵션과 동작을 제공하지 않습니다.

엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠엠데넘 스프링 부츠 1호
스프링 부츠 2

환경 속성 소스 및 순서

한 Spring Boot 2를 합니다.PropertySource값을 합리적으로 덮어쓸 수 있도록 설계된 순서입니다.속성은 다음 순서로 고려됩니다.

  • 홈 디렉토리의 Devtools 글로벌 설정 속성(devtools가 활성 상태일 경우 ~/.spring-boot-devtools.properties)을 선택합니다.

  • @TestPropertySource주석을 추가합니다.

  • @SpringBootTest#properties주석 속성을 사용할 수 있습니다.명령줄 인수

  • ★★★★의 속성SPRING_APPLICATION_JSON(JSON).

  • ServletConfig parametersinit " " " " 입니다.

  • ServletContext parametersinit " " " " 입니다.

  • JNDI로부터의 java:comp/env.

  • 시스템 Java ")System.getProperties()를 참조해 주세요.

  • OS 환경 변수

  • A RandomValuePropertySource.*.*.*.*.* **.* .*.*.*.*.* .*.*.*.*.*.*.

  • jar 에 있는 프로파일 ( 「」 「」 「 」application-{profile}.propertiesYAML 종종)

  • 프로파일 의 어플리케이션 ( 「 」 )application-{profile}.propertiesYAML 종종)

  • 항아리 의 어플리케이션 (「」 「」 「 」 「 」application.propertiesYAML 종종)

  • 안에 응용 프로그램 「」 「」 「」 「」application.propertiesYAML 종종)

  • @PropertySource@Configuration를 클릭합니다)SpringApplication.setDefaultProperties를 참조해 주세요.

외부 속성 파일을 지정하려면 다음 옵션이 필요합니다.

  • jar 에 있는 프로파일 ( 「」 「」 「 」application-{profile}.propertiesYAML 종종)

  • 항아리 의 어플리케이션 (「」 「」 「 」 「 」application.propertiesYAML 종종)

  • @PropertySource@Configuration를 클릭합니다)SpringApplication.setDefaultProperties를 참조해 주세요.

이 세 가지 옵션 중 하나만 사용하거나 필요에 따라 조합할 수 있습니다.
를 들어 매우 의 속성만 디폴트 및 를 모두 할 수 .@PropertySource

application.properties 파일의 기본 위치

해서에 application.properties및 은 이들을 을 다음 순서로및 배리언트)을 추가합니다.

  • 현재 디렉토리의 /config 서브 디렉토리

  • 현재 디렉토리

  • classpath /config 패키지

  • 클래스 패스 루트

우선순위가 높은 것은 문자 그대로 다음과 같습니다.
classpath:/,classpath:/config/,file:./,file:./config/

특정 이름을 가진 속성 파일을 사용하는 방법

것은 「 「 」 )과 디폴트 입니다.★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★♪application.properties가하지 않을 수 .)가 적합하지 않을 수 있습니다. 질문과 이외의 파일을 여러 개 해야 할 수 .application.properties(일부러)
★★★★★★★★★★★★★★★★★.spring.config.name충분하지 않을 겁니다.

, '.'를 하여 위치를 인 위치를 지정해야 합니다.spring.config.location환경 속성(디렉토리 위치 또는 파일 경로를 쉼표로 구분한 목록)입니다.
파일명 패턴에 대해 자유롭게 하기 위해 디렉토리 목록보다 파일 경로 목록을 선호합니다.
이렇게 .

java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

이 방법은 폴더를 지정하는 것보다 가장 상세하지만 설정 파일을 매우 세밀하게 지정하고 효과적으로 사용되는 속성을 명확하게 문서화하는 방법이기도 합니다.

spring.config.location은 기본 위치를 추가하는 대신 기본 위치를 바꿉니다.

Spring Boot 1의 경우spring.config.location인수를 지정하면 스프링 환경에서 지정된 위치가 추가됩니다.
, 부터는 'Spring Boot 2'에서spring.config.location는 스프링에서 사용되는 기본 위치를 설명서에 기재되어 있는 스프링 환경 내의 지정된 위치로 대체합니다.

로케이션이 「」를 사용해 .spring.config.location이치노를 들어, 「」의 ,spring.config.location는, 값 「」으로 되어 있습니다.classpath:/custom-config/ ,file:./custom-config/는 다음과

  1. file:./custom-config/

  2. classpath:custom-config/

spring.config.location이제 모든 것을 확실하게 하기 위한 방법이 되었습니다.application.properties파일을 명시적으로 지정해야 합니다.
uber JAR 패키지가 JAR의 application.properties파, 、 그꽤 、 그찮데데데 。

spring.config.location Spring Boot 2를 사용할 수 .spring.config.additional-location「」이 「」spring.config.location매뉴얼에 기재되어 있는 대로 로케이션을 추가합니다.

이 「」를 사용해 되어 있는 .spring.config.additional-location이치노


실제로

따라서 OP 질문에서와 같이 지정할 외부 속성 파일 2개와 uber jar에 포함된 속성 파일 1개가 있다고 가정합니다.

지정한 컨피규레이션파일만 사용하려면 다음 절차를 수행합니다.

-Dspring.config.location=classpath:/job1.properties,classpath:/job2.properties,classpath:/applications.properties   

컨피규레이션파일을 디폴트로케이션으로 추가하는 순서는 다음과 같습니다.

-Dspring.config.additional-location=classpath:/job1.properties,classpath:/job2.properties

classpath:/applications.properties는 마지막 예에서는 필요하지 않습니다.기본 로케이션에는 이 로케이션이 있고 기본 로케이션은 덮어쓰지 않고 확장되어 있기 때문입니다.

Property Placeholder Configr를 보면 주석보다 사용하기 쉽다는 것을 알 수 있습니다.

예.

@Configuration
public class PropertiesConfiguration {


    @Bean
    public PropertyPlaceholderConfigurer properties() {
        final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
//        ppc.setIgnoreUnresolvablePlaceholders(true);
        ppc.setIgnoreResourceNotFound(true);

        final List<Resource> resourceLst = new ArrayList<Resource>();

        resourceLst.add(new ClassPathResource("myapp_base.properties"));
        resourceLst.add(new FileSystemResource("/etc/myapp/overriding.propertie"));
        resourceLst.add(new ClassPathResource("myapp_test.properties"));
        resourceLst.add(new ClassPathResource("myapp_developer_overrides.properties")); // for Developer debugging.

        ppc.setLocations(resourceLst.toArray(new Resource[]{}));

        return ppc;
    }

이것은 스프링 부츠를 사용한 간단한 접근법입니다.

TestClass.java

@Configuration
@Profile("one")
@PropertySource("file:/{selected location}/app.properties")
public class TestClass {

    @Autowired
    Environment env;

    @Bean
    public boolean test() {
        System.out.println(env.getProperty("test.one"));
        return true;
    }
}

app.properties 컨텍스트, 선택한 위치

test.one = 1234

스프링 부트 어플리케이션

@SpringBootApplication

public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(testApplication.class, args);
    }
}

및 미리 정의된 application.properties 컨텍스트

spring.profiles.active = one

spring.disable.active = 프로파일 이름/이름{콤마로 구분}을 설정하기만 하면 원하는 수만큼 구성 클래스를 작성하고 활성화/비활성화할 수 있습니다.

스프링 부츠는 매우 훌륭하다는 것을 알 수 있습니다.그냥 익숙해질 시간이 필요하기 때문에, 자신의 분야에서도 @Value를 사용할 수 있다는 것을 언급할 필요가 있습니다.

@Value("${test.one}")
String str;

저도 같은 문제가 있었어요.기동시에, Spring Boot application.properties 검출과 같이, 내부 설정 파일을 외부 파일로 덮어쓰는 기능을 가지고 싶다고 생각하고 있었습니다.이 경우 어플리케이션 사용자가 저장되어 있는user.properties 파일입니다.

요건:

다음 위치에서 파일을 로드합니다(이 순서대로).

  1. 클래스 패스
  2. 현재 디렉토리의 /config 서브dir.
  3. 현재 디렉토리
  4. 시작할 때 명령줄 매개 변수에 의해 지정된 디렉터리 또는 파일 위치

저는 다음과 같은 해결책을 생각해 냈습니다.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.Properties;

import static java.util.Arrays.stream;

@Configuration
public class PropertiesConfig {

    private static final Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);

    private final static String PROPERTIES_FILENAME = "user.properties";

    @Value("${properties.location:}")
    private String propertiesLocation;

    @Bean
    Properties userProperties() throws IOException {
        final Resource[] possiblePropertiesResources = {
                new ClassPathResource(PROPERTIES_FILENAME),
                new PathResource("config/" + PROPERTIES_FILENAME),
                new PathResource(PROPERTIES_FILENAME),
                new PathResource(getCustomPath())
        };
        // Find the last existing properties location to emulate spring boot application.properties discovery
        final Resource propertiesResource = stream(possiblePropertiesResources)
                .filter(Resource::exists)
                .reduce((previous, current) -> current)
                .get();
        final Properties userProperties = new Properties();

        userProperties.load(propertiesResource.getInputStream());

        LOG.info("Using {} as user resource", propertiesResource);

        return userProperties;
    }

    private String getCustomPath() {
        return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + PROPERTIES_FILENAME;
    }

}

이제 응용 프로그램은 클래스 경로 리소스를 사용하지만 지정된 다른 위치에서도 리소스를 확인합니다.마지막으로 존재하는 리소스가 선택되어 사용됩니다.java - jar myapp . jar --properties . location = / directory / myproperties . properties to java java java which which which which with로 앱을 기동하여 보트를 띄우는 속성 위치를 사용할 수 있습니다.

중요한 세부 사항은 다음과 같습니다.속성이 설정되지 않은 경우 오류를 방지하려면 @Value 주석의 properties.location에 대해 빈 문자열을 기본값으로 사용합니다.

properties.location의 표기법은 다음과 같습니다.프로퍼티 파일의 디렉토리 또는 경로를 properties.location으로 사용합니다.

특정 속성만 재정의하는 경우 setIgnoreResourceNotFound(true)를 사용하는 PropertiesFactoryBean을 리소스 배열로 설정할 수 있습니다.

이 솔루션은 여러 파일을 처리할 수 있도록 확장할 수 있습니다.

편집

여기에서는 여러 파일에 대한 솔루션:) 이전과 마찬가지로 Properties Factory Bean과 조합할 수 있습니다.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toMap;

@Configuration
class PropertiesConfig {

    private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);
    private final static String[] PROPERTIES_FILENAMES = {"job1.properties", "job2.properties", "job3.properties"};

    @Value("${properties.location:}")
    private String propertiesLocation;

    @Bean
    Map<String, Properties> myProperties() {
        return stream(PROPERTIES_FILENAMES)
                .collect(toMap(filename -> filename, this::loadProperties));
    }

    private Properties loadProperties(final String filename) {
        final Resource[] possiblePropertiesResources = {
                new ClassPathResource(filename),
                new PathResource("config/" + filename),
                new PathResource(filename),
                new PathResource(getCustomPath(filename))
        };
        final Resource resource = stream(possiblePropertiesResources)
                .filter(Resource::exists)
                .reduce((previous, current) -> current)
                .get();
        final Properties properties = new Properties();

        try {
            properties.load(resource.getInputStream());
        } catch(final IOException exception) {
            throw new RuntimeException(exception);
        }

        LOG.info("Using {} as user resource", resource);

        return properties;
    }

    private String getCustomPath(final String filename) {
        return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + filename;
    }

}

스프링 부트에서는, 다른 환경용으로 다른 프로파일을 써넣을 수 있습니다.예를 들어 프로덕션, QA, 로컬 환경용으로 개별의 속성 파일을 작성할 수 있습니다.

application-local.properties 파일은 로컬머신에 따른 구성을 포함하고 있습니다.

spring.profiles.active=local

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=users
spring.data.mongodb.username=humble_freak
spring.data.mongodb.password=freakone

spring.rabbitmq.host=localhost
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.port=5672

rabbitmq.publish=true

마찬가지로 application-prod.properties와 application-qa.properties를 원하는 수만큼 쓸 수 있습니다.

그런 다음 여러 환경에서 응용 프로그램을 시작하는 스크립트를 작성합니다.

mvn spring-boot:run -Drun.profiles=local
mvn spring-boot:run -Drun.profiles=qa
mvn spring-boot:run -Drun.profiles=prod

이와 비슷한 문제가 발생했는데, 그 원인을 알게 되었습니다.application.properties 파일의 소유권과 rwx 속성이 잘못되어 있습니다.따라서 Tomcat이 application.properties 파일을 시작할 때 다른 사용자가 소유했지만 올바른 위치에 있었습니다.

$ chmod 766 application.properties

$ chown tomcat application.properties

여러 파일을 정의할 수 있는 @mxsb 솔루션의 수정 버전입니다.이 경우 이 파일은 yml 파일입니다.

application-dev.yml에 -dev.yml이 포함된 모든 yml을 삽입할 수 있는 설정을 추가했습니다.이것은 특정 파일의 리스트가 될 수도 있습니다."classpath:/test/test.yml, classpath:/test2/test.yml"

application:
  properties:
    locations: "classpath*:/**/*-dev.yml"

속성 맵을 가져오는 데 도움이 됩니다.

@Configuration

public class PropertiesConfig {

private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);

@Value("${application.properties.locations}")
private String[] locations;

@Autowired
private ResourceLoader rl;

@Bean
Map<String, Properties> myProperties() {
    return stream(locations)
            .collect(toMap(filename -> filename, this::loadProperties));
}

private Properties loadProperties(final String filename) {

    YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    try {
        final Resource[] possiblePropertiesResources = ResourcePatternUtils.getResourcePatternResolver(rl).getResources(filename);
        final Properties properties = new Properties();
        stream(possiblePropertiesResources)
                .filter(Resource::exists)
                .map(resource1 -> {
                    try {
                        return loader.load(resource1.getFilename(), resource1);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).flatMap(l -> l.stream())
                .forEach(propertySource -> {
                    Map source = ((MapPropertySource) propertySource).getSource();
                    properties.putAll(source);
                });

        return properties;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
}

단, 제 경우처럼 각 프로파일에 대해 yml 파일을 분할하여 로드하고 콩 초기화 전에 스프링 구성에 직접 삽입해야 했습니다.

config
    - application.yml
    - application-dev.yml
    - application-prod.yml
management
    - management-dev.yml
    - management-prod.yml

...알고 계시죠?

컴포넌트가 약간 다릅니다.

@Component
public class PropertiesConfigurer extends     PropertySourcesPlaceholderConfigurer
    implements EnvironmentAware, InitializingBean {

private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfigurer.class);

private String[] locations;

@Autowired
private ResourceLoader rl;
private Environment environment;

@Override
public void setEnvironment(Environment environment) {
    // save off Environment for later use
    this.environment = environment;
    super.setEnvironment(environment);
}

@Override
public void afterPropertiesSet() throws Exception {
    // Copy property sources to Environment
    MutablePropertySources envPropSources = ((ConfigurableEnvironment) environment).getPropertySources();
    envPropSources.forEach(propertySource -> {
        if (propertySource.containsProperty("application.properties.locations")) {
            locations = ((String) propertySource.getProperty("application.properties.locations")).split(",");
            stream(locations).forEach(filename -> loadProperties(filename).forEach(source ->{
                envPropSources.addFirst(source);
            }));
        }
    });
}


private List<PropertySource> loadProperties(final String filename) {
    YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    try {
        final Resource[] possiblePropertiesResources = ResourcePatternUtils.getResourcePatternResolver(rl).getResources(filename);
        final Properties properties = new Properties();
        return stream(possiblePropertiesResources)
                .filter(Resource::exists)
                .map(resource1 -> {
                    try {
                        return loader.load(resource1.getFilename(), resource1);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).flatMap(l -> l.stream())
                .collect(Collectors.toList());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

}

application.properties 파일에 지정된 값을 덮어쓰려면 응용 프로그램을 실행하는 동안 활성 프로파일을 변경하고 프로파일의 응용 프로그램 속성 파일을 만들 수 있습니다.예를 들어 액티브프로파일을 "override"로 지정하고 /tmp 아래에 "application-override.properties"라는 새로운 응용 프로그램 속성 파일을 작성했다고 가정하면 실행할 수 있습니다.

java -jar yourApp.jar --spring.profiles.active="override" --spring.config.location="file:/tmp/,classpath:/" 

spring.config.location에서 지정된 값은 역순으로 평가됩니다.이 예에서는 classpat이 먼저 평가되고 다음으로 파일 값이 평가됩니다.

jar 파일 및 "application-override.properties" 파일이 현재 디렉토리에 있는 경우 실제로는 단순히 사용할 수 있습니다.

java -jar yourApp.jar --spring.profiles.active="override"

Spring Boot에서 속성 파일을 찾을 수 있기 때문에

나는 이것이 따르는 데 유용한 패턴이라는 것을 알았다.

@RunWith(SpringRunner)
@SpringBootTest(classes = [ TestConfiguration, MyApplication ],
        properties = [
                "spring.config.name=application-MyTest_LowerImportance,application-MyTest_MostImportant"
                ,"debug=true", "trace=true"
        ]
)

사용하기 .
은 .Spring의 .properties 파일).

디버깅 및 트레이스 설정도 추가 보너스로 포함되어 있습니다.따라서 필요에 따라 코멘트 아웃할 수 있습니다.]

디버깅/트레이스는 스프링이 로드하는 모든 파일과 로드하려는 파일의 이름을 덤프하기 때문에 매우 유용합니다.
실행 시 콘솔에 다음과 같은 행이 표시됩니다.

TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_MostImportant.properties' (file:./config/application-MyTest_MostImportant.properties) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_MostImportant.xml' (file:./config/application-MyTest_MostImportant.xml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_MostImportant.yml' (file:./config/application-MyTest_MostImportant.yml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_MostImportant.yaml' (file:./config/application-MyTest_MostImportant.yaml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_LowerImportance.properties' (file:./config/application-MyTest_LowerImportance.properties) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_LowerImportance.xml' (file:./config/application-MyTest_LowerImportance.xml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_LowerImportance.yml' (file:./config/application-MyTest_LowerImportance.yml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_LowerImportance.yaml' (file:./config/application-MyTest_LowerImportance.yaml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_MostImportant.properties' (file:./application-MyTest_MostImportant.properties) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_MostImportant.xml' (file:./application-MyTest_MostImportant.xml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_MostImportant.yml' (file:./application-MyTest_MostImportant.yml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_MostImportant.yaml' (file:./application-MyTest_MostImportant.yaml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_LowerImportance.properties' (file:./application-MyTest_LowerImportance.properties) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_LowerImportance.xml' (file:./application-MyTest_LowerImportance.xml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_LowerImportance.yml' (file:./application-MyTest_LowerImportance.yml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./application-MyTest_LowerImportance.yaml' (file:./application-MyTest_LowerImportance.yaml) resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_MostImportant.properties' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_MostImportant.xml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_MostImportant.yml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_MostImportant.yaml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.properties' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.xml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.yml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.yaml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_MostImportant.properties' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_MostImportant.xml' resource not found
DEBUG 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Loaded config file 'file:/Users/xxx/dev/myproject/target/test-classes/application-MyTest_MostImportant.yml' (classpath:/application-MyTest_MostImportant.yml)
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_MostImportant.yaml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_LowerImportance.properties' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_LowerImportance.xml' resource not found
DEBUG 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Loaded config file 'file:/Users/xxx/dev/myproject/target/test-classes/application-MyTest_LowerImportance.yml' (classpath:/application-MyTest_LowerImportance.yml)
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'classpath:/application-MyTest_LowerImportance.yaml' resource not found
TRACE 93941 --- [   main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped config file 'file:./config/application-MyTest_MostImportant-test.properties' (file:./config/application-MyTest_MostImportant-test.properties) resource not found

쓸 수 요.-Dspring.profiles.active=intranetapplication-properties. properties 입니다.은 제 파일명입니다.의 파일명은 합니다.사용하는 파일명은 다릅니다.

나는 이것을 알아내려고 할 때 많은 문제에 부딪혔다.여기 내 장치가 있어

Dev Env : Windows 10, Java : 1.8.0_25, Spring Boot : 2.0.3.릴리즈, 스프링 : 5.0.7.풀어주다

스프링은 'Sensible defaults for configuration'이라는 개념을 고수하고 있습니다.즉, 모든 재산 파일을 전쟁 파일의 일부로 보유해야 합니다.그런 다음 "--spring.config.additional-location" 명령줄 속성을 사용하여 외부 속성 파일을 가리킬 수 있습니다.그러나 속성 파일이 원래 전쟁 파일의 일부가 아니면 작동하지 않습니다.

데모코드: https://github.com/gselvara/spring-boot-property-demo/tree/master

언급URL : https://stackoverflow.com/questions/25855795/spring-boot-and-multiple-external-configuration-files

반응형