본문 바로가기
카테고리 없음

[Spring] 인프런 Spring 입문 - 회원 관리 예제

by 발담그는블로그 2024. 1. 1.

일반 웹 애플리케이션 구조

* 컨트롤러: 웹 MVC 컨트롤러

* 서비스: 비즈니스 로직

* 리포지토리: DB에 저장되는 데이터와 관련있는 로직. 도메인 객체를 DB에 저장

* 도메인: 비즈니스 도메인 객체 

 

로직 구현

* domain 패키지

- 멤버 객체. 멤버는 간단하게 id와 name으로 구성.

package hello.hellospring.domain;

public class Member {
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

* repository 패키지

- (Interface) MemberRepository

package hello.hellospring.repository;

import hello.hellospring.domain.Member;

import java.util.List;
import java.util.Optional;

public interface MemberRepository {
    Member save(Member member);
    Optional<Member> findById(Long id);
    Optional<Member> findByName(String name);
    List<Member> findAll();
}

 

- (Java Class) MemoryMemberRepository

package hello.hellospring.repository;

import hello.hellospring.domain.Member;

import java.util.*;

public class MemoryMemberRepository implements MemberRepository {

    private static Map<Long, Member> store = new HashMap<>();
    private static long sequence = 0L;

    @Override
    public Member save(Member member) {
        member.setId(++sequence);
        store.put(member.getId(), member);
        return member;
    }

    @Override
    public Optional<Member> findById(Long id) {
        return Optional.ofNullable(store.get(id));
    }

    @Override
    public Optional<Member> findByName(String name) {
        return store.values().stream()
                .filter(member -> member.getName().equals(name))
                .findAny();
    }

    @Override
    public List<Member> findAll() {
        return new ArrayList<>(store.values());
    }
}

 

검증 방법 - Test Code

package hello.hellospring.repository;

import hello.hellospring.domain.Member;
import org.assertj.core.util.VisibleForTesting;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

class MemoryMemberRepositoryTest {

    MemoryMemberRepository repository = new MemoryMemberRepository();

    @AfterEach
    public void afterEach() {
        repository.clearStore();
    }

    @Test
    public void save() {
        Member member = new Member();
        member.setName("spring");
        repository.save(member);

        Member result = repository.findById(member.getId()).get();
        Assertions.assertEquals(member, result);
    }

    @Test
    public void findByName() {
        Member member1 = new Member();
        member1.setName("spring1");
        repository.save(member1);

        Member member2 = new Member();
        member2.setName("spring2");
        repository.save(member2);

        Member result = repository.findByName("spring1").get();
        assertThat(result).isEqualTo(member1);
    }

    @Test
    public void findAll() {
        Member member1 = new Member();
        member1.setName("spring1");
        repository.save(member1);

        Member member2 = new Member();
        member2.setName("spring2");
        repository.save(member2);

        List<Member> result = repository.findAll();
        assertThat(result.size()).isEqualTo(2);
    }
}

 

테스트 메서드는 실행 순서가 따로 지정되어 있지 않음. 

그래서 테스트 메서드가 끝날때마다 store를 비워주는 로직을 개발하고, AfterEach 어노테이션으로 추가해야함.

public void clearStore() {
    store.clear();
}

 

회원 서비스 로직 구현 (비즈니스 로직)

단순한 객체 저장 및 조회 로직이 대부분인 repository 패키지와 다르게

서비스 패키지는 핵심 비즈니스 로직이 있다.

service 패키지 > memberService.cls

package hello.hellospring.service;

import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;

import java.util.List;
import java.util.Optional;

public class MemberService {
    // command + option + v ?
    // ctrl + p => 단축키 추천 ??

    private final MemberRepository repository = new MemoryMemberRepository();

    public Long join(Member member) {
        this.validateDuplicateMember(member);
        repository.save(member);
        return member.getId();
    }

    public void validateDuplicateMember(Member member) {
        repository.findByName(member.getName())
                .ifPresent(m -> {
                    throw new IllegalStateException("이미 중복된 이름 존재");
                });
    }

    public List<Member> findMembers() {
        return repository.findAll();
    }

    public Optional<Member> findOne(Long memberId) {
        return repository.findById(memberId);
    }

}

 

 

 

반응형