PostController 수정
package com.eom.controllerexercise.controller;
import com.eom.controllerexercise.dto.PostDto;
import com.eom.controllerexercise.service.PostService;
import org.springframework.web.bind.annotation.*;
import static org.springframework.web.bind.annotation.RequestMethod.*;
@RestController
@RequestMapping(value = "/post")
public class PostController {
PostService postService;
// 생성자 추가
public PostController(PostService postService) {
this.postService = postService;
}
@GetMapping
// getPost Method는 postservice를 호출해서 받은 postdto result 값을 반환을 한다.
public PostDto getPost(@RequestParam Integer id) {
PostDto result = postService.getPost(id);
return result;
}
@PostMapping
public String savePost(@RequestBody PostDto postDto) {
System.out.println(postDto.getId());
System.out.println(postDto.getTitle());
System.out.println(postDto.getContent());
System.out.println(postDto.getUsername());
return "POST /post";
}
@PutMapping
public String updatePost() {
return "PUT /post";
}
@DeleteMapping
public String deletePost() {
return "DELETE /post";
}
}
Postman
Console log
객체를 대신 만들어 postcontroller 객체 생성할 때 생성자 파라미터에 postservice 객체를 넘겨줬고 결과적으로
postcontroller에 postservice 멤버변수에서 생성된 postservice 객체를 참조하고 있다.
누가 이 역할을 해주냐?
Spring Framework 더 정확하게는 Spring Framework의 Spring IoC 컨테이너가 작업을 대신 수행 해준다.
config 패키지 생성 후 AppConfig 클래스 생성
package com.eom.controllerexercise.config;
import com.eom.controllerexercise.service.PostService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public PostService postService() {
return new PostService();
}
}
@Bean Annotation 이 붙은 메소드에서 현재 postservice 객체를 반환하고 있는데
Spring Framework 는 postservice 객체를 Bean으로 만들어서 관리를 하게 됩니다
Bean을 postcontroller에 생성자에 넣어줘서 postcontroller를 사용할 수 있게끔 설정을 해주는 것입니다.
PostService 클래스 변경 @Service Annotation 제거 하였음
package com.eom.controllerexercise.service;
import com.eom.controllerexercise.dto.PostDto;
import org.springframework.stereotype.Service;
public class PostService {
public PostDto getPost(Integer id) {
System.out.println("find post data from database by " + id);
System.out.println("validate dataa from database");
System.out.println("process data if necessary");
return new PostDto(id, "title", "this is content", "hjeom");
}
}
'Spring' 카테고리의 다른 글
스프링 빈과 의존성 주입 (0) | 2024.03.21 |
---|---|
Spring Service 실습 (0) | 2024.03.21 |
Spring Service (0) | 2024.03.21 |
REST API 문서의 활용 (0) | 2024.03.20 |
HTTP Method RequestBody 실습 (0) | 2024.03.20 |