[Spring] 의존성 주입(XML - setter 사용)

김승현·2022년 1월 11일
0

personBeanContext.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 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

<!-- Person Bean (객체) 1개 생성 -->
<!-- 
	Person p1 = new Person();
	p1.setName("홍길동");
	p1.setAge(20);
	p1.setAddr("경기도 부천");
 -->
<bean id="p1" class="kr.or.iei.person.model.vo.Person">
	<property name="name">
		<value>홍길동</value>
	</property>
	<property name="age">
		<value>20</value>
	</property>
	<property name="addr">
		<value>경기도 부천</value>
	</property>
</bean>


<bean id="p2" class="kr.or.iei.person.model.vo.Person">
	<property name="name" value="김말똥"></property>
	<property name="age" value="20"></property>
	<property name="addr" value="서울시 양천"></property>
</bean>

<!-- 
	PersonManger pm = new PersonManager();
	pm.setPs(p1);
 -->
<bean id="pm" class="kr.or.iei.person.model.vo.PersonManager">
	<property name="ps" ref="p1"></property>
</bean>


</beans>

Dependency2Servlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
AbstractApplicationContext context = new GenericXmlApplicationContext("/personBeanContext.xml");
		
//2가지 방법
// PersonManager pm =(PersonManager)context.getBean("pm");
PersonManager pm = context.getBean("pm", PersonManager.class);
		
Person ps = pm.getPs();
		
System.out.println("이름 : " + ps.getName());
System.out.println("나이 : " + ps.getAge());
System.out.println("주소 : " + ps.getAddr());
}

PersonManager.java

public class PersonManager {

	private Person ps;

	public PersonManager(Person ps) {
		super();
		this.ps = ps;
	}

	public PersonManager() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Person getPs() {
		return ps;
	}

	public void setPs(Person ps) {
		this.ps = ps;
	}

}

Person.java

public class Person {

	private String name;
	private int age;
	private String addr;

	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Person(String name, int age, String addr) {
		super();
		this.name = name;
		this.age = age;
		this.addr = addr;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getAddr() {
		return addr;
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}

}
profile
개발자로 매일 한 걸음

0개의 댓글