본문 바로가기

Java/Spring

스프링의 DI에 대해서...

스프링의 핵심으로 객체 사이의 의존 관계가 자기 자신이 아닌 외부에 의해서 설정된다는 개념이다.


Bar.java
package ditestlab1;

public class Bar {

	public Bar() {
		System.out.println("Bar 객체생성");
	}

}
Foo.java
package ditestlab1;

public class Foo {
	private Bar bar;
	public Foo() {
		System.out.println("Foo() 객체 생성");
	}
	public Foo(Bar bar) {
		this.bar = bar;
		System.out.println("Foo(Bar bar) 객체생성");
		System.out.println("전달된 Bar 객체 : "+bar);
	}
	public Foo(int num, String message) {		
		System.out.println("Foo(int num, String message) 객체생성");
		System.out.println("전달된 num = "+num);
		System.out.println("전달된 message = "+message);		
	}
	public Foo(int num, String message, boolean flag) {
		System.out.println("Foo(int num, String message, boolean flag) 객체생성");
		System.out.println("전달된 num = "+num);
		System.out.println("전달된 message = "+message);	
		System.out.println("전달된 flag = "+flag);		
	}
}
FooTestApp.java
package ditestlab1;

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

public class FooTestApp {

	public static void main(String[] args) {
		Resource resource = new ClassPathResource("applicationContext.xml");
		System.out.println("new ClassPathResource(\"applicationContext.xml\");");
		BeanFactory factory = new XmlBeanFactory(resource);
		System.out.println("new XmlBeanFactory(resource);");
		Foo obj1 = (Foo)factory.getBean("foo1");
		System.out.println(obj1);
		System.out.println(factory.isSingleton("foo1"));
		System.out.println("---------------");
		Foo obj2 = (Foo)factory.getBean("foo2");	
		System.out.println(obj2);
		System.out.println(factory.isSingleton("foo2"));
		System.out.println("---------------");
		Foo obj3 = (Foo)factory.getBean("foo3");
		System.out.println(obj3);
		System.out.println(factory.isSingleton("foo3"));
		System.out.println("---------------");
		Foo obj4 = (Foo)factory.getBean("foo4");
		System.out.println(obj4);
		System.out.println(factory.isSingleton("foo4"));
		System.out.println("---------------");
		
	}
}