Spring 핵심원리 고급편 - 필드 동기화 적용

목차

필드 동기화 적용

Bean 으로 등록

@Configuration 
public class LogTraceConfig {
@Bean
public LogTrace logTrace() {
return new FieldLogTrace();
}
}
@RestController
@RequiredArgsConstructor
public class OrderControllerV3 {

private final OrderServiceV3 orderService;
private final LogTrace trace;

@GetMapping("/v3/request")
public String request(String itemId){

System.out.println(itemId);

TraceStatus status = null;
try {
status = trace.begin("OrderController.request()");
orderService.orderItem(itemId);
trace.end(status);

return "ok";
}catch (Exception e){
trace.exception(status, e);
throw e; // 예외를 반드시 던져 줘야 한다.
}
}
}
@Service
@RequiredArgsConstructor
public class OrderServiceV3 {

private final OrderRepositoryV3 orderRepository;
private final LogTrace trace;

public void orderItem (String itemId){
TraceStatus status = null;
try {
status = trace.begin("OrderService.orderItem()");
orderRepository.save(itemId);
trace.end(status);

}catch (Exception e){
trace.exception(status, e);
throw e; // 예외를 반드시 던져 줘야 한다.
}
}
}
@Repository
@RequiredArgsConstructor
public class OrderRepositoryV3 {

private final LogTrace trace;

public void save(String itemId){

TraceStatus status = null;
try {
status = trace.begin("OrderRepository.save()");

// 저장 로직
if(itemId.equals("ex")){
throw new IllegalStateException("예외 발생!");
}
sleep(1000);

trace.end(status);
}catch (Exception e){
trace.exception(status, e);
throw e; // 예외를 반드시 던져 줘야 한다.
}
}

private void sleep(int millis) {
try{
Thread.sleep(millis);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
Share