본문 바로가기
Programming/Spring

[Spring] IoC(Inversion of Controller) 컨테이너

by NAMP 2016. 4. 18.

[Spring] IoC(Inversion of Controller) 컨테이너

IoC(Inversion of Control) 개념

IoC는 컴포넌트의 재사용을 용이하게 해주고, 단위테스트를 쉽게 할 수 있도록 지원함

결합도(Coupling) 와 유지보수성

결합도(Coupling)

다형성을 이용한 결합도 떨어뜨리기

Factory 패턴을 이용한 결합도 떨어뜨리기

public class BeanFactory {
    public Object getBean(String name){
        if (name.equals("s"))
            return new STV();
        else if (name.equals("l"))
            return new LTV();
        return null;
    }
}
public class Test {
    public static void main(String[] args) {
        BeanFactory f = new BeanFactory();
        TV remocon1 = (TV) f.getBean("l");
        remocon1.powerOn();
    }
}

Spring 의 기본적인 역할
BeanFactory : 객체 관리
ApplicationContext : 기능 확장
WebApplicationContext : MVC 확장

Spring IoC 컨테이너

Bean Factory

Servlet 컨테이너는 web.xml 파일에 Servlet 을 등록하고 관리
EJB 컨테이너는 ejb-jar.xml 파일을 사용하여 EJB 객체를 관리
spring 프레임워크는 POJO(Plain Ole Java Object) 객체들을 관리하기 위하여 XML 파일 형태의 저장소를 가짐

환경설정 파일이 있어야 함.
src/main/resources 에 만든다.

spring bean configuration file 생성

Spring 에서 사용할 Bean 객체들의 저장소로 applicationContext.xml 파일을 작성

    <bean id="s" class="tv.STV"/>
    <bean id="l" class="tv.LTV"/>

Spring 컨테이너란 Spring 프레임워크에서 컨테이너 기능을 제공해주는 클래스를 의미

Spring 컨테이너의 종류

Spring IoC 컨테이너는 BeanFactory 와 BeanFactory 를 상속한 AplicationContext 두 가지 유형의 컨테이너를 제공한다.

BeanFactory

Bean 의 생성과 소멸 담당
Bean 생성 시 필요한 속성 설정
Bean 의 Life Cycle 에 관련된 메소드 호출
Context 시작 시 모든 Singleton Bean을 실제 Bean 객체가 사용되는 시점에 로딩(lazy-loading) 시킴
BeanFactory 인터페이스 구현 클래스로 XmlBeanFactory 클래스 제공

package tv;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class Test {
    public static void main(String[] args) {
        //BeanFactory f = new BeanFactory();
        String config = "applicationContext.xml";  
        BeanFactory factory = new XmlBeanFactory(new ClassPathResource(config));
        //TV remocon1 = (TV) f.getBean("l");
        TV r1 = (TV) factory.getBean("s");
        //remocon1.powerOn();
        r1.powerOn();
        
    }
}

실행결과

2016-mm-dd 14:38:24,027  INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] Loading XML bean definitions from class path resource [applicationContext.xml]
STV powerOn

log4j2.xml 파일 추가.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d %5p [%c] %m%n" />
        </Console>
        <!-- <File name="file" fileName="F:/log/log.log">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File> 
        <File name="file2" fileName="F:/log/report.log">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>   -->
    </Appenders>
    <Loggers>
        <Logger name="java.sql" level="INFO" additivity="false">
            <AppenderRef ref="console" />
        </Logger>
        <Logger name="egovframework" level="DEBUG" additivity="false">
            <AppenderRef ref="console" />
        </Logger>
          <!-- log SQL with timing information, post execution -->
        <Logger name="jdbc.sqltiming" level="INFO" additivity="false">
            <AppenderRef ref="console" />
        </Logger>
        <Logger name="org.springframework" level="INFO" additivity="false">
            <AppenderRef ref="console" />
        </Logger>
      
        <Root level="INFO">
            <AppenderRef ref="console" />
        </Root>
    </Loggers>
</Configuration>

ApplicationContext

ResourceBundle 파일을 이용한 국제화(l18n) 지원
다양한 Resource 로딩 방법 제공
이벤트 핸들링
Context 시작 시 모든 Singleton Bean 을 미리 로딩(pre-loading) 시킴
다양한 구현 클래스 제공
XmlWebApplicationContext
FileSystemXmlApplicationContext
ClassPathXmlApplicationContext

package tv;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        String config = "applicationContext.xml";  
        //BeanFactory factory = new XmlBeanFactory(new ClassPathResource(config));
        ApplicationContext context = new ClassPathXmlApplicationContext(config);
        TV r1 = (TV) context.getBean("s");
        r1.powerOn();        
    }
}

실행결과

STV 생성
LTV 생성
STV powerOn

파일 이름이 여러 개 일 수도 있다.

String[] config = {"applicationContext.xml", "other.xml"};  
ApplicationContext context = new ClassPathXmlApplicationContext(config);

Bean 객체의 초기화

BeanFactory 의 Bean 객체 초기화

ApplicationContext 의 Bean 객체 초기화


'Programming > Spring' 카테고리의 다른 글

[spring] DI(Dependency Inversion) 개념  (0) 2016.04.19
[Spring] 설정 파일  (0) 2016.04.18
[spring] 프레임워크 개요  (0) 2016.04.17
[spring] Servlet & EJB & Spring  (0) 2016.04.17
[Spring] file download  (0) 2015.08.13

댓글