-
[Spring Core] 공식문서 공부 - 1.2.3 Using the ContainerJAVA/Spring 2022. 8. 21. 15:39
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-client
Core Technologies
In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do
docs.spring.io
이번 글에서는 인스턴스화 한 IoC 컨테이너로 부터 어떻게 Bean의 인스턴스에 대한 참조를 얻을 수 있는지에 대해 다룬다.
ApplicationContext 인터페이스는 IoC 컨테이너에 등록된 Bean들과 그들의 의존성(협력 객체를 말하는 거 같음)을 다룰 수 있다.
이는 getBean() 메소드를 통해서 해당 bean의 인스턴스에 대한 참조를 얻을(retrieve)수 있다.

Figure 1. getBean() 메소드 [Figure 1]은 공식 API 문서에서 getBean() 메소드를 검색한 결과이다. 상위 인터페이스인 BeanFactory 문서에 있다.
아래는 공식문서에 있는 getBean() 메소드의 사용 예제이다.
// bean들을 생성 및 구성(configuration)한다. ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml"); // 구성된(configured) 인스턴스에 대한 참조를 얻는다. PetStoreService service = context.getBean("petStore", PetStoreService.class); // 인스턴스를 사용한다. List<String> userList = service.getUsernameList();공식문서에서는 ApplicationContext의 또 다른 구현체인 GenericApplicationContext 클래스의 생성자를 이용한 예제도 소개한다.
GenericApplicationContext context = new GenericApplicationContext(); new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml"); context.refresh();앞의 예제와 이 예제에서 큰 차이점은 Bean의 인스턴스에 대한 참조를 얻기 위해 getBean() 메소드를 사용하지 않는다는 점인데, 이처럼 이상적인 어플리케이션에서는 getBean() 메소드를 사용하지 않음으로써 Spring APIs 자체에 대한 의존도를 없애야 한다고 한다. 예시로, 웹 프레임워크 개발시에 @Autowiring 어노테이션을 사용하여 의존성 주입(Dependency Injection)을 한다고 한다.
'JAVA > Spring' 카테고리의 다른 글
[Spring Core] 공식문서 공부 - 1.3.1 Naming Beans (0) 2022.08.21 [Spring Core] 공식문서 공부 - 1.3 Bean Overview (0) 2022.08.21 [Spring Core] 공식문서 공부 - 1.2.2 Instantiating a Container (0) 2022.08.21 [Spring Core] 공식문서 공부 - 1.2.1 Configuration Metadata (0) 2022.08.21 [Spring Core] 공식문서 공부 - 1.2 Container Overview (1) 2022.08.21