[Spring] ResponseEntity의 유용한 메소드들 [200 OK, 400 Bad Request, 404 Not Found, 201 Created 등]
·
▣ Framework/Spring🍃
- ResponseEntity의 유용한 메소드들1. ResponseEntity.ok(): 200 OK 응답 반환return ResponseEntity.ok("성공");2. ResponseEntity.badRequest(): 400 Bad Request 응답 반환return ResponseEntity.badRequest().body("잘못된 요청입니다.");3. ResponseEntity.notFound(): 404 Not Found 응답 반환return ResponseEntity.notFound().build();4. ResponseEntity.created(): 201 Created 응답 반환 (새로운 리소스 생성 시)URI location = URI.create("/resource/1");return..
[Spring] ResponseEntity란? [HTTP 응답을 생성할 때 매우 유용한 클래스]
·
▣ Framework/Spring🍃
- ResponseEntity란?ResponseEntity는 Spring에서 HTTP 응답을 생성할 때 매우 유용한 클래스이다. 상태 코드, 헤더, 본문을 자유롭게 조작할 수 있기 때문에 다양한 HTTP 응답을 세밀하게 제어할 수 있다.- 기본 사용법 // 기본적인 ResponseEntity 사용 예시ResponseEntity response = new ResponseEntity(body, HttpStatus.OK);- 주요 사용 예시들 1) 기본적인 응답 ResponseEntity.ok() : 상태 코드 200 OK와 함께 응답 본문 반환 @ResponseBody@PostMapping("/example")public ResponseEntity example() { // 정상적으로 처리된 응답 ..
[Spring] @Autowired 옵션 처리 방법 [주입할 스프링 빈이 없어도 동작해야 할 때]
·
▣ Framework/Spring🍃
- 주입할 스프링 빈이 없어도 동작해야 할 때 주입할 스프링 빈이 없어도 동작해야 할 때가 있다. 자동 주입 대상이 없는 상태로 @Autowired만 사용하면 required의 기본값이 true라 오류가 발생한다. - @Autowired 옵션 처리 방법 @Autowired(required=false) : 자동 주입할 대상이 없으면 수정자 메서드 자체가 호출 안됨 @Nullable : 자동 주입할 대상이 없으면 null이 입력됨 Optional : 자동 주입할 대상이 없으면 Optional.empty 가 입력됨 //호출 안됨 @Autowired(required = false) public void setNoBean1(Member member) { System.out.println("setNoBean1 = ..
[Spring] 싱글톤, 무상태(stateless)로 설계하라! [Singleton 패턴 주의사항]
·
▣ Framework/Spring🍃
- 싱글톤, 무상태(stateless)로 설계하라! 객체 인스턴스를 하나만 생성해서 공유하는 싱글톤 방식은 여러 클라이언트가 하나의 같은 객체 인스턴스를 공유하기 때문에 싱글톤 객체는 상태를 유지(stateful)하게 설계하면 안된다. - 잘못된 설계 : 상태가 유지되는 경우 - StateFulService.java public class StateFulService { private int price; // 상태를 유지하는 필드 public void order(String name, int price) { System.out.println("name = " + name + " price = " + price); this.price = price; // 여기가 문제! } public int getPric..
[Spring] Object 타입으로 Bean을 조회하면 어떻게 될까? [스프링 빈 조회 시 상속 관계]
·
▣ Framework/Spring🍃
- Object 타입으로 Bean을 조회하면 어떻게 될까? 스프링에서는 부모 타입으로 빈을 조회하면, 자식 타입도 함께 조회한다. 즉, 모든 자바 객체의 최고 부모인 Object 타입으로 빈을 조회하면 모든 스프링 빈을 조회한다. - ApplicationContextExtendsFindTest.java import hello.core.discount.DiscountPolicy; import hello.core.discount.FixDiscountPolicy; import hello.core.discount.RateDiscountPolicy; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.spri..