실습 4일차_MyBatis_Transaction ★

 

 Spring MyBatis_Transaction ★

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.DeptDTO;
import com.service.DeptService;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/dept.xml");	
		DeptService service = ctx.getBean("deptService", DeptService.class);
		
		// 1. 저장 ==> Spring + Mybatis는 자동으로 commit된다.
		// int num = service.insert(new DeptDTO(99, "IT", "부산"));	
		// int num2 = service.update(new DeptDTO(99, "AI", "서울"));
		// int num3 = service.delete(99);
		
		// transaction 처리	
		try {
			service.tx();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		List<DeptDTO> list = service.selectAll();
		System.out.println(list);
	}
}

DeptDAO.java

package com.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.dto.DeptDTO;

@Repository("deptDAO")
public class DeptDAO {
	
	@Autowired
	SqlSession session; // null
	// SqlSessionTemplate session;
	
	public List<DeptDTO> selectAll(){
		return session.selectList("com.config.DeptMapper.selectAll");
	}

	public DeptDTO selectByDeptno(int deptno) {
		
		return session.selectOne("com.config.DeptMapper.selectByDeptno", deptno);
	}

	public int insert(DeptDTO dto) {
		
		return session.insert("com.config.DeptMapper.insert", dto);
	}

	public int update(DeptDTO dto) {
		
		return session.update("com.config.DeptMapper.update", dto);
	}
	
	public int delete(int deptno) {
		
		return session.delete("com.config.DeptMapper.delete", deptno);
	}
}

DeptDTO.java

package com.dto;
import org.apache.ibatis.type.Alias;

@Alias("DeptDTO")
public class DeptDTO {

	int deptno;
	String dname;
	String loc;
	
	public DeptDTO() {
		
	}
	
	public DeptDTO(int deptno, String dname, String loc) {
		super();
		this.deptno = deptno;
		this.dname = dname;
		this.loc = loc;
	}

	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getLoc() {
		return loc;
	}
	public void setLoc(String loc) {
		this.loc = loc;
	}
	
	@Override
	public String toString() {
		return "DeptDTO [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + "]";
	}
}

DeptService.java

package com.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.dto.DeptDTO;

@Service("deptService")
public interface DeptService {

	// 전체 레코드 조회
	public List<DeptDTO> selectAll();
	
	// 특정 레코드 조회
	public DeptDTO selectByDeptno(int deptno);
	
	// 저장
	public int insert(DeptDTO dto);
	
	// 수정
	public int update(DeptDTO dto);
	
	// 삭제
	public int delete(int deptno);
	
	// 트랜잭션 실습 메서드
	public void tx() throws Exception;
	
}

DeptServiceImpl.java

package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.DeptDAO;
import com.dto.DeptDTO;

@Service("deptService")
public class DeptServiceImpl implements DeptService {
	
	@Autowired
	DeptDAO dao; //null

	@Override
	public List<DeptDTO> selectAll() {
		
		return dao.selectAll();
	}

	@Override
	public DeptDTO selectByDeptno(int deptno) {
		
		return dao.selectByDeptno(deptno);
	}

	@Override
	public int insert(DeptDTO dto) {
		
		return dao.insert(dto);
	}

	@Override
	public int update(DeptDTO dto) {
		
		return dao.update(dto);
	}
	
	@Override
	public int delete(int deptno) {
		
		return dao.delete(deptno);
	}

	// 트랜잭션 실습 메서드
	@Transactional
	@Override
	public void tx() throws Exception {
		int num = dao.insert(new DeptDTO(96, "IT", "서울"));
		int num2 = dao.delete(1);
	}
}

dept.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"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

  <!-- mybatis 연동 -->
  <!-- 1. jdbc.properties 등록 -->
  <context:property-placeholder location="classpath:com/config/jdbc.properties"/>

  <!-- 2. DBCP2 등록 (Connection Pool 기능을 가지고 있음) -->
  <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="${jdbc.oracle}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.userid}" />
    <property name="password" value="${jdbc.passwd}" />
  </bean>
  
  <!-- 트랜잭션 처리 -->
  <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- (this dependency is defined somewhere else) -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
  <tx:annotation-driven transaction-manager="txManager"/>
  <!-- 트랜잭션 처리 -->
  
  <!-- 3. SqlSessionFactoryBean 등록 -->
  <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mapperLocations">
      <list>
		<value>classpath:com/config/DeptMapper.xml</value>      
      </list>
    </property>
    <property name="typeAliases">
      <list>
        <value>com.dto.DeptDTO</value>
      </list>
    </property>
  </bean>
  
  <!-- 4. SqlSessionTemplate 등록 -->
  <bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
     <constructor-arg name="sqlSessionFactory" ref="sessionFactory" />
  </bean>
  <!-- mybatis 연동 -->
  <context:component-scan base-package="com.*" />

</beans>

DeptMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.config.DeptMapper">

	<select id="selectAll" resultType="DeptDTO">
	<![CDATA[
		select deptno,dname,loc
		from dept
		order by deptno desc
		]]>
	</select>
	
	<select id="selectByDeptno" resultType="DeptDTO"
		parameterType="int">
		<![CDATA[
		select deptno,dname,loc
		from dept
		where deptno = #{deptno}
		]]>
	</select>
	
	<insert id="insert" parameterType="DeptDTO">
	<![CDATA[
	    insert into dept ( deptno, dname, loc )
	    values ( #{deptno} , #{dname} , #{loc})
	    ]]>
	</insert>
	
	<update id="update" parameterType="DeptDTO">
	<![CDATA[
	   update dept 
	   set dname = #{dname} , loc=#{loc}
	   where deptno = #{deptno}
	   ]]>
	</update>
	
	<delete id="delete" parameterType="int">
	<![CDATA[
	   delete from dept
	   where deptno = #{deptno}
	   ]]>
	</delete>

</mapper>

jdbc.properties

#주석입니다.
#문법은 key=value
jdbc.oracle=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.userid=????? #DB 계정
jdbc.passwd=????? #DB 계정 패스워드

 

* 출력 화면 

 

 출처

 

Mybatis : 

+ 강의 교재

 

실습 4일차_MyBatis ★

 

 Spring MyBatis ★

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.DeptDTO;
import com.service.DeptService;

public class MainClass {
	public static void main(String[] args) {
		
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/dept.xml");
		
		DeptService service = ctx.getBean("deptService", DeptService.class);
		
		// 1. 저장 ==> Spring + Mybatis는 자동으로 commit된다.
		// int num = service.insert(new DeptDTO(99, "IT", "부산"));
		// int num2 = service.update(new DeptDTO(99, "AI", "서울"));
		// int num3 = service.delete(99);
		
		List<DeptDTO> list = service.selectAll();
		System.out.println(list);
	}
}

DeptDAO.java

package com.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.dto.DeptDTO;

@Repository("deptDAO")
public class DeptDAO {
	
	@Autowired
	SqlSession session; // null
	// SqlSessionTemplate session;
	
	public List<DeptDTO> selectAll(){
		return session.selectList("com.config.DeptMapper.selectAll");
	}
	
	public DeptDTO selectByDeptno(int deptno) {
		
		return session.selectOne("com.config.DeptMapper.selectByDeptno", deptno);
	}

	public int insert(DeptDTO dto) {
		
		return session.insert("com.config.DeptMapper.insert", dto);
	}

	public int update(DeptDTO dto) {
		
		return session.update("com.config.DeptMapper.update", dto);
	}
	
	public int delete(int deptno) {
		
		return session.delete("com.config.DeptMapper.delete", deptno);
	}
}

DeptDTO.java

package com.dto;
import org.apache.ibatis.type.Alias;

@Alias("DeptDTO")
public class DeptDTO {

	int deptno;
	String dname;
	String loc;
	
	public DeptDTO() {
		
	}
	
	public DeptDTO(int deptno, String dname, String loc) {
		super();
		this.deptno = deptno;
		this.dname = dname;
		this.loc = loc;
	}

	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getLoc() {
		return loc;
	}
	public void setLoc(String loc) {
		this.loc = loc;
	}
	
	@Override
	public String toString() {
		return "DeptDTO [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + "]";
	}
	
}

