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() {
// TODO Auto-generated method stub
return "Hello" + name;
}
public void print() {
this.printer.print(sayHello());
}
}
Printer.java (인터페이스)
package myspring.di.xml;
public interface Printer {
public void print(String message);
}
ConsolePrinter.java
package myspring.di.xml;
public class ConsolePrinter implements Printer{
@Override
public void print(String message) {
System.out.println(message);
}
}
StringPrinter.java
package myspring.di.xml;
public class StringPrinter implements Printer {
private StringBuffer buffer = new StringBuffer();
@Override
public void print(String message) {
buffer.append(message);
}
public String toString() {
return buffer.toString();
}
}
new - Spring - Spring Bean Configuration File 생성
beans.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="myspring.di.xml.Hello">
<property name="name" value="Spring"/>
<property name="printer" ref="printer"></property>
</bean>
<bean id="printer" class="myspring.di.xml.StringPrinter"/>
<bean id="consolePrinter" class="myspring.di.xml.ConsolePrinter"/>
</beans>
<bean id>
: bean의 이름
<bean class>
: 사용할 클래스의 이름(src아래부터)
<property name>
: 클래스의 멤버명
<property value>
: 넣어줄 값
<property ref>
: 참조할 빈
IoC 컨테이너를 포함해 기능을 수행하는 클래스 작성
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) {
// 1. IoC 컨테이너 생성
ApplicationContext context =
new GenericXmlApplicationContext("config/beans.xml");
// 2. Hello Bean 가져오기
//Object 타입으로 가져오기 때문에 Hello 객체로 형변환 필요
Hello hello =(Hello)context.getBean("hello");
System.out.println(hello.sayHello());
hello.print();
// 3. StringPrinter Bean 가져오기
Printer printer = (Printer)context.getBean("printer");
System.out.println(printer.toString());
// 4. Singleton 패턴 확인
Hello hello2 = context.getBean("hello",Hello.class);
System.out.println(hello == hello2);
//True -> IoC 컨테이너가 Spring Bean을 Singleton 패턴으로 관리한다!
}
}
context.getBean
사용 시 id
만 사용시 형변환이 필요하다.
id와 클래스를 같이 지정해줄 시 형변환을 따로 해주지 않아도 된다.