Spring

@PostConstruct와 @Value 그리고 bean life cycle 관하여

point_Man 2023. 4. 3. 10:37

@Value의경우 appilcation.property의 값을 의존성 주입단계에서 필드주입방식으로 값을 할당한다 

아래와 같이 생성자를 통하여 headers에 값을 주려고하면 

빈생성 단계에서 해당된 값을 아직 주입 받지 않아서 null값이 할당 되고

그후 @Value를 통해 필드 주입이 되기 때문에 

의도한 대로 작동하지 않는다.

@Component
@Getter
@Setter
@ToString
public class HeadersDto {
    @Value("${headers.remote_token}")
    private String remote_token;
    @Value("${headers.Cookie}")
    private String Cookie;
    private String timestamp;
    @Value("${headers.client_id}")
    private String client_id;
    @Value("${headers.swap_key}")
    private String swap_key;
    private Map<String,String> headers ;


    public HeadersDto() {
        this.headers = new HashMap<>();
        this.headers.put("remote_token",this.remote_token);
        this.headers.put("Cookie",this.Cookie);
        this.headers.put("timestamp",this.timestamp);
        this.headers.put("client_id",this.client_id);
        this.headers.put("swap_key",this.swap_key);
    }
    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
        this.headers.put("timestamp",this.timestamp);
    }
}

 

 

 

 

그리하여 아래와같이 @PostConstruct애노테이션을 사용하면 bean 초기화 단계에서 한번 실행을 보장하기 때문에

빈생성 => 의존성 주입 => 초기화(@PostConstruct) 실행 단계로 실행되고

초기화 단계에서는 @Value의 값들이 할당된 상태이기 때문에 의도한 대로 작동하게 된다.

@Component
@Getter
@Setter
@ToString
public class HeadersDto {
    @Value("${headers.remote_token}")
    private String remote_token;
    @Value("${headers.Cookie}")
    private String Cookie;
    private String timestamp;
    @Value("${headers.client_id}")
    private String client_id;
    @Value("${headers.swap_key}")
    private String swap_key;
    private Map<String,String> headers ;


    @PostConstruct
    public Map<String, String> initHeaders() {
        this.headers = new HashMap<>();
        this.headers.put("remote_token",this.remote_token);
        this.headers.put("Cookie",this.Cookie);
        this.headers.put("timestamp",this.timestamp);
        this.headers.put("client_id",this.client_id);
        this.headers.put("swap_key",this.swap_key);
        return this.headers;
    }
    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
        this.headers.put("timestamp",this.timestamp);
    }
}