DeptService.java

package com.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.dto.DeptDTO;

@Service("deptService")
public interface DeptService {

	// 전체 레코드 조회
	public List<DeptDTO> selectAll();
	
	// 특정 레코드 조회
	public DeptDTO selectByDeptno(int deptno);
	
	// 저장
	public int insert(DeptDTO dto);
	
	// 수정
	public int update(DeptDTO dto);
	
	// 삭제
	public int delete(int deptno);
}

DeptServiceImpl.java

package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dao.DeptDAO;
import com.dto.DeptDTO;

@Service("deptService")
public class DeptServiceImpl implements DeptService {
	
	@Autowired
	DeptDAO dao; //null

	@Override
	public List<DeptDTO> selectAll() {
		
		return dao.selectAll();
	}

	@Override
	public DeptDTO selectByDeptno(int deptno) {
		
		return dao.selectByDeptno(deptno);
	}

	@Override
	public int insert(DeptDTO dto) {
		
		return dao.insert(dto);
	}

	@Override
	public int update(DeptDTO dto) {
		
		return dao.update(dto);
	}
	
	@Override
	public int delete(int deptno) {
		
		return dao.delete(deptno);
	}

}

dept.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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

  <!-- mybatis 연동 -->
  <!-- 1. jdbc.properties 등록 -->
  <context:property-placeholder location="classpath:com/config/jdbc.properties"/>

  <!-- 2. DBCP2 등록 (Connection Pool 기능을 가지고 있음) -->
  <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="${jdbc.oracle}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.userid}" />
    <property name="password" value="${jdbc.passwd}" />
  </bean>
  
  <!-- 3. SqlSessionFactoryBean 등록 -->
  <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mapperLocations">
      <list>
		<value>classpath:com/config/DeptMapper.xml</value>      
      </list>
    </property>
    <property name="typeAliases">
      <list>
        <value>com.dto.DeptDTO</value>
      </list>
    </property>
  </bean>
  
  <!-- 4. SqlSessionTemplate 등록 -->
  <bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
     <constructor-arg name="sqlSessionFactory" ref="sessionFactory" />
  </bean>
  <!-- mybatis 연동 -->
  <context:component-scan base-package="com.*" />

</beans>

DeptMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.config.DeptMapper">

	<select id="selectAll" resultType="DeptDTO">
	<![CDATA[
		select deptno,dname,loc
		from dept
		order by deptno desc
		]]>
	</select>
	
	<select id="selectByDeptno" resultType="DeptDTO"
		parameterType="int">
		<![CDATA[
		select deptno,dname,loc
		from dept
		where deptno = #{deptno}
		]]>
	</select>
	
	<insert id="insert" parameterType="DeptDTO">
	<![CDATA[
	    insert into dept ( deptno, dname, loc )
	    values ( #{deptno} , #{dname} , #{loc})
	    ]]>
	    
	</insert>
	
	<update id="update" parameterType="DeptDTO">
	<![CDATA[
	   update dept 
	   set dname = #{dname} , loc=#{loc}
	   where deptno = #{deptno}
	   ]]>
	</update>
	
	<delete id="delete" parameterType="int">
	<![CDATA[
	   delete from dept
	   where deptno = #{deptno}
	   ]]>
	</delete>

</mapper>

jdbc.properties

#주석입니다.
#문법은 key=value
jdbc.oracle=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.userid=????? #DB 계정
jdbc.passwd=????? #DB 계정 패스워드

 

* 출력 화면 

 

 출처

 

Mybatis : 

+ 강의 교재

 

실습 4일차_Component_Scan

 

 

 

 Spring Component_Scan

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");

		UserService service = ctx.getBean("service", UserService.class);
		List<String> list = service.list();
		System.out.println(list);
	}
}

UserDAO.java

package com.dao;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

// @Component // @Component는 전부 Class Level
@Repository("dao")
public class UserDAO {
	
	public UserDAO() {
		System.out.println("UserDAO 생성자");
	}

	// DB 연동 가정
	public List<String> list(){
		List<String> list = Arrays.asList("고길동", "홍길동", "신길동");
		return list;
	}
}

UserService.java

package com.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.dao.UserDAO;

// POJO Class
// @Component // @Component는 전부 Class Level
@Service("service")
public class UserService {
	
	@Autowired
	UserDAO dao; // property (인스턴스 변수)
	
	public UserService() {
		System.out.println("UserService 생성자");
	}
	
	public List<String> list(){
		return dao.list();
	}
}

user.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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<!-- @ 어노테이션 활성화 -->
	<!-- <context:annotation-config /> --> <!-- empty tag -->
	
	<!-- 내부적으로 <context:annotation-config /> 기능 포함 -->

	<!-- 마킹된(Component) Bean들의 Pakage Name 지정 -->
	<context:component-scan base-package="com.service, com.dao" /> <!-- empty tag -->
	<!-- <context:component-scan base-package="com.*" /> -->
</beans>
<!-- @ 어노테이션 활성화 -->
<context:annotation-config />

* context 활성화 방법

[Namespaces 탭] → [context] Check → Configure Namespaces 알림창 OK 버튼 마우스로 클릭 

 

 

 

* 출력 화면 

 

 출처

 

* Component_Scan : 

+ 강의 교재

 

실습 4일차_@Value_resourceBundle

 

 

 

 Spring @Value_resourceBundle

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Cat c = ctx.getBean("cat1", Cat.class);
		System.out.printf("고양이 이름:%s 나이:%s 성별:%s", c.getName(), c.getAge(), c.getSex());	
	}
}

Cat.java

package com.dto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

public class Cat {
	
	@Value("${cat.name}")
	String name;
	@Value("${cat.age}")
	int age;
	@Value("${cat.sex}")
	String sex;
	
	public Cat() {

	}

	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Person {
	
	String username;
	int userage;
	String address;
	
	//@Autowired(required = false)
	//@Qualifier("cat1")
	@Resource(name = "cat2")
	Cat cat; // null
	
	public Person() {
	
	}

	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Person(String username, int userage, String address, Cat cat) {
		super();
		this.username = username;
		this.userage = userage;
		this.address = address;
		this.cat = cat;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Cat getCat() {
		return cat;
	}

	public void setCat(Cat cat) {
		this.cat = cat;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", cat=" + cat + "]";
	}
	
}

test.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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<context:annotation-config />

	<context:property-placeholder location="classpath:com/config/cat.properties" file-encoding="utf-8"/> 

	<bean id="cat1" class="com.dto.Cat" />
	<!-- 
	<bean id="cat1" class="com.dto.Cat"> < 생성자로 주입   property라는 setter method 이용-->
		<!-- 	<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	 -->

</beans>

 

<!-- @ 어노테이션 활성화 -->
<context:annotation-config />

* context 활성화 방법

[Namespaces 탭] → [context] Check → Configure Namespaces 알림창 OK 버튼 마우스로 클릭 

 

 

cat.properties

cat.name = 망치 
cat.age = 2
cat.sex = 수컷

 

* 출력 화면 

 

 출처

 

@Value: 

+ 강의 교재

 

실습 4일차_@Resource

 

 

 

 Spring @Resource

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Person p1 = ctx.getBean("p1", Person.class);
		Cat c = p1.getCat();
		
		System.out.printf("이름:%s 나이:%s 주소:%s \n", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat
		System.out.printf("고양이 이름:%s 나이:%s 성별:%s", c.getName(), c.getAge(), c.getSex());	
	}
}

Cat.java

package com.dto;
import org.springframework.beans.factory.annotation.Autowired;

public class Cat {
	String name;
	int age;
	String sex;
	
