Spring boot 10주차 개발일지

이동규·2023년 7월 21일

Springboot 기초

목록 보기
10/13

Spring Stereotypes

스프링 컨테이너가 스프링 관리 컴퍼넌트로 식별하게 해주는 단순한 마커이다.

component - controller: RequestMapping과 함께 사용 MVC의 'Controller'역할을 함을 알림
                         - repository: Data Acess Object와 같이 실제 데이터 근원과 소통하는 부분임을 알림
                         - service: 비즈니스 로직이 구현된 부분임을 알림

@autowired란 무엇인가?

필요한 의존 객체의 “타입"에 해당하는 빈을 찾아 주입한다.

Target(객체의 요소)

ElementType.CONSTRUCTOR,
ElementType.METHOD,
ElementType.PARAMETER,
ElementType.FIELD,
ElementType.ANNOTATION_TYPE

Controller 부분

@RestController
@RequestMapping("post")
public class PostRestController {
    private static final Logger logger= LoggerFactory.getLogger(PostRestController.class);
    private final PostService postService;
    public PostRestController(
            @Autowired PostService postService // post Serivc의 구현체를 전달
    ) {
        this.postService = postService;
    }
    
    @PostMapping()
    @ResponseStatus(HttpStatus.CREATED)
    public void createPost(@RequestBody PostDto postdto){
        logger.info(postdto.toString());
        this.postService.createPost(postdto);
    }
    

    @GetMapping()
    public List<PostDto> readPostAll(){
        logger.info("Post all");
       return postService.readAll();
    }
   
    @GetMapping("{id}")
    public PostDto readPost(@PathVariable("id") int id){
        logger.info("in read post");
        return postService.readPost(id);
    }

    @PutMapping("{id}")
    public void updatePost(@PathVariable("id") int id,@RequestBody PostDto postdto){
        logger.info("target id: " + id);
        logger.info("update content" + postdto);
        postService.updatePost(id,postdto);
    }

    @DeleteMapping("{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deletePost(@PathVariable("id")int id){
        logger.info(id + "is Delete");
        postService.deletePost(id);

    }
}

PostService의 구현체이며 Service이다.

@Service
public class PostServiceSimple implements PostService{
    private static final Logger looger = LoggerFactory.getLogger(PostServiceSimple.class);// 정적
    private final PostRepository postRepository;//인터페이스
    public PostServiceSimple(
            @Autowired PostRepository postRepository//이 인페이스의 클래스
    ) {
        this.postRepository = postRepository;
    }

    @Override
    public void createPost(PostDto dto) {
        //Todo
        if(!this.postRepository.save(dto)){
            throw new RuntimeException("save failed");
        }
    }

    @Override
    public List<PostDto> readAll() {
            return this.postRepository.findAll();
    }

    @Override
    public PostDto readPost(int id) {
        return this.postRepository.findByID(id);
    }

    @Override
    public void updatePost(int id, PostDto dto) {
         this.postRepository.update(id, dto);

    }

    @Override
    public void deletePost(int id) {
        this.postRepository.delete(id);
    }

PostRepository의 구현체이며 Repository이다.

@Repository
public class PostInMemoryRepository implements PostRepository{
    private  final Logger logger= LoggerFactory.getLogger(PostInMemoryRepository.class);
    private final List<PostDto>postList;

    public PostInMemoryRepository() {
        this.postList = new ArrayList<>();

    }

    @Override
    public List<PostDto> findAll() {
        return this.postList;

    }

    @Override
    public PostDto findByID(int id) {
        return this.postList.get(id);
    }

    @Override
    public boolean save(PostDto dto) {
        return this.postList.add(dto);
    }

    @Override
    public boolean delete(int id) {
        this.postList.remove(id);
        return true;
    }

    @Override
    public boolean update(int id,PostDto dto) {
        PostDto targetPost= this.postList.get(id);// 기존 리스트에서 업데이트할 인덱스의 값을 targetPost 저장
        if (dto.getTitle()!= null){
            targetPost.setTitle(dto.getTitle());// 업데이트를 할 데이터의 제목이 null 값이 아니면 targetPost title 변경
        }

        if (dto.getContent() != null){
            targetPost.setContent(dto.getContent());// 업데이트를 할 데이터의 컨텐츠가 null 값이 아니면 targetPost content 변경
        }
        this.postList.set(id,targetPost);// post list 업데이트
        return true;
    }

}

0개의 댓글