본문 바로가기

Spring/Dependency Injection

[Spring Framework] Application Context 사용하기

728x90
반응형

'뉴렉처' 님의 채널(www.youtube.com/user/newlec1)을 바탕으로 제작한 블로그 글입니다:)

 

 

 

이번 시간에는 이전에 작성한 setting.xml을 java 코드에서 어떻게 가져와 사용하는지에 대해서 배워보고자 합니다.

만약 Spring 라이브러리가 준비되어있지 않다면 제 블로그의 아래 글을 참고해주세요!

programming-workspace.tistory.com/22

 

[Spring Framework] 이클립스에서 Spring Library 가져오기

'뉴렉처' 님의 채널(www.youtube.com/user/newlec1)을 바탕으로 제작한 블로그 글입니다:)] 이번 시간에는 이클립스에서 Spring 라이브러리를 사용하기 위해서 세팅하는 작업을 해보려고 합니다. 우선 이클

programming-workspace.tistory.com

 

 

우선 ApplicationContext란 무엇인지 알아봅시다.

 

 

ApplicationContext란, BeanFactory 인터페이스를 상속받은 하위 인터페이스입니다. 이는 BeanFactory가 제공하는 기능 외에도, 추가적으로 자원 처리 추상화나 메시지 및 국제화와 이벤트 지원 등을 제공하고 있어,

BeanFactory보다 더 자주 사용된다고 합니다.

 

 

ApplicationContext는 아래와 같이 사용됩니다.

 

ApplicationContext context = new ClassPathXmlApplicationContext(xml파일명);

 

 

ClassPathXmlApplicationContext는 Interface인 ApplicationContext를 구현한 class입니다.

 

 

구현하고있는 Class는 ClassPathXmlApplicationContext 외에도 3가지가 더 있습니다.

아래의 4가지 class는 어떻게 xml의 위치를 넘겨주냐에 대한 차이점을 갖고 있습니다.

 

 

- ClassPathXmlApplicationContext : ClassPath에 위치한 xml 파일을 읽어 설정 정보를 로딩, root로부터 경로를 지정함

- FileSystemXmlApplicationContext : 파일 경로로 지정된 곳의 xml을 읽어 설정 정보를 로딩

- XmlWebApplicationContext : 웹 어플리케이션에 위치한 곳에서 xml파일을 읽어 설정 정보를 로딩

- AnnotationConfigApplicationContext : @Configuration 어노테이션이 붙은 클래스를 이용하여 설정 정보로 로딩

 

 

외부 설정을 가져오기 위해서 Program.java 코드를 아래와 같이 수정해주세요.이 때, ClassPathXmlApplicationContext의 경우, src를 root로 보고 경로를 적어주면 됩니다.

 

 

저는 src 디렉토리 내부의 spring/di 안에 xml 파일이 있으니, spring/di/setting.xml로 넣어야합니다.

 

 

- Program.java

public static void main(String[] args) {

	ApplicationContext context = 
		new ClassPathXmlApplicationContext("spring/di/setting.xml");

	AnimalPrint console = (AnimalPrint) context.getBean("console");
	console.print();

}

 

 

AnimalPrint console = (AnimalPrint) context.getBean("console") 코드를 분석해봅시다.

 

 

우선, getBean 안에 있는 "console"은, xml 안에서 우리가 정해준 spring.console.AnimalPrintAge class 형식의 인스턴스 이름(아래 setting.xml 참고)입니다.

 

 

- setting.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 = "animal" class = "spring.entity.Animal">
          <constructor-arg type="java.lang.String" value="BINGO"/>
          <constructor-arg type="int" value="5"/>
	</bean>
	<bean id = "console" class = "spring.console.AnimalPrintAge">
		<property name = "animal" ref = "animal"/>
	</bean>

</beans>

 

 

즉, 우리가 xml에서 무엇을 꺼내서 사용할 것인지 결정하는 부분입니다.

xml의 bean 정보를 가져오는 방법은 위에서 언급한 것 외에도

AnimalPrint console = context.getBean(AnimalPrint.class)를 사용하여 가져 올 수 있습니다.

이 코드는 명시적 형변환을 해 줄 필요 없이 bean 정보를 가져오기 때문에 더 선호되는 방식이라고 하네요.

 

 

이제 위의 코드를 실행시켜보면, Animal의 age가 잘 출력된 모습을 볼 수 있습니다.

 

 

 

그러면 이제, setting.xml에서 AnimalPrintAge를 AnimalPrintName으로 바꿨을 때에 이름이 잘 출력되는지 확인해보기 위해서 setting.xml을 아래와 같이 바꿔봅시다.

 

 

- setting.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 = "animal" class = "spring.entity.Animal">
          <constructor-arg type="java.lang.String" value="BINGO"/>
          <constructor-arg type="int" value="5"/>
	</bean>
	<bean id = "console" class = "spring.console.AnimalPrintName">
		<property name = "animal" ref = "animal"/>
	</bean>

</beans>

 

 

코드를 실행하면 아래와 같이 외부 설정의 변경으로 인해서 나이가 아닌 이름을 출력되는 것을 확인할 수 있습니다.

 

 

이처럼 Program.java 코드를 변경하지 않고도 외부 설정을 사용함으로써 기능을 변경 및 업데이트 할 수 있다는 것을 알 수 있습니다.

 

 

 

 

 

728x90
반응형