	public Cat() {

	}

	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Person {
	
	String username;
	int userage;
	String address;
	
	//@Autowired(required = false)
	//@Qualifier("cat1")
	@Resource(name = "cat2")
	Cat cat; // null
	
	public Person() {
	
	}

	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Person(String username, int userage, String address, Cat cat) {
		super();
		this.username = username;
		this.userage = userage;
		this.address = address;
		this.cat = cat;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Cat getCat() {
		return cat;
	}

	public void setCat(Cat cat) {
		this.cat = cat;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", cat=" + cat + "]";
	}
	
}

user.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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<context:annotation-config />

	<bean id="cat1" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="cat2" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비2" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="userage" value="30" />
		<property name="address" value="서울" />
		<!--  <property name="cat" ref="cat" /> 자동으로 주입  Cat.java @Autowired 코드 확인-->
	</bean>
</beans>

 

<!-- @ 어노테이션 활성화 -->
<context:annotation-config />

* context 활성화 방법

[Namespaces 탭] → [context] Check → Configure Namespaces 알림창 OK 버튼 마우스로 클릭 

 

 

 

* 출력 화면 

 

 출처

 

@Resource : 

+ 강의 교재

 

실습 3일차_I18N_MessageSource

 

 I18N이란?

 

I18N은 Internationalization의 축약형이다.

Internationalization은 알파벳이 20개로, 가장 첫 글자인 I와 가장 마지막 글자인 N 사이에 알파벳이 18개 있다고 하여

I18N으로 칭한다. 즉, 국제화, Internationalization, I18N 모두 같은 말이다.

 

SW 국제화(I18N)이란?

SW(Software) 국제화는 SW가 특정 지역이나 언어에 종속되지 않고 다양한 지역, 언어에서 정상 동작하도록

국제적으로 통용되는 SW를 설계하고 개발하는 과정을 말한다.

 

 Spring Injection_Callback

MainClass.java

import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.foo.Example;

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

		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");
		String mesg = ctx.getMessage("greet", null, "Hello~~~", Locale.KOREA);
		System.out.println(mesg);
		
		String mesg2 = ctx.getMessage("greet2", new Object[] {"Kim"}, "Hello~~~", Locale.UK);
		System.out.println(mesg2);
		
		String mesg3 = ctx.getMessage("greet3", new Object[] {"Kim", 20}, "Hello~~~", Locale.UK);
		System.out.println(mesg3);
		
		//Example 빈 참조
		Example exam = ctx.getBean("exam", Example.class);
		exam.printMessage();
		
	}
}

 

Example.java

package com.foo;

import java.util.Locale;
import org.springframework.context.MessageSource;

public class Example {

	MessageSource messageSource;
	
	//setter 메서드 주입
	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}
	
	public void printMessage() {
		String mesg = messageSource.getMessage("greet", null, "Hello~~~", Locale.KOREA);
		System.out.println(mesg);
	}
}

 

hello_en.properties

# hello_en.properties
greet=Good Morning
greet2=name:{0}
greet3=name:{0} age:{1}

hello_ko.properties

# hello_ko.properties
greet=안녕하세요.
greet2=이름:{0}
greet3=이름:{0} 나이:{1}

user.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.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- hello_xx.properties 에서 hello만 저장한다. -->

	<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
	<!-- id="messageSource" id 값이 정해져 있음 다르게 쓰면 안됨.. -->
		<property name="basenames">
			<list>
			<value>classpath:com/config/hello</value> <!-- 문자열일 경우 value 사용 -->
			</list>
		</property>
		<property name="defaultEncoding" value="utf-8" /> <!-- default encoding: ISO-8859-1. > utf-8로 변경  --> 
	</bean>

	<bean id="exam" class="com.foo.Example">
		<property name="messageSource" ref="messageSource" />
	</bean>

</beans>

* 출력 화면 

 

 출처

 

* I18N : https://miaow-miaow.tistory.com/32

+ 강의 교재

실습 3일차_Injection_Callback

 

https://docs.spring.io/spring-framework/docs/4.3.0.RELEASE/spring-framework-reference/html/beans.html#beans-collection-elements

 

 Spring Injection_Callback

ExampleMain.java

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

public class ExampleMain {

	public static void main(String[] args) {
	
		// IoC Container
		
		//ApplicationContext ctx =
		GenericXmlApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/conf.xml");
		
		ctx.close();
	}

}

ExampleBean.java

package examples;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExampleBean {
	
	private static final Logger logger = LoggerFactory.getLogger(ExampleBean.class);

	String mesg; // null 
	
	public ExampleBean() {
		logger.info("ExampleBean 생성자 호출");
	}

	// setter 메서드 주입 ==> xml에서는 <property name = "mesg"
	public void setMesg(String mesg) {
		logger.info("setMesg 메서드 호출");
		this.mesg = mesg;
	}
	
	public String getMesg() {
		return mesg;
	}
	
	// init-method에서 호출
	public void init() {
		logger.info("init 메서드 호출");
	}
	
	// destroy-method에서 호출
	public void cleanup() {
		logger.info("cleanup 메서드 호출");
	}
	
}

conf.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.xsd">
	
	<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init" destroy-method="cleanup">
		<property name="mesg" value="helloworld" />
	</bean>
	
</beans>

* 출력 화면 

 

 Spring Injection_Callback

ExampleMain.java

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

public class ExampleMain {
	public static void main(String[] args) {
	
		// IoC Container
		
		//ApplicationContext ctx =
		GenericXmlApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/conf.xml");
		
		ctx.close();
	}
}

ExampleBean.java

package examples;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class ExampleBean implements InitializingBean, DisposableBean{
	
	private static final Logger logger = LoggerFactory.getLogger(ExampleBean.class);

	String mesg; // null 
	
	public ExampleBean() {
		logger.info("ExampleBean 생성자 호출");
	}

	// setter 메서드 주입 ==> xml에서는 <property name = "mesg"
	public void setMesg(String mesg) {
		logger.info("setMesg 메서드 호출");
		this.mesg = mesg;
	}
	
	public String getMesg() {
		return mesg;
	}
	
	// init-method에서 호출
	public void init() {
		logger.info("init 메서드 호출");
	}
	
	// destroy-method에서 호출
	public void cleanup() {
		logger.info("cleanup 메서드 호출");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		logger.info("afterPropertiesSet 메서드 호출");
		
	}

	@Override
	public void destroy() throws Exception {
		logger.info("destroy 메서드 호출");
	}
	
}

conf.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.xsd">
	
	<bean id="exampleInitBean" class="examples.ExampleBean">
		<property name="mesg" value="helloworld" />
	</bean>
	
</beans>

* 출력 화면 

 

 Spring Injection_Callback

ExampleMain.java

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

public class ExampleMain {
	public static void main(String[] args) {
	
		// IoC Container
		
		//ApplicationContext ctx =
		GenericXmlApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/config/conf.xml");
		
		ctx.close();
	}
}

ExampleBean.java

