Study/spring

[Java] Spring @ConfigurationProperties 어노테이션 사용법

 

스프링에서 @ConfigurationProperties 어노테이션은 외부의 값을 주입받기 위해 사용됩니다.

@ConfigurationProperties로 변수 혹은 내부 객체에 매핑하는 방법에 대해 설명드리겠습니다.

 

@ConfigurationProperties

.properties와 같은 외부 구성 파일에 정의된 값들을 자바 객체에 매핑할 수 있습니다.

다음과 같이 사용할 수 있습니다.

 

변수 매핑 방법

application.properties 파일에 다음과 같이 프로퍼티를 추가합니다.

# application.properties
app.test.name=Test App Name

# application.yml
app:
  test:
    name: Test App Name

 

추가한 프로퍼티를 자바 객체로 매핑하려면 아래처럼 설정하면 됩니다.

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "app.test")
public class TestConfig {
    private String name;
}

 

Setter나 생성자같이 값을 주입할 수단이 없으면 스프링 실행 시 오류가 발생합니다.

값을 주입할 방법이 없으면 스프링 실행 시 오류 발생
값을 주입할 방법이 없으면 스프링 실행 시 오류 발생

name 프로퍼티에 대한 setter가 없다고 합니다.

 

설정을 마치면 사용을 해봅시다.

@RestController
public class TestRestController {

    @Autowired
    private TestConfig config;

    @GetMapping("/properties")
    public String getProperties() {
        return config.getName();
    }
}

외부 설정 파일에 있던 app.test.name의 값을 가져와서 반환하는 API를 만들었습니다.

 

properties 설정 프로퍼티 값 사용 결과
properties 설정 프로퍼티 값 사용 결과

값을 잘 가져왔습니다.

 

 

 

 

객체 매핑 방법

@ConfigurationProperties로 매핑한 자바 클래스 안에 있는 클래스에도 매핑이 가능합니다.

properties 파일을 다음과 같이 설정합니다.

app.test.additional.property1: property1
app.test.additional.property2: property2

 

자바 클래스를 다음과 같이 구성합니다.

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "app.test")
public class TestConfig {

    private String name;

    private Additional additional;

    @Getter
    @Setter
    public static class Additional {
        private String property1;
        private String property2;
    }
}

 

외부 프로퍼티값을 가져다 쓸 API를 생성합니다.

@RestController
public class TestRestController {

    @Autowired
    private TestConfig config;

    @GetMapping("/properties/object")
    public String getObjectProperties() {
        return config.getAdditional().getProperty1() + ", " + config.getAdditional().getProperty2();
    }
}

 

API를 실행합니다.

외부 설정값을 내부 객체에 주입한 값을 가져온 결과
외부 설정값을 내부 객체에 주입한 값을 가져온 결과

내부 객체의 값을 잘 가져왔습니다.

 

읽으면 좋은 글

[Java] Spring @Value 어노테이션 사용법

 

[Java] Spring @Value 어노테이션 사용법

스프링의 @Value 어노테이션은 @ConfigurationProperties처럼 외부 설정 값을 가져오기 위해 사용됩니다. @ConfigurationProperties는 외부 설정 값을 객체로 매핑할 때 사용되고, @Value는 단일 값을 매핑할 때 사

priming.tistory.com