2019백업

4-1) DI 예시 코드

728x90

Hello.java

...더보기

package myspring.di.xml;

public class Hello {
private String name;
private Printer printer;

public void setName(String name) {
this.name = name;
}
public void setPrinter(Printer printer) {
this.printer = printer;
}

public String sayHello() {
return "Hello" + name;
}

public void print() {
this.printer.print(sayHello());
}

}

Printer.interface

...더보기

package myspring.di.xml;

public interface Printer {
public void print(String message);
}

StringPrinter.java

...더보기

package myspring.di.xml;

public class StringPrinter implements Printer {
private StringBuffer buffer = new StringBuffer();

public void print(String message) {
this.buffer.append(message);
}

public String toString() {
return this.buffer.toString();
}
}

ConsolePrinter.java

...더보기

package myspring.di.xml;

public class ConsolePrinter implements Printer {

@Override
public void print(String message) {
System.out.println(message);
}
}

bean.xml

...더보기

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.2.xsd">

myspring.di.xml.Hello">



myspring.di.xml.StringPrinter" />
myspring.di.xml.ConsolePrinter">

HelloBeanTest.java (서비스)

...더보기

package myspring.di.xml.Test;

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

import myspring.di.xml.Hello;
import myspring.di.xml.Printer;

public class HelloBeanTest {
public static void main(String[] args) {

//ioc 컨테이너 생성
ApplicationContext context = 
new GenericXmlApplicationContext("/config/beans.xml");
// src부터가 절대 경로로 기본 으로 설정 되어있다.

//2.Hello Bean 가져오기
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.sayHello());
hello.print();

    //3.SpringPrinter Bean 가져오기
Printer printer = (Printer) context.getBean("printer");
System.out.println(printer.toString());

Hello hello2 = context.getBean("hello", Hello.class);
//Behaves the same as getBean(String), 
//but provides a measure of type safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the required type. 
hello2.print();

//true가 나온다는 것은 sigleton 패턴이다.
System.out.println(hello == hello2);
}
}

실행코드

true 라는 것은 싱글톤 패턴으로 구현이 되었다.

반응형