package examples;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class ExampleBean {
	
	private static final Logger logger = LoggerFactory.getLogger(ExampleBean.class);

	String mesg; // null 
	
	public ExampleBean() {
		logger.info("ExampleBean 생성자 호출");
	}

	// setter 메서드 주입 ==> xml에서는 <property name = "mesg"
	public void setMesg(String mesg) {
		logger.info("setMesg 메서드 호출");
		this.mesg = mesg;
	}
	
	public String getMesg() {
		return mesg;
	}
	
	@PostConstruct
    public void populateMovieCache() {
        logger.info("@PostConstruct 메서드 호출");
    }

    @PreDestroy
    public void clearMovieCache() {
    	logger.info("@PreDestroy 메서드 호출");
    }
}

conf.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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- @ 어노테이션 활성화 -->
	<context:annotation-config />
	
	<bean id="exampleInitBean" class="examples.ExampleBean">
		<property name="mesg" value="helloworld" />
	</bean>
	
</beans>

* 출력 화면 

 

 출처

 

+ 강의 교재

실습 2일차_Injection_Collection(list & set & map &props)

 

https://docs.spring.io/spring-framework/docs/4.3.0.RELEASE/spring-framework-reference/html/beans.html#beans-collection-elements

 

 Spring Injection_Collection_list

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Person p1 = ctx.getBean("p1", Person.class);
		
		
		System.out.printf("이름:%s 나이:%s 주소:%s \n", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat
		
		List<String> emailList = p1.getEmailList();
		for (String email : emailList) {
			System.out.println("email:\n" + email);
		}
		
		List<Cat> catList = p1.getCatList();
		for ( Cat c : catList) {
			System.out.printf("고양이 이름:%s 나이:%s 성별:%s \n", c.getName(), c.getAge(), c.getSex());
		}
			
	}

}

Cat.java

package com.dto;

public class Cat {
	String name;
	int age;
	String sex;
	
	/* test.xml
	 * <bean id="p1" class="com.dto.Person">
		<constructor-arg name="username" value="홍길동" />
		<constructor-arg name="userage" value="30" />
		<constructor-arg name="address" value="서울" />
		<constructor-arg name="cat" ref="cat" />
	</bean>
	 * constructor가 아닌 property는 기본 생성자가 있어야함
	 */
	
	public Cat() {
		
	}

	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;
import java.util.List;

public class Person {
	
	String username;
	int userage;
	String address;
	
	// 이메일
	List<String> emailList;
	
	// 여러개의 Cat 관리
	List<Cat> catList;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public List<String> getEmailList() {
		return emailList;
	}

	public void setEmailList(List<String> emailList) {
		this.emailList = emailList;
	}

	public List<Cat> getCatList() {
		return catList;
	}

	public void setCatList(List<Cat> catList) {
		this.catList = catList;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", emailList="
				+ emailList + ", catList=" + catList + "]";
	}
	
}

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

	<bean id="cat1" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="cat2" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비2" />
		<property name="age" value="3" />
		<property name="sex" value="숫컷" />
	</bean>
	
	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="userage" value="30" />
		<property name="address" value="서울" />
		<property name="catList">
			<list>
				<ref bean="cat1" /> <!-- 0번째 -->
				<ref bean="cat2" /> <!-- 1번째 -->
			</list>
		</property>
		
		<property name="emailList">
			<list>
				<value>aaa@daum.net</value>
				<value>aaa@naver.com</value>
			</list>
		</property>
	</bean>
	
	<!-- https://docs.spring.io/spring-framework/docs/4.3.0.RELEASE/spring-framework-reference/html/beans.html#beans-collection-elements -->

</beans>

* 출력 화면 

 

 Spring Injection_Collection_list_util

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");


		Person p1 = ctx.getBean("p1", Person.class);
		
		
		System.out.printf("이름:%s 나이:%s 주소:%s \n", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat
		
		List<String> emailList = p1.getEmailList();
		for ( String email : emailList) {
			System.out.println("email:\n" + email);
		}
		
		List<Cat> catList = p1.getCatList();
		for ( Cat c : catList) {
			System.out.printf("고양이 이름:%s 나이:%s 성별:%s \n", c.getName(), c.getAge(), c.getSex());
		}
		
	}
}

Cat.java

package com.dto;

public class Cat {
	String name;
	int age;
	String sex;
	
	/* test.xml 일부
	 * <bean id="p1" class="com.dto.Person">
		<constructor-arg name="username" value="홍길동" />
		<constructor-arg name="userage" value="30" />
		<constructor-arg name="address" value="서울" />
		<constructor-arg name="cat" ref="cat" />
	</bean>
	 * constructor가 아닌 property는 기본 생성자가 있어야함
	 */
	
	public Cat() {
		
	}

	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;
import java.util.List;

public class Person {
	
	String username;
	int userage;
	String address;
	
	// 이메일
	List<String> emailList;
	
	// 여러개의 Cat 관리
	List<Cat> catList;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public List<String> getEmailList() {
		return emailList;
	}

	public void setEmailList(List<String> emailList) {
		this.emailList = emailList;
	}

	public List<Cat> getCatList() {
		return catList;
	}

	public void setCatList(List<Cat> catList) {
		this.catList = catList;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", emailList="
				+ emailList + ", catList=" + catList + "]";
	}

}

test.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"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<bean id="cat1" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="cat2" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비2" />
		<property name="age" value="3" />
		<property name="sex" value="숫컷" />
	</bean>
	
	<util:list id="globalCatList">
		<ref bean="cat1" /> <!-- 0번째 -->
		<ref bean="cat2" /> <!-- 1번째 -->
		<ref bean="cat1" /> <!-- 중복허용 -->
		<ref bean="cat1" /> <!-- 중복허용 -->
	</util:list>
	
	<util:list id="globalEmailList">
		<value>aaa@daum.net</value>
		<value>aaa@naver.com</value>
	</util:list>
	
	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="userage" value="30" />
		<property name="address" value="서울" />
		<property name="catList" ref="globalCatList" />
		<property name="emailList" ref="globalEmailList" />
	</bean>
	
	<!-- https://docs.spring.io/spring-framework/docs/4.3.0.RELEASE/spring-framework-reference/html/beans.html#beans-collection-elements -->

</beans>

* 출력 화면 

* spring link : https://docs.spring.io/spring-framework/docs/4.3.0.RELEASE/spring-framework-reference/html/beans.html#beans-collection-elements

 

 Spring Injection_Collection_set

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Person p1 = ctx.getBean("p1", Person.class);
		
		System.out.printf("이름:%s 나이:%s 주소:%s \n", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat
		
		List<String> emailList = p1.getEmailSet();
		for ( String email : emailList) {
			System.out.println("email:\n" + email);
		}
		
		List<Cat> catList = p1.getCatSet();
		for ( Cat c : catList) {
			System.out.printf("고양이 이름:%s 나이:%s 성별:%s \n", c.getName(), c.getAge(), c.getSex());
		}
			
	}
	
}

Cat.java

package com.dto;

public class Cat {
	String name;
	int age;
	String sex;
	
	/* test.xml 일부
	 * <bean id="p1" class="com.dto.Person">
		<constructor-arg name="username" value="홍길동" />
		<constructor-arg name="userage" value="30" />
		<constructor-arg name="address" value="서울" />
		<constructor-arg name="cat" ref="cat" />
	</bean>
	 * constructor가 아닌 property는 기본 생성자가 있어야함
	 */
	
	public Cat() {
		// TODO Auto-generated constructor stub
	}

	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;

import java.util.List;

public class Person {
	
	String username;
	int userage;
	String address;
	
	// 이메일
	List<String> emailSet;
	
	// 여러개의 Cat 관리
	List<Cat> catSet;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public List<String> getEmailSet() {
		return emailSet;
	}

	public void setEmailSet(List<String> emailSet) {
		this.emailSet = emailSet;
	}

	public List<Cat> getCatSet() {
		return catSet;
	}

