타입이 중복되었을때 조회는 3가지방법으로 해결할수있다.
그렇다면 같은타입의 빈을 조회하고 모두 써야되는 경우라면? 의외로 간단하다!
자바기능인 List
나 Map
을 쓰면 끝!
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 모두 fixDiscountPolicy
와 rateDiscountPolicy
가 잘 담겨져있죠?
이게 끝임 뭐없더라.. 그냥 그렇다구요..
싱겁게 자료구조 이용하는거라 나도 당황 😅