Spring 핵심 원리 - AppConfig 정제하기

김태훈·2023년 1월 10일
0

Spring 핵심 원리

목록 보기
7/15

AppConfig를 활용해 DIP를 적용시키기 때문에, '역할'과 '구현'이 뚜렷하게 정의가 될 필요가 있다.

package Goat.core;

import Goat.core.discount.FixDiscountPolicy;
import Goat.core.member.MemberService;
import Goat.core.member.MemberServiceImpl;
import Goat.core.member.MemoryMemberRepository;
import Goat.core.order.OrderService;
import Goat.core.order.OrderServiceImpl;

public class AppConfig {
    public MemberService memberService(){
        return new MemberServiceImpl(new MemoryMemberRepository());
    }

    public OrderService orderService(){
        return new OrderServiceImpl(new MemoryMemberRepository(), new FixDiscountPolicy());
    }
}

문제점

  1. new MemoryMemberRepository() 코드의 중복
  2. 역할과 구현이 뚜렷하게 정의, 분리가 되지 않음
    --> FixDiscountPolicy는 뭐고, MemoryMemberRepository가 뭐냐?

해결책

package Goat.core;

import Goat.core.discount.DiscountPolicy;
import Goat.core.discount.FixDiscountPolicy;
import Goat.core.member.MemberRepository;
import Goat.core.member.MemberService;
import Goat.core.member.MemberServiceImpl;
import Goat.core.member.MemoryMemberRepository;
import Goat.core.order.OrderService;
import Goat.core.order.OrderServiceImpl;

public class AppConfig {
    public MemberService memberService(){
        return new MemberServiceImpl(memberRepository());
    }

    private static MemberRepository memberRepository() {
        return new MemoryMemberRepository();
    }

    public OrderService orderService(){
        return new OrderServiceImpl(memberRepository(), discountPolicy());
    }

    private static DiscountPolicy discountPolicy() {
        return new FixDiscountPolicy();
    }
}

ctrl + alt + m 으로 refactoring 해보자!
아무래도 반환형은 interface로 하는게 좋겠죠?

profile
기록하고, 공유합시다

0개의 댓글