	public void setCatSet(List<Cat> catSet) {
		this.catSet = catSet;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", emailSet="
				+ emailSet + ", catSet=" + catSet + "]";
	}

}

test.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"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<bean id="cat1" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="cat2" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비2" />
		<property name="age" value="3" />
		<property name="sex" value="숫컷" />
	</bean>
	
	<util:list id="globalCatSet">
		<ref bean="cat1" /> <!-- 0번째 -->
		<ref bean="cat2" /> <!-- 1번째 -->
		<ref bean="cat1" /> <!-- 중복허용 -->
		<ref bean="cat1" /> <!-- 중복허용 -->
	</util:list>
	
	<util:list id="globalEmailSet">
		<value>aaa@daum.net</value>
		<value>aaa@naver.com</value>
	</util:list>
	
	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="userage" value="30" />
		<property name="address" value="서울" />
		<property name="catSet" ref="globalCatSet" />
		<property name="emailSet" ref="globalEmailSet" />
	</bean>
	
	<!-- https://docs.spring.io/spring-framework/docs/4.3.0.RELEASE/spring-framework-reference/html/beans.html#beans-collection-elements -->

</beans>

* 출력 화면 

 

 Spring Injection_Collection_set_util

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Person p1 = ctx.getBean("p1", Person.class);
		
		
		System.out.printf("이름:%s 나이:%s 주소:%s \n", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat
		
		List<String> emailList = p1.getEmailSet();
		for ( String email : emailList) {
			System.out.println("email:\n" + email);
		}
		
		List<Cat> catList = p1.getCatSet();
		for ( Cat c : catList) {
			System.out.printf("고양이 이름:%s 나이:%s 성별:%s \n", c.getName(), c.getAge(), c.getSex());
		}
				
	}

}

Cat.java

package com.dto;

public class Cat {
	String name;
	int age;
	String sex;
	
	/* test.xml
	 * <bean id="p1" class="com.dto.Person">
		<constructor-arg name="username" value="홍길동" />
		<constructor-arg name="userage" value="30" />
		<constructor-arg name="address" value="서울" />
		<constructor-arg name="cat" ref="cat" />
	</bean>
	 * constructor가 아닌 property는 기본 생성자가 있어야함
	 */
	
	public Cat() {
		
	}

	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;

import java.util.List;

public class Person {
	
	String username;
	int userage;
	String address;
	
	// 이메일
	List<String> emailSet;
	
	// 여러개의 Cat 관리
	List<Cat> catSet;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public List<String> getEmailSet() {
		return emailSet;
	}

	public void setEmailSet(List<String> emailSet) {
		this.emailSet = emailSet;
	}

	public List<Cat> getCatSet() {
		return catSet;
	}

	public void setCatSet(List<Cat> catSet) {
		this.catSet = catSet;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", emailSet="
				+ emailSet + ", catSet=" + catSet + "]";
	}

}

test.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"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<bean id="cat1" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="cat2" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비2" />
		<property name="age" value="3" />
		<property name="sex" value="숫컷" />
	</bean>
	
	<util:set id="globalCatSet">
		<ref bean="cat1" /> <!-- 0번째 -->
		<ref bean="cat2" /> <!-- 1번째 -->
		<ref bean="cat1" /> <!-- 중복허용 -->
		<ref bean="cat1" /> <!-- 중복허용 -->
	</util:set>
	
	<util:set id="globalEmailSet">
		<value>aaa@daum.net</value>
		<value>aaa@naver.com</value>
	</util:set>
	
	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="userage" value="30" />
		<property name="address" value="서울" />
		<property name="catSet" ref="globalCatSet" />
		<property name="emailSet" ref="globalEmailSet" />
	</bean>
	
	<!-- https://docs.spring.io/spring-framework/docs/4.3.0.RELEASE/spring-framework-reference/html/beans.html#beans-collection-elements -->

</beans>

* 출력 화면 

 

 Spring Injection_Collection_map

MainClass.java

import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Person p1 = ctx.getBean("p1", Person.class);
			
		System.out.printf("이름:%s 나이:%s 주소:%s \n", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat
		
		Map<String, String> emailMap = p1.getEmailMap();
		Set<String> keys = emailMap.keySet();
		for (String key : keys) {
			System.out.printf("이메일:%s", emailMap.get(key));
		}
		
		Map<String, Cat> catMap = p1.getCatMap();
		Set<String> keys2 = catMap.keySet();
		for (String key : keys2) {
			Cat c = catMap.get(key);
			System.out.printf("고양이 이름:%s 나이:%d 성별:%s \n", c.getName(), c.getAge(), c.getSex());
		}
				
	}

}

Cat.java

package com.dto;

public class Cat {
	String name;
	int age;
	String sex;
	
	/* test.xml 일부
	 * <bean id="p1" class="com.dto.Person">
		<constructor-arg name="username" value="홍길동" />
		<constructor-arg name="userage" value="30" />
		<constructor-arg name="address" value="서울" />
		<constructor-arg name="cat" ref="cat" />
	</bean>
	 * constructor가 아닌 property는 기본 생성자가 있어야함
	 */
	
	public Cat() {

	}

	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;
import java.util.List;
import java.util.Map;

public class Person {
	
	String username;
	int userage;
	String address;
	
	// 이메일
	Map<String, String> emailMap;
	
	// 여러개의 Cat 관리
	Map<String, Cat> catMap;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Map<String, String> getEmailMap() {
		return emailMap;
	}

	public void setEmailMap(Map<String, String> emailMap) {
		this.emailMap = emailMap;
	}

	public Map<String, Cat> getCatMap() {
		return catMap;
	}

	public void setCatMap(Map<String, Cat> catMap) {
		this.catMap = catMap;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", emailMap="
				+ emailMap + ", catMap=" + catMap + "]";
	}

}

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

	<bean id="cat1" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="cat2" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비2" />
		<property name="age" value="3" />
		<property name="sex" value="숫컷" />
	</bean>
	
	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="userage" value="30" />
		<property name="address" value="서울" />
		<property name="catMap">
			<map>
				<entry key="c1" value-ref="cat1" />
				<entry key="c2">
					<ref bean="cat2"/>
				</entry>
			</map>
		</property>
		
		<property name="emailMap">
			<map>
				<entry key="e1" value="aaa@daum.net" />
				<entry key="e2">
					<value>aaa@naver.com</value>
				</entry>
			</map>
		</property>
	</bean>
	
	<!-- https://docs.spring.io/spring-framework/docs/4.3.0.RELEASE/spring-framework-reference/html/beans.html#beans-collection-elements -->

</beans>

* 출력 화면 

 

 Spring Injection_Collection_map_util

MainClass.java

import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");


		Person p1 = ctx.getBean("p1", Person.class);
		
		System.out.printf("이름:%s 나이:%s 주소:%s \n", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat
		
		Map<String, String> emailMap = p1.getEmailMap();
		Set<String> keys = emailMap.keySet();
		for (String key : keys) {
			System.out.printf("이메일:%s \n", emailMap.get(key));
		}
		
		Map<String, Cat> catMap = p1.getCatMap();
		Set<String> keys2 = catMap.keySet();
		for (String key : keys2) {
			Cat c = catMap.get(key);
			System.out.printf("고양이 이름:%s 나이:%d 성별:%s \n", c.getName(), c.getAge(), c.getSex());
		}
		
	}

}

Cat.java

package com.dto;

public class Cat {
	String name;
	int age;
	String sex;
	
	/* test.xml 일부
	 * <bean id="p1" class="com.dto.Person">
		<constructor-arg name="username" value="홍길동" />
		<constructor-arg name="userage" value="30" />
		<constructor-arg name="address" value="서울" />
		<constructor-arg name="cat" ref="cat" />
	</bean>
	 * constructor가 아닌 property는 기본 생성자가 있어야함
	 */
	
