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 라는 것은 싱글톤 패턴으로 구현이 되었다.
'2019백업' 카테고리의 다른 글
4-2) DI 애플리케이션 작성 - JUnit (0) | 2019.06.25 |
---|---|
namespace는 무엇이고 XML은 무엇일까? (0) | 2019.06.20 |
4) 스프링프레임워크 DI의 개념 (0) | 2019.06.20 |
3. Spring Framework 개요 (0) | 2019.06.20 |
2. 프레임워크의 구성요소와 종류 (0) | 2019.06.20 |