Spring Boot
@Autowired와 Collection 클래스(List, Map, etc.)
작은별._.
2023. 12. 5. 21:54
728x90
아래 포스팅에서 동일 타입의 빈들이 충돌할 때 어떻게 해결할 수 있는지 확인했습니다.
이번 포스팅은 의도적으로 해당 타입의 스프링 빈이 다 필요한 경우, 특히 동적으로 동일 타입의 스프링 빈이 선택되는 경우에는 어떻게 해결할 수 있을지 작성하였습니다.
이 경우에는 자바의 Collection 클래스를 이용하여 동일 타입의 모든 빈들을 저장할 수 있습니다.
코드를 통해 확인해 보겠습니다.
// Product 인터페이스
public interface Product {
int discount();
}
// Product 상속(구현)하는 Computer 클래스
@Component
public class Computer implements Product{
@Override
public int discount() {
return 50000;
}
}
// Product 상속(구현)하는 Car 클래스
@Component
public class Car implements Product{
@Override
public int discount() {
return 1000000;
}
}
아래는 테스트 코드 입니다.
@Test
@DisplayName("동일한 타입의 빈들이 모두 저장된다.")
void AllBeanTest(){
ApplicationContext ac = new AnnotationConfigApplicationContext(HelloApplication.class, ProductService.class);
ProductService productService = ac.getBean(ProductService.class);
int discount = productService.discount("car"); // 동적으로 빈 선택
List<Product> products = productService.getProducts();
assertThat(productService).isInstanceOf(ProductService.class);
assertThat(discount).isEqualTo(1000000); // Car 타입 빈
assertThat(products.size()).isEqualTo(2); // 동일 타입 빈이 모두 저장된다.
}
static class ProductService {
private final Map<String, Product> productMap; // String: 빈 이름, Product: 빈 객체
private final List<Product> products; // 빈 객체 리스트
public ProductService(Map<String, Product> productMap,
List<Product> products) {
this.productMap = productMap;
this.products = products;
System.out.println("policyMap = " + productMap);
System.out.println("policies = " + products);
}
public int discount(String code) {
Product product = productMap.get(code); // code는 결국 빈 이름을 의미한다.
System.out.println("Code = " + code);
System.out.println("Product = " + product);
return product.discount(); // 동적으로 product 선택
}
public List<Product> getProducts(){
return products;
}
}
[출력 결과]
policyMap = {car=com.example.hello.product.Car@620aa4ea, computer=com.example.hello.product.Computer@2db2dd9d}
policies = [com.example.hello.product.Car@620aa4ea, com.example.hello.product.Computer@2db2dd9d]
Code = car
Product = com.example.hello.product.Car@620aa4ea
동일한 타입(Product 타입)의 빈들이 모두 등록되었음을 확인할 수 있습니다.
[전체 소스코드]
GitHub - eunhwa99/SpringBlog
Contribute to eunhwa99/SpringBlog development by creating an account on GitHub.
github.com
[참고자료]
김영한, "스프링 핵심 원리 - 기본편", 인프런
728x90
반응형