1.13.3 @PropertySource 사용

@PropertySource어노테이션은 PropertySource를 Spring 환경에 추가하기위한 편리하고 선언적인 메커니즘을 제공한다.

testbean.name = myTestBean 키 - 값 쌍을 포함하는 app.properties라는 파일이 주어지면 다음 @Configuration 클래스는 @PropertySource를 사용하여 testBean.getName ()을 호출하면 myTestBean을 반환합니다.

@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {

    @Autowired
    Environment env;

    @Bean
    public TestBean testBean() {
        TestBean testBean = new TestBean();
        testBean.setName(env.getProperty("testbean.name"));
        return testBean;
    }
}

리소스 위치 @PropertySource에있는 모든 자리 표시 ${…​}자는 다음 예제와 같이 환경에 대해 이미 등록 된 속성 소스 집합에 대해 확인됩니다.

@Configuration
@PropertySource("classpath:/com/${my.placeholder:default/path}/app.properties")
public class AppConfig {

    @Autowired
    Environment env;

    @Bean
    public TestBean testBean() {
        TestBean testBean = new TestBean();
        testBean.setName(env.getProperty("testbean.name"));
        return testBean;
    }
}

my.placeholder이미 등록 된 속성 소스 중 하나 (예 : 시스템 속성 또는 환경 변수)에 있다고 가정하면 자리 표시자가 해당 값으로 확인됩니다. 그렇지 않은 경우 default/path기본값으로 사용됩니다. 디폴트를 지정하지 않고 프로퍼티를 해결할 수없는 경우, anIllegalArgumentException가 슬로우됩니다.

@PropertySource어노테이션은 자바 8 규칙에 따라 반복이다. 그러나 이러한 모든 @PropertySource주석은 구성 클래스에서 직접 또는 동일한 사용자 지정 주석 내의 메타 주석으로 같은 수준에서 선언해야합니다. 직접 주석과 메타 주석을 혼합하는 것은 권장되지 않습니다. 직접 주석이 메타 주석을 효과적으로 대체하기 때문입니다.

Last updated