본문 바로가기

SpringFramework Core - I. IoC 컨테이너/1. 스프링 IoC 컨테이너와 Beans 소개

2.2. 컨테이너 인스턴스화 하기

원문: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-instantiation

 

 

ApplicationContext 생성자에 제공되는 위치 경로들은 리소스 문자열로 되어있다. 이 경로는 로컬 파일시스템이나 자바 클래스패스 등 다양한 외부 자원으로부터 컨테이너가 설정 메타데이터를 로딩하도록 한다. 

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

※ 스프링 IoC 컨테이너에 대해 공부하고 나면, 스프링의 Resource 추출에 대해 알고 싶을 수 있다. 스프링의 Resource 추출 기능은, URI 문법으로 정의된 위치들로부터 InputStream을 통해 편리하게 읽어들이는 메커니즘을 제공한다. 특히, Resource 경로들은 application contexts를 생성하는 데 사용된다. 'Application Context들과 Resource 경로들'을 참고하라.

 

다음 예시는 응용 계층 객체인 'services.xml' 설정 파일이다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    					https://www.springframework.org/schema/beans/spring-beans.xsd">
                        
                        
	<!-- services -->
    
    
    <bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
    	<property name="accountDao" ref="accountDao" />
        <property name="itemDao" ref="itemDao" />
    	<!-- 이 bean에 대한 추가적인 협력자들과 설정들이 위치함 -->
    </bean>
    
    
    
    <!-- 서비스에 대한 더 많은 bean 정의들이 위치함 -->
    
    
</beans>    

다음 예시는 데이터 접근 객체인 'daos.xml' 파일을 보여준다.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        				https://www.springframework.org/schema/beans/spring-beans.xsd">
                        

    <bean id="accountDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
    	<!-- 이 bean에 대한 추가적인 협력자와 설정들이 위치함 -->
    </bean>
    
    
    <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
    	<!-- 이 bean에 대한 추가적인 협력자와 설정들이 위치함 -->
    </bean>
    
    
    
    <!-- 데이터 접근 객체에 대한 더 많은 bean 정의들이 위치함 -->

</beans>

 

위의 예시에서, 응용 계층은 PetStoreServiceImpl 클래스와 두 개의 데이터 접근 객체인 JpaAccountDao, JpaItemDao로 구성된다. property name 요소는 자바빈 프로퍼티의 이름을 가리킨다. 그리고 ref 요소는 다른 bean의 이름을 가리킨다. id와 ref 사이의 연결을 통해 협력 객체들 사이의 의존성을 표현한다. 객체들의 의존성 설정에 대해 자세히 알고싶다면 '의존성'을 참고하라.