[Spring] 의존성 주입(XML - List 객체)

김승현·2022년 1월 11일
0

List 타입 매핑

  • 배열 객체java.util.List 타입의 컬렉션 객체<list> 태그를 사용하여 설정
  • 우선적으로 컬렉션을 멤버변수로 가지는 CollectionBean 클래스를 작성하여 사용 해야 함

listContext.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">

<!--
ArrayList<Person> list =new List<Person>().add(new Person("홍길동",20,"경기도 부천")).add(new Person("김말똥",30,"서울시 양천"));
-->
  
<bean id="listBeanFactory" class="kr.or.iei.person.model.vo.PersonListBeanFactory">
	<property name="list">
		<list>
			<bean class="kr.or.iei.person.model.vo.Person">
				<constructor-arg>
					<value>홍길동</value>
				</constructor-arg>
				<constructor-arg>
					<value>20</value>
				</constructor-arg>
				<constructor-arg>
					<value>경기도 부천</value>
				</constructor-arg>
			</bean>
			
			<bean class="kr.or.iei.person.model.vo.Person">
				<constructor-arg>
					<value>김말똥</value>
				</constructor-arg>
				<constructor-arg>
					<value>30</value>
				</constructor-arg>
				<constructor-arg>
					<value>서울시 양천</value>
				</constructor-arg>
			</bean>
		</list>
	</property>
</bean>

</beans>

ListServlet.java

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	AbstractApplicationContext context = new GenericXmlApplicationContext("/personBeanListContext.xml");
	PersonListBeanFactory listBeanFactory = (PersonListBeanFactory) context.getBean("listBeanFactory");

	ArrayList<Person> list = listBeanFactory.getList();

	for (Person p : list) {
		System.out.println("이름 : " + p.getName());
		System.out.println("나이 : " + p.getAge());
		System.out.println("주소 : " + p.getAddr());
	}

}

PersonListBeanFactory.java

package kr.or.iei.person.model.vo;

import java.util.ArrayList;

// 기존 매니저 Class와 같은 개념
// 여러 개의 Person 객체를 저장하고 있는 list를 저장하는 Class
public class PersonListBeanFactory {

	private ArrayList<Person> list;

	public PersonListBeanFactory() {
		super();
	}

	public PersonListBeanFactory(ArrayList<Person> list) {
		super();
		this.list = list;
	}

	public ArrayList<Person> getList() {
		return list;
	}

	public void setList(ArrayList<Person> list) {
		this.list = list;
	}

}

Person.java

package kr.or.iei.person.model.vo;

public class Person {

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

	public Person() {
	}

	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개의 댓글