SW/Java

Java: Spring : IoC 개념 : ApplicationContext, BeanFactory : 예제, 구현

얇은생각 2020. 4. 12. 19:30
반응형

Java: Spring : IoC 개념 : ApplicationContext, BeanFactory : 예제, 구현

 

IoC 컨테이너

Inversion of Control의 약자로 제어 역전을 의미합니다. 일반적으로 프로그래밍을 할 때 프로그램이 흘러가는 흐름이나 생성되는 객체에 대한 제어권을 개발자가 가지는 것과 달리 프레임워크가 가지는 것을 의미합니다.

개발자가 코드의 흐름이나 객체 생성에 관련된 코드를 프로그래밍 코드에 직접 작성하는 것이 아닌 프레임워크가 사용하는 파일에 작성하면 이를 토대로 프레임워크가 객체를 생성하여 반환하고 코드가 동작하는 순서를 결정하게 된다는 의미입니다. 

 

 

 

POJO Class

POJO는 Plain Old Java Object의 약자입니다. 자바 모델이나 기능, 프레임워크 등에 따르지 않고 홀로 독립적이며 단순한 기능만을 가진 객체들을 의미합니다. 자바에서는 이러한 객체들을 Bean이라고 부릅니다. 

 

 

 

IoC 컨테이너의 종류

BeanFactory

클래스를 통해 객체를 생성하고 이를 전달합니다. 상속 등 객체 간의 관계를 형성하고 관리합니다. Bean에 관련된 설정을 위한 xml 파일은 즉시 로딩하지만 객체는 개발자가 요구할 때 생성합니다. XmlBeanFactory가 있습니다.

 

ApplicationContext

클래스를 통해 객체를 생성하고 이를 전달합니다. 상속 등 객체 간의 관계를 형성하고 관리합니다. 국제화 지원 등 문자열에 관련된 다양한 기능을 제공합니다. 리스너로 등록되어 있는 Bean에 이벤트를 발생시킬 수 있습니다. Bean에 관련된 설정을 위한 xml 파일은 즉시 로딩하면서 객체를 미리 생성해서 가지고 있습니다. ClassPathXmlApplicationContext, FileSystemXmlApplicationContext, XmlWebApplicationContext가 있습니다.

 

 

 

예제

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>kr.co.softcampus</groupId>
	<artifactId>IoC</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<!-- xml에서 사용할 속성들 -->
	<properties>
		<!-- 자바 버전 -->
		<java-version>1.8</java-version>
		<!-- 스프링 버전 -->
		<org.springframework-version>5.1.9.RELEASE</org.springframework-version>
		<!--<org.springframework-version>4.3.25.RELEASE</org.springframework-version> -->
		<org.slf4j-version>1.7.26</org.slf4j-version>
		<ch.qos.logback-version>1.2.3</ch.qos.logback-version>
	</properties>

	<!-- 프로젝트에서 사용할 라이브러리 정보 -->
	<dependencies>
		<!-- spring context -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<!-- slf4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<!-- logback -->
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${ch.qos.logback-version}</version>
			<exclusions>
				<exclusion>
					<groupId>org.slf4j</groupId>
					<artifactId>slf4j-api</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

	</dependencies>
</project>

 

beans.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
	                    http://www.springframework.org/schema/beans/spring-beans.xsd">
	                    
	<bean id='t1' class='kr.co.softcampus.beans.TestBean'/>
</beans>

 

TestBean.java

package kr.co.softcampus.beans;

public class TestBean {
	
	public TestBean() {
		System.out.println("TestBean의 생성자");
	}
}

 

MainClass.java

package kr.co.softcampus.main;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;

import kr.co.softcampus.beans.TestBean;

public class MainClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//test1();
		//test2();
		//test3();
		test4();
	}
	
	// BeanFactory - 패키지 내부 
	public static void test1() {
		ClassPathResource res = new ClassPathResource("kr/co/softcampus/config/beans.xml");
		XmlBeanFactory factory = new XmlBeanFactory(res);
		
		TestBean t1 = factory.getBean("t1", TestBean.class);
		System.out.printf("t1 : %s\n", t1);
		
		TestBean t2 = factory.getBean("t1", TestBean.class);
		System.out.printf("t2 : %s\n", t2);
	}
	
	// BeanFactory - 패키지 외부
	public static void test2() {
		FileSystemResource res = new FileSystemResource("beans.xml");
		XmlBeanFactory factory = new XmlBeanFactory(res);
		
		TestBean t1 = factory.getBean("t2", TestBean.class);
		System.out.printf("t1 : %s\n", t1);
		
		TestBean t2 = factory.getBean("t2", TestBean.class);
		System.out.printf("t2 : %s\n", t2);
	}
	
	// ApplicationContext - 패키지 내부
	public static void test3() {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("kr/co/softcampus/config/beans.xml");
		
		TestBean t1 = ctx.getBean("t1", TestBean.class);
		System.out.printf("t1 : %s\n", t1);
		
		TestBean t2 = ctx.getBean("t1", TestBean.class);
		System.out.printf("t2 : %s\n", t2);
		
		ctx.close();
	}
	
	// ApplicationContext - 패키지 외부
	public static void test4() {
		FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("beans.xml");
		
		TestBean t1 = ctx.getBean("t2", TestBean.class);
		System.out.printf("t1 : %s\n", t1);
		
		TestBean t2 = ctx.getBean("t2", TestBean.class);
		System.out.printf("t2 : %s\n", t2);
		
		ctx.close();
	}
}

 

IoC 컨테이너가 어떻게 동작을 하는지, 스프링 프레임 워크에서 제어권을 갖는다는 것이 어떠한 의미인 지 알 수 있었습니다. 그리고 이러한 빈 컨테이너에 접근하는 방식이 어떤 것이 있는지 알 수 있었습니다. 

반응형