본문 바로가기

spring/기초

스프링 컨테이너

package pack;


public class MessageImpl implements MessageInter{

@Override

public void sayHello(String name) {

System.out.println("안녕하세요 " + name + "님.");

}

}


==========================================================================================


package pack;


public class MessageImpl2 implements MessageInter{

@Override

public void sayHello(String name) {

System.out.println("반가워요 " + name + "씨.");

}

}


==========================================================================================


package pack;


import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Main {


public static void main(String[] args) {

MessageInter inter;

inter = new MessageImpl();

inter.sayHello("손오공");

inter = new MessageImpl2();

inter.sayHello("손오공");

}


}

==========================================================================================

package pack;


import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Main {


public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("init.xml");

MessageInter inter = null;

inter = (MessageInter)context.getBean("impl");

inter.sayHello("손오공");

inter = (MessageInter)context.getBean("impl2");

inter.sayHello("손오공");

}


}

==========================================================================================

아래 파일은 이클립스 프로젝트 폴더에서 우클릭 New --> Other --> Spirng 항목중 Spring Bean Configuration File 을 선택

이름 적고 next 누른후 beans 체크해주고 3.2.xsd 버전으로 체크해줌

주의할점은 위의 Main Class 파일의 설정상 최상위? 경로에 있어야함


<?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-3.1.xsd">


<bean id="impl" class="pack.MessageImpl"/>

<bean id="impl2" class="pack.MessageImpl2"/>


</beans>


==========================================================================================

==========================================================================================


첫번째 Main과 두번째 Main을 실행하면

결과는 똑같다.


차이는 두번째 Main은 객체 생성을 하지 않고도 실행됬다는 점이다.


Configuration File 설정파일을 통해서 객체를 만들어놨고 Main Class에서 만들어 놓은 객체를 가져다가 사용했기 때문이다.


스프링의 컨테이너는 Bean을 관리해준다.