	public Cat() {
		// TODO Auto-generated constructor stub
	}

	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;
import java.util.List;
import java.util.Map;

public class Person {
	
	String username;
	int userage;
	String address;
	
	// 이메일
	Map<String, String> emailMap;
	
	// 여러개의 Cat 관리
	Map<String, Cat> catMap;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Map<String, String> getEmailMap() {
		return emailMap;
	}

	public void setEmailMap(Map<String, String> emailMap) {
		this.emailMap = emailMap;
	}

	public Map<String, Cat> getCatMap() {
		return catMap;
	}

	public void setCatMap(Map<String, Cat> catMap) {
		this.catMap = catMap;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", emailMap="
				+ emailMap + ", catMap=" + catMap + "]";
	}

}

test.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"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<bean id="cat1" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="cat2" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비2" />
		<property name="age" value="3" />
		<property name="sex" value="숫컷" />
	</bean>
	
	<util:map id="globalCatMap">
		<entry key="c1" value-ref="cat1" />
		<entry key="c2">
			<ref bean="cat2" />
		</entry>
	</util:map>
	
	<util:map id="globalEmailMap">
		<entry key="e1" value="aaa@daum.net" />
		<entry key="e2">
			<value>aaa2@naver.com</value>
		</entry>
	</util:map>
	
	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="userage" value="30" />
		<property name="address" value="서울" />
		<property name="catMap" ref="globalCatMap" />	
		<property name="emailMap" ref="globalEmailMap" />
			
	</bean>
	
	<!-- https://docs.spring.io/spring-framework/docs/4.3.0.RELEASE/spring-framework-reference/html/beans.html#beans-collection-elements -->

</beans>

* 출력 화면 

 

 Spring Injection_Collection_props

MainClass.java

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Person p1 = ctx.getBean("p1", Person.class);
		
		
		System.out.printf("이름:%s 나이:%s 주소:%s", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat
		
		
		Properties emailMap = p1.getEmailMap();
		Set<String> keys  = emailMap.stringPropertyNames();
		for(String key : keys) {
			System.out.printf("이메일:%s \n", emailMap.getProperty(key));
		}		
		
		Map<String, Cat> catMap = p1.getCatMap();
		Set<String> keys2 = catMap.keySet();
		for (String key : keys2) {
			Cat c = catMap.get(key);
			System.out.printf("고양이 이름:%s 나이:%d 성별:%s \n", c.getName(), c.getAge(), c.getSex());
		}

	}
}

Cat.java

package com.dto;

public class Cat {
	String name;
	int age;
	String sex;
	
	/* test.xml 일부
	 * <bean id="p1" class="com.dto.Person">
		<constructor-arg name="username" value="홍길동" />
		<constructor-arg name="userage" value="30" />
		<constructor-arg name="address" value="서울" />
		<constructor-arg name="cat" ref="cat" />
	</bean>
	 * constructor가 아닌 property는 기본 생성자가 있어야함
	 */
	
	public Cat() {
	
	}

	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Person {
	
	String username;
	int userage;
	String address;
	
	// 이메일
	//Map<String, String> emailMap;
	Properties emailMap;
	
	// 여러개의 Cat 관리
	Map<String, Cat> catMap;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}


	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Properties getEmailMap() {
		return emailMap;
	}

	public void setEmailMap(Properties emailMap) {
		this.emailMap = emailMap;
	}

	public Map<String, Cat> getCatMap() {
		return catMap;
	}

	public void setCatMap(Map<String, Cat> catMap) {
		this.catMap = catMap;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", emailMap="
				+ emailMap + ", catMap=" + catMap + "]";
	}
	
}

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

	<bean id="cat1" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="cat2" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비2" />
		<property name="age" value="3" />
		<property name="sex" value="숫컷" />
	</bean>
	
	<bean id="p1" class="com.dto.Person">
		<property name="username" value="홍길동" />
		<property name="userage" value="30" />
		<property name="address" value="서울" />
		<property name="catMap">
			<map>
				<entry key="c1" value-ref="cat1" />
				<entry key="c2">
					<ref bean="cat2"/>
				</entry>
			</map>
		</property>
		
		<property name="emailMap">
		
			<props>
				<prop key="e1">aaa@daum.net</prop>
				<prop key="e2">aaa2@naver.com</prop>
			</props>	
		</property>
	</bean>
	
	<!-- https://docs.spring.io/spring-framework/docs/4.3.0.RELEASE/spring-framework-reference/html/beans.html#beans-collection-elements -->
</beans>

* 출력 화면 

 

 Spring Injection_Collection_props_util

MainClass.java

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Person p1 = ctx.getBean("p1", Person.class);
		
		
		System.out.printf("이름:%s 나이:%s 주소:%s \n", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat		
		
		Properties emailMap = p1.getEmailMap();
		Set<String> keys  = emailMap.stringPropertyNames();
		for(String key : keys) {
			System.out.printf("이메일:%s \n", emailMap.getProperty(key));
		}
	
		Map<String, Cat> catMap = p1.getCatMap();
		Set<String> keys2 = catMap.keySet();
		for (String key : keys2) {
			Cat c = catMap.get(key);
			System.out.printf("고양이 이름:%s 나이:%d 성별:%s \n", c.getName(), c.getAge(), c.getSex());
		}
			
	}

}

Cat.java

package com.dto;

public class Cat {
	String name;
	int age;
	String sex;
	
	/* test.xml 일부
	 * <bean id="p1" class="com.dto.Person">
		<constructor-arg name="username" value="홍길동" />
		<constructor-arg name="userage" value="30" />
		<constructor-arg name="address" value="서울" />
		<constructor-arg name="cat" ref="cat" />
	</bean>
	 * constructor가 아닌 property는 기본 생성자가 있어야함
	 */
	
	public Cat() {

	}

	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Person {
	
	String username;
	int userage;
	String address;
	
	// 이메일
	//Map<String, String> emailMap;
	Properties emailMap;
	
	// 여러개의 Cat 관리
	Map<String, Cat> catMap;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Properties getEmailMap() {
		return emailMap;
	}

	public void setEmailMap(Properties emailMap) {
		this.emailMap = emailMap;
	}

	public Map<String, Cat> getCatMap() {
		return catMap;
	}

	public void setCatMap(Map<String, Cat> catMap) {
		this.catMap = catMap;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", emailMap="
				+ emailMap + ", catMap=" + catMap + "]";
	}

}

test.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"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<bean id="cat1" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="cat2" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비2" />
		<property name="age" value="3" />
		<property name="sex" value="숫컷" />
	</bean>
	
	<util:properties id="globalEmailProps">
		<prop key="e1">aaa@daum.net</prop>
		<prop key="e2">aaa2@naver.com</prop>
	</util:properties>
	
	<bean id="p1" class="com.dto.Person">
		<property name="username" value="고길동" />
		<property name="userage" value="30" />
		<property name="address" value="서울" />
		<property name="catMap">
			<map>
				<entry key="c1" value-ref="cat1" />
				<entry key="c2">
					<ref bean="cat2"/>
				</entry>
			</map>
		</property>
		<property name="emailMap" ref="globalEmailProps" />

	</bean>
	
	<!-- https://docs.spring.io/spring-framework/docs/4.3.0.RELEASE/spring-framework-reference/html/beans.html#beans-collection-elements -->

</beans>

* 출력 화면 

 

 출처

 

+ 강의 교재

실습 2일차_Injection_Constructor & Setter 혼합

 

