[Spring] 빈 조회 - 조회한 같은 타입의 빈이 모두 필요한 경우

이신영·2024년 1월 17일
1

Spring

목록 보기
10/16
post-thumbnail

타입이 중복되었을때 조회는 3가지방법으로 해결할수있다.
그렇다면 같은타입의 빈을 조회하고 모두 써야되는 경우라면? 의외로 간단하다!

자바기능인 ListMap을 쓰면 끝!

테스트 전체 코드

public class AllBeanTest {

    @Test
    void findAllBean(){
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AutoAppConfig.class, DiscountService.class);

        DiscountService discountService = ac.getBean(DiscountService.class);
        Member member = new Member(1L, "userA", Grade.VIP);
        int discountPrice = discountService.discount(member,10000,"fixDiscountPolicy");

        assertThat(discountService).isInstanceOf(DiscountService.class);
        assertThat(discountPrice).isEqualTo(1000);

        int rateDiscountPrice= discountService.discount(member,20000,"rateDiscountPolicy");
        assertThat(rateDiscountPrice).isEqualTo(2000);

    }


    static class DiscountService{
        private final Map<String, DiscountPolicy> policyMap;
        private final List<DiscountPolicy> policyList;

        @Autowired
        public DiscountService(Map<String, DiscountPolicy> policyMap, List<DiscountPolicy> policyList) {
            this.policyMap = policyMap;
            this.policyList = policyList;
            System.out.println("policyMap = " + policyMap);
            System.out.println("policyList = " + policyList);
        }

        public int discount(Member member, int price, String discountCode){
            DiscountPolicy discountPolicy = policyMap.get(discountCode);
            return discountPolicy.discount(member,price);
        }
    }
}

자자 천천히 살펴보자

        private final Map<String, DiscountPolicy> policyMap;
        private final List<DiscountPolicy> policyList;

이렇게 Map이나 List로 모든 DiscountPolicy를 주입해준뒤에

    @Test
    void findAllBean(){
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AutoAppConfig.class, DiscountService.class);

        DiscountService discountService = ac.getBean(DiscountService.class);
        Member member = new Member(1L, "userA", Grade.VIP);
        int discountPrice = discountService.discount(member,10000,"fixDiscountPolicy");

        assertThat(discountService).isInstanceOf(DiscountService.class);
        assertThat(discountPrice).isEqualTo(1000);

        int rateDiscountPrice= discountService.discount(member,20000,"rateDiscountPolicy");
        assertThat(rateDiscountPrice).isEqualTo(2000);

    }

빈등록하고 assertThat()을 해보면?


Map과 List 모두 fixDiscountPolicyrateDiscountPolicy 가 잘 담겨져있죠?

이게 끝임 뭐없더라.. 그냥 그렇다구요..


싱겁게 자료구조 이용하는거라 나도 당황 😅

profile
후회하지 않는 사람이 되자 🔥

0개의 댓글