hyeonga_code

@PostConstruct 어노테이션 본문

Spring

@PostConstruct 어노테이션

hyeonga 2024. 2. 15. 05:59
반응형

 

-- PostConstruct

---- 의존성 주입이 된 후 초기화를 수행하는 메소드

---- 클래스가 service를 수행하기 전에 발생

---- 다른 리소스에서 메소드를 호출하지 않아도 수행됨

 

-- 사용하는 이유

---- 기본적으로 생성자가 호출될 때 빈이 초기화되지 않은 상태

-- PostConstruct를 사용하면 빈이 초기화되며 의존성을 확인할 수 있다.

-- bean lifecycle에서 오직 한 번만 수행되므로 여러번 초기화되는 것을 방지할 수 있음

 

>> @PostConstruct를 사용하려면 pom.xml 파일에 라이브러리를 추가해야 import할 수 있다.

<!-- PostConstruct 어노테이션 -->
		<!-- https://mvnrepository.com/artifact/jakarta.annotation/jakarta.annotation-api -->
		<dependency>
		    <groupId>jakarta.annotation</groupId>
		    <artifactId>jakarta.annotation-api</artifactId>
		    <version>2.1.1</version>
		</dependency>

 

 

>> 기존 프로젝트에 적용하려고 하였는데 service로 넘어가는 로직이 아닌 controller에서만 처리되어 적용이 되지 않는 것인지 작동하지 않아 생략했다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.w2.client.controller;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RestController;
import com.siot.IamportRestClient.IamportClient;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
 
@RestController
@RequiredArgsConstructor
@PropertySource("classpath:config/webserverdb.properties")
public class PaymentController {
 
    @Value("${imp.api.key}")
    private String apiKey;
    
    @Value("${imp.api.secretKey}")
    private String secretKey;
    
    private IamportClient iamportClient;
 
    @PostConstruct
    public void init() {
        this.iamportClient = new IamportClient(apiKey, secretKey);
    }
    
}
 

 

반응형