 Spring Injection_Constructor & Setter 혼합

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {

	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");

		UserService service =
				ctx.getBean("service", UserService.class);
		System.out.println(service);
		
		UserService service2 =
				ctx.getBean("service2", UserService.class);
		System.out.println(service2);
		
	}
}

UserService.java

package com.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// POJO Class
public class UserService {
	// 인스턴스
	String mesg; // null ==> 외부에서 문자열을 주입
	int num; 	 // 0 ==> 외부에서 값을 주입
	
	// 생성자 주입
	public UserService(String m) {
		this.mesg = m;
	}
	
	// setter 메서드 주입
	public void setNum(int num) {
		this.num = num;
	}

	public UserService(int n) {
		this.num = n;
	}
	
	// overriding?
	public UserService(String m, int n) {
		this.mesg = m;
		this.num = n;
	}
	
	// getter
	public String getMesg() {
		return mesg;
	}
	
	public int getNum() {
		return num;
	}

	// toString
	@Override
	public String toString() {
		return "UserService [mesg=" + mesg + ", num=" + num + "]";
	}
	
}

user.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"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="service" class="com.service.UserService">
		<constructor-arg name="m" value="고길동" />
		<property name="num" value="20"/> 
		<!-- 고길동이 생성자에 의해서 mesg 변수에 저장이 됨 -->
	</bean>

	<!-- 
		c namespace
		p namespace
	 -->
	 
	 <bean id="service2" class="com.service.UserService" c:m="고길동" p:num="30" />
	
</beans>

* 출력 화면 

 

 Spring Injection_shortcut_p 2

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");

		UserService service = ctx.getBean("service", UserService.class);
		List<String> list = service.list();
		System.out.println(list);
		
		UserService service2 = ctx.getBean("service2", UserService.class);
		List<String> list2 = service2.list();
		System.out.println(list2);
		
	}
}

UserService.java

package com.service;
import java.util.List;
import com.dao.UserDAO;

// POJO Class
public class UserService {
	// property (인스턴스 변수)
	UserDAO dao;
	
	// setter 메서드 주입
	public UserService(UserDAO dao) {
		this.dao = dao;
	}
	
	public List<String> list(){
		return dao.list();
	}

}

UserDAO.java

package com.dao;
import java.util.Arrays;
import java.util.List;

public class UserDAO {

	// DB 연동 가정
	public List<String> list(){
		List<String> list = Arrays.asList("고길동", "신길동", "홍길동");
		return list;
	}
}

user.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"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="dao" class="com.dao.UserDAO" /> 		<!-- bean 태그로 등록하면 기본 생성자 호출 가능 -->
	<!--  다음 코드와 동일
		UserDAO userDAO = new UserDAO();
	 --> 
	<bean id="service" class="com.service.UserService"> <!-- id는 식별 가능한 값, class는 클래스 입력 -->
		<constructor-arg name="dao" ref="dao" />
	</bean>
	<!-- 다음 코드와 동일
		UserService service = new UserService();
		service.setDAO(UserDAO);
	 -->
	
	<!-- 
		c namespace
	 -->
	 
	 <bean id="service2" class="com.service.UserService" c:dao-ref="dao" />
	<!--  
		UserService service2= new UserService(dao);
	 --> 
</beans>

* 출력 화면 :

 

 출처

 

+ 강의 교재

실습 2일차_Injection_shortcut_c

 

 Spring Injection_shortcut_c 1

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");

		UserService service =
				ctx.getBean("service", UserService.class);
		System.out.println(service.getMesg());
		
		UserService service2 =
				ctx.getBean("service2", UserService.class);
		System.out.println(service2.getMesg());
		
	}
}

UserService.java

package com.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// POJO Class
public class UserService {

	String mesg; // null ==> 외부에서 문자열을 주입
	
	// 생성자 주입
	public UserService(String m) {
		this.mesg = m;
	}
	
	public String getMesg() {
		return mesg;
	}
}

user.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"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


	<bean id="service" class="com.service.UserService">
		<constructor-arg name="m" value="helloWorld" />
	</bean>
	<!-- 
		위의 코드는 다음 코드와 동일하다.
		UserService service = new UserService("helloWorld");
	 -->
	
	<!-- 
		c namespace
	 -->
	 
	 <bean id="service2" class="com.service.UserService" c:m="happyworld" />
</beans>

* 출력 화면 

 

 Spring Injection_shortcut_p 2

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");

		UserService service = ctx.getBean("service", UserService.class);
		List<String> list = service.list();
		System.out.println(list);
		
		UserService service2 = ctx.getBean("service2", UserService.class);
		List<String> list2 = service2.list();
		System.out.println(list2);
		
	}
}

UserService.java

package com.service;
import java.util.List;
import com.dao.UserDAO;

// POJO Class
public class UserService {
	// property (인스턴스 변수)
	UserDAO dao;
	
	// setter 메서드 주입
	public UserService(UserDAO dao) {
		this.dao = dao;
	}
	
	public List<String> list(){
		return dao.list();
	}

}

UserDAO.java

package com.dao;
import java.util.Arrays;
import java.util.List;

public class UserDAO {

	// DB 연동 가정
	public List<String> list(){
		List<String> list = Arrays.asList("고길동", "신길동", "홍길동");
		return list;
	}
}

user.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"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="dao" class="com.dao.UserDAO" /> 		<!-- bean 태그로 등록하면 기본 생성자 호출 가능 -->
	<!--  다음 코드와 동일
		UserDAO userDAO = new UserDAO();
	 --> 
	<bean id="service" class="com.service.UserService"> <!-- id는 식별 가능한 값, class는 클래스 입력 -->
		<constructor-arg name="dao" ref="dao" />
	</bean>
	<!-- 다음 코드와 동일
		UserService service = new UserService();
		service.setDAO(UserDAO);
	 -->
	
	<!-- 
		c namespace
	 -->
	 
	 <bean id="service2" class="com.service.UserService" c:dao-ref="dao" />
	<!--  
		UserService service2= new UserService(dao);
	 --> 
</beans>

* 출력 화면 :

 

 출처

 

+ 강의 교재

실습 2일차_Injection_shortcut_p

 

 Spring Injection_shortcut_p 1

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");

		UserService service =
				ctx.getBean("service", UserService.class);
		System.out.println(service.getMesg());
		
		UserService service2 =
				ctx.getBean("service2", UserService.class);
		System.out.println(service2.getMesg());
		
	}
}

UserService.java

package com.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// POJO Class
public class UserService {

	String mesg; // null ==> 외부에서 문자열을 주입
	
	// setter 메서드 주입
	public void setMesg(String mesg) {
		System.out.println("setMesg 메서드");
		this.mesg = mesg;
	}
	
	public String getMesg() {
		return mesg;
	}
	
}

user.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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="service" class="com.service.UserService"> <!-- id는 식별 가능한 값, class는 클래스 입력 -->
		<property name="mesg" value="HelloWorld" />     <!-- System.out.println("setMesg 메서드"); property에 의해 출력 -->
	</bean>
	<!-- 아래 코드와 동일
		UserService service = new UserService();
		service.setMesg("HelloWorld");
	 -->
	
	<bean id="service2" class="com.service.UserService" p:mesg="HappyWorld" />
	<!-- 아래 코드와 동일
		UserService service2 = new UserService();
		service2.setMesg("HelloWorld");
	 -->
</beans>

* 출력 화면 

 

 Spring Injection_shortcut_p 2

MainClass.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {

	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");

		UserService service = ctx.getBean("service", UserService.class);
		System.out.println(service.getMesg());
		System.out.println(service);
		
		UserService service2 = ctx.getBean("service2", UserService.class);
		System.out.println(service2.getMesg());
		System.out.println(service2);
		
		UserService service3 = ctx.getBean("service3", UserService.class);
		System.out.println(service3.getMesg());
		System.out.println(service3);
		
		UserService service4 = ctx.getBean("service4", UserService.class);
		System.out.println(service4.getMesg());
		System.out.println(service4);
		
	}
}

