이 글은 스프링 핵심 원리 - 기본편 을 듣고 정리한 내용입니다.
[회원 도메인 요구사항]
package hello.core.member;
public class Member {
private Long id;
private String name;
private Grade grade;
public Member(Long id, String name, Grade grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
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;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
}
package hello.core.member;
public enum Grade {
BASIC,
VIP
}
package hello.core.member;
public interface MemberRepository {
void save(Member member);
Member findById(Long memberId);
}
package hello.core.member;
import java.util.HashMap;
import java.util.Map;
public class MemoryMemberRepository implements MemberRepository {
private static Map<Long, Member> store = new HashMap<>();
@Override
public void save(Member member) {
store.put(member.getId(),member);
}
@Override
public Member findById(Long memberId) {
return store.get(memberId);
}
}
package hello.core.member;
public interface MemberService {
void join(Member member);
Member findMember(Long MemberId);
}
package hello.core.member;
public class MemberServiceImpl implements MemberService{
private final MemberRepository memberRepository = new MemoryMemberRepository();
//memberRepository interface필요, but interface만 가지고 있으면 nullPointerException 터질것임.
@Override
public void join(Member member) {
memberRepository.save(member);
}
@Override
public Member findMember(Long memberId) {
return memberRepository.findById(memberId);
}
}
package hello.core.member;
public class MemberApp {
public static void main(String[] args) {
MemberService memberService = new MemberServiceImpl();
Member member = new Member(1L, "memberA", Grade.VIP);
memberService.join(member);
Member findMember = memberService.findMember(1L);
System.out.println("new member = "+member.getName());
System.out.println("findMember = "+findMember.getName());
}
}
폴더가 main, test 폴더로 나뉘어져 있는데 나중에 빌드해서 나가면 main에 대한 코드만 나가고, test에 대한 코드는 빌드될 때 빠진다.
Test Code 작성은 이제 필수임!
Test 디렉토리에 member패키지 만들어서 그 안에 작성.
- Test Code는 given, when, then으로 나눠서 작성하면 안헷갈림.
MemberServiceTest.java
package hello.core.member;
public class MemberServiceTest {
MemberService memberService = new MemberServiceImpl();
@Test // 이 어노테이션이 import 되어야 함.
void join(){
//givn - 멤버 생성
Member member= new Member(1L, "memberA", Grade.VIP);
//when - 멤버 회원가입하고, 그 멤버 찾음.
memberService.join(member);
Member findMember = memberService.findMember(2L);
//then //여기서 검증
Assertions.assertThat(member).isEqualTo(findMember);
}
}
Interface에 대한 구현체가 1개만 있으면 보통 InterfaceImpl 이라고 적는다. -> (Interface이름)+(Impl)
할인 정책은 고정 할인정책과 정률 할인정책이 있음.
디렉토리 구조는 다음과 같다.
먼저 Order 패키지를 생성하여 주문 관련된 파일들을 만든다.
OrderService의 주요 기능은 주문을 생성하는 것인데 회원ID, 상품명,상품 가격을 넘겨받아서 주문을 리턴한다.
Order.class
package hello.core.order;
public class Order {
private Long memberId;
private String itemName;
private int itemPrice;
private int discountPrice;
public Order(Long memberId, String itemName, int itemPrice, int discountPrice) {
this.memberId = memberId;
this.itemName = itemName;
this.itemPrice = itemPrice;
this.discountPrice = discountPrice;
}
public int calculatePrice(){ //할인 계산된 결과
return itemPrice-discountPrice;
}
public Long getMemberId() {
return memberId;
}
public void setMemberId(Long memberId) {
this.memberId = memberId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getItemPrice() {
return itemPrice;
}
public void setItemPrice(int itemPrice) {
this.itemPrice = itemPrice;
}
public int getDiscountPrice() {
return discountPrice;
}
public void setDiscountPrice(int discountPrice) {
this.discountPrice = discountPrice;
}
@Override
public String toString() {
return "Order{" +
"memberId=" + memberId +
", itemName='" + itemName + '\'' +
", itemPrice=" + itemPrice +
", discountPrice=" + discountPrice +
'}';
}
}
package hello.core.order;
public interface OrderService {
Order createOrder(Long memberId, String itemName, int itemPrice);
// 주문 생성할때, 회원id, 상품명, 상품 가격 넘김.
}
package hello.core.order;
import hello.core.discount.DiscountPolicy;
import hello.core.discount.FixDiscountPolicy;
import hello.core.member.Member;
import hello.core.member.MemberRepository;
import hello.core.member.MemoryMemberRepository;
public class OrderServiceImpl implements OrderService {
private final MemberRepository memberRepository = new MemoryMemberRepository();
private final DiscountPolicy discountPolicy = new FixDiscountPolicy();
@Override
public Order createOrder(Long memberId, String itemName, int itemPrice) {
Member member = memberRepository.findById(memberId);
int discountPrice= discountPolicy.discount(member,itemPrice);
return new Order(memberId, itemName,itemPrice,discountPrice );
}
}
discount 패키지 생성
package hello.core.discount;
import hello.core.member.Member;
public interface DiscountPolicy {
/**
* @return 할인 대상 금액
*/
int discount(Member member, int price);
}
package hello.core.discount;
import hello.core.member.Grade;
import hello.core.member.Member;
public class FixDiscountPolicy implements DiscountPolicy{
private int discountFixAmount=1000; //1000원 할인
@Override
public int discount(Member member, int price) {
if(member.getGrade() == Grade.VIP){
return discountFixAmount;
}else{
return 0;
}
}
}
public class OrderApp {
public static void main(String[] args) {
MemberService memberService = new MemberServiceImpl();
OrderService orderService= new OrderServiceImpl();
Long memberId = 1L;
Member member = new Member(memberId, "memberA", Grade.VIP);
memberService.join(member);
Order order = orderService.createOrder(memberId, "itemA", 10000);
System.out.println("order = "+ order);
System.out.println("order.calculatePrice= "+order.calculatePrice());
}
}
TEST 폴더에 Order 패키지 생성하고, 그 안에 작성
public class OrderServiceTest {
MemberService memberService = new MemberServiceImpl();
OrderService orderService = new OrderServiceImpl();
@Test
void createOrder(){
Long memberId = 1L;
Member member = new Member(memberId, "memberA", Grade.VIP);
memberService.join(member);
Order order = orderService.createOrder(memberId, "itemA",10000);
Assertions.assertThat(order.getDiscountPrice()).isEqualTo(1000);
}
}