의존성 주입이 끝난 뒤 초기화 작업을 수행하기 위해 사용하는 어노테이션으로 Spring Bean이 생성되고, 필요한 의존성 주입(@Autowired, @Value
)이 끝난 후 초기화 로직을 실행할 메서드에 붙인다.
생성자 → 의존성 주입 → @PostConstruct 순으로 진행
@Component
public class MyService {
@Autowired
private SomeRepository repository;
public MyService() {
System.out.println("1. 생성자 호출");
}
@PostConstruct
public void init() {
System.out.println("3. @PostConstruct 실행");
// 초기화 로직 예시: 캐시 데이터 로드
repository.loadCache();
}
}
new MyService()
→ 생성자 호출@Autowired
로 repository 주입@PostConstruct
메서드 실행DB에서 설정값 불러오기
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class ConfigCacheService {
private final ConfigRepository configRepository;
private Map<String, String> cache = new HashMap<>();
public ConfigCacheService(ConfigRepository configRepository) {
this.configRepository = configRepository;
}
@PostConstruct
public void init() {
System.out.println("애플리케이션 시작 시 ConfigCacheService 초기화");
loadConfig();
}
private void loadConfig() {
cache = configRepository.findAllAsMap();
System.out.println("Config 값 캐시 완료: " + cache);
}
// 다른 서비스에서 캐시된 값 가져갈 수 있도록 getter 제공
public String getConfig(String key) {
return cache.get(key);
}
}
import org.springframework.stereotype.Repository;
import java.util.Map;
import java.util.HashMap;
@Repository
public class ConfigRepository {
public Map<String, String> findAllAsMap() {
// 실제로는 DB에서 SELECT 해서 가져오겠지만,
// 여기서는 예시로 Map 반환
Map<String, String> data = new HashMap<>();
data.put("service.url", "<https://api.example.com>");
data.put("timeout", "5000");
return data;
}
}
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
private final ConfigCacheService configCacheService;
public TestController(ConfigCacheService configCacheService) {
this.configCacheService = configCacheService;
}
@GetMapping("/config")
public String getServiceUrl() {
return "서비스 URL: " + configCacheService.getConfig("service.url");
}
}
ConfigCacheService
빈 생성ConfigRepository
주입@PostConstruct
실행 → loadConfig()
호출외부 API 토큰 초기화
캐시 미리 적재
로그 초기화