UserService.java

package com.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// POJO Class
public class UserService {
	// property (인스턴스 변수)
	String mesg; // null ==> 외부에서 문자열을 주입
	int num; 	 // 0 ==> 외부에서 값을 주입
	
	// setter 메서드 주입
	public void setMesg(String mesg) {
		this.mesg = mesg;
	}
	
	public void setNum(int num) {
		this.num = num;
	}
	
	public void setMesgNum(String mesg, int num) {
		this.mesg = mesg;
		this.num = num;
	}
	
	// getter
	public String getMesg() {
		return mesg;
	}
	
	public int getNum() {
		return num;
	}

	// toString
	@Override
	public String toString() {
		return "UserService [mesg=" + mesg + ", num=" + num + "]";
	}
	
}

user.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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="service" class="com.service.UserService"> <!-- id는 식별 가능한 값, class는 클래스 입력 -->
		<property name="mesg" value="HelloWorld" />     <!-- System.out.println("setMesg 메서드"); property에 의해 출력 -->
	</bean>
	<!-- 
		UserService service = new UserService();
		service.setMesg("HelloWorld");
	 -->
	
	<bean id="service2" class="com.service.UserService">
		<property name="num" value="20" />
	</bean>

	<bean id="service3" class="com.service.UserService">
		<property name="mesg" value="Happy" />
		<property name="num" value="30" />
	</bean>
	<!-- setter based injection -->
	
	<!--  
		p namespace 사용
	 -->
	<bean id="service4" class="com.service.UserService" p:mesg="Lucky" p:num="40"/>

</beans>

 

* 출력 화면

 

 Spring Injection_shortcut_p 3

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.service.UserService;

public class MainClass {

	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/config/user.xml");

		UserService service = ctx.getBean("service", UserService.class);
		List<String> list = service.list();
		System.out.println(list);
		
		UserService service2 = ctx.getBean("service2", UserService.class);
		List<String> list2 = service.list();
		System.out.println(list2);
		
	}
}

UserService.java

package com.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dao.UserDAO;

// POJO Class
public class UserService {
	// property (인스턴스 변수)
	UserDAO dao;
	
	// setter 메서드 주입
	public void setDao(UserDAO dao) {
		this.dao = dao;
	}
	
	public List<String> list(){
		return dao.list();
	}
	
}

UserDAO.java

package com.dao;
import java.util.Arrays;
import java.util.List;

public class UserDAO {

	// DB 연동 가정
	public List<String> list(){
		List<String> list = Arrays.asList("고길동", "신길동", "홍길동");
		return list;
	}
}

user.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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="userDAO" class="com.dao.UserDAO" /> 		<!-- bean 태그로 등록하면 기본 생성자 호출 가능 -->
	<!--  아래 코드와 동일
		UserDAO userDAO = new UserDAO();
	 --> 
	<bean id="service" class="com.service.UserService"> <!-- id는 식별 가능한 값, class는 클래스 입력 -->
		<property name="dao" ref="userDAO"></property>
	</bean>
	<!-- 아래 코드와 동일
		UserService service = new UserService();
		service.setDAO(UserDAO);
	 -->
	
	<!--  
		p namespace 설정
	 -->
	 <bean id="service2" class="com.service.UserService" p:dao-ref="userDAO" />
	<!-- 아래 코드와 동일
		UserService service = new UserService();
		service2.setDAO(UserDAO);
	 -->
</beans>

* 출력 화면 :

 

 

 출처

 

+ 강의 교재

실습 2일차_exam

 

 Spring exam 1_Constructor

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Person p1 = ctx.getBean("p1", Person.class);
		Cat c = p1.getCat();
		
		System.out.printf("이름:%s 나이:%s 주소:%s", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat
		System.out.printf("고양이 이름:%s 나이:%s 성별:%s", c.getName(), c.getAge(), c.getSex());	
	}
}

 

Cat.java

package com.dto;

public class Cat {
	String name;
	int age;
	String sex;
	
	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int userage;
	String address;
	
	Cat cat;

	// 기본 생성자 안 만들고 인자있는 생성자 만듬
	public Person(String username, int userage, String address, Cat cat) {
		super();
		this.username = username;
		this.userage = userage;
		this.address = address;
		this.cat = cat;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Cat getCat() {
		return cat;
	}

	public void setCat(Cat cat) {
		this.cat = cat;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", cat=" + cat + "]";
	}
	
}

 

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

	<bean id="cat" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<constructor-arg name="name" value="나비" />
		<constructor-arg name="age" value="3" />
		<constructor-arg name="sex" value="암컷" />
	</bean>
	
	<bean id="p1" class="com.dto.Person">
		<constructor-arg name="username" value="고길동" />
		<constructor-arg name="userage" value="30" />
		<constructor-arg name="address" value="서울" />
		<constructor-arg name="cat" ref="cat" />
	</bean>

</beans>

* 출력 화면 

 

 Spring exam 2_setter

MainClass.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import com.dto.Cat;
import com.dto.Person;

public class MainClass {
	public static void main(String[] args) {
		
		// IoC Container
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/test.xml");

		Person p1 = ctx.getBean("p1", Person.class);
		Cat c = p1.getCat();
		
		System.out.printf("이름:%s 나이:%s 주소:%s", p1.getUsername(), p1.getUserage(), p1.getAddress()); // printformat
		System.out.printf("고양이 이름:%s 나이:%s 성별:%s", c.getName(), c.getAge(), c.getSex());
		
	}
}

Cat.java

package com.dto;

public class Cat {
	String name;
	int age;
	String sex;
	
	/*
	 * <bean id="p1" class="com.dto.Person">
		<constructor-arg name="username" value="홍길동" />
		<constructor-arg name="userage" value="30" />
		<constructor-arg name="address" value="서울" />
		<constructor-arg name="cat" ref="cat" />
	</bean>
	 * constructor가 아닌 property는 기본 생성자가 있어야함
	 */
	
	public Cat() {

	}

	public Cat(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
	
}

Person.java

package com.dto;

public class Person {
	
	String username;
	int userage;
	String address;
	
	Cat cat;

	/*
	 * <bean id="p1" class="com.dto.Person">
		<constructor-arg name="username" value="홍길동" />
		<constructor-arg name="userage" value="30" />
		<constructor-arg name="address" value="서울" />
		<constructor-arg name="cat" ref="cat" />
	</bean>
	 * constructor가 아닌 property는 기본 생성자가 있어야함
	 */
	
	public Person() {
		// TODO Auto-generated constructor stub
	}

	public Person(String username, int userage, String address, Cat cat) {
		super();
		this.username = username;
		this.userage = userage;
		this.address = address;
		this.cat = cat;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Cat getCat() {
		return cat;
	}

	public void setCat(Cat cat) {
		this.cat = cat;
	}

	@Override
	public String toString() {
		return "Person [username=" + username + ", userage=" + userage + ", address=" + address + ", cat=" + cat + "]";
	}
	
}

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

	<bean id="cat" class="com.dto.Cat"> <!-- 생성자로 주입  -->
		<property name="name" value="나비" />
		<property name="age" value="3" />
		<property name="sex" value="암컷" />
	</bean>
	
	<bean id="p1" class="com.dto.Person">
		<property name="username" value="홍길동" />
		<property name="userage" value="30" />
		<property name="address" value="서울" />
		<property name="cat" ref="cat" />
	</bean>

</beans>

 

* 출력 화면

 

 출처

 

+ 강의 교재

+ Recent posts