실습 3일차_@Autowired

 

 

 

 Spring @Autowired

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 service3 = ctx.getBean("service3", UserService.class);
		List<String> list3 = service3.list();
		System.out.println(list3);
	}
}

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;
	}
}

UserService.java

package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.dao.UserDAO;

public class UserService {

	@Autowired
	UserDAO dao;
	
	// user.xml 2. property는 기본 생성자가 있어야 에러가 안남
	public UserService() {
		
	}
	
	// 생성자 주입
	public UserService(UserDAO dao) {
		this.dao = dao;
	}
	
	// setter 메서드 주입
	public void setDao(UserDAO dao) {
		this.dao = dao;
	}

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

	<bean id="dao" class="com.dao.UserDAO" />
	
	<!-- @ 어노테이션 활성화  -->
	<context:annotation-config />
	
	<!-- 1. xml의 constructor를 이용한 의존성 주입_Injection -->
	<bean id="service" class="com.service.UserService">
		<constructor-arg name="dao" ref="userDAO" />
	</bean>
	
	<!-- 2. xml의 setter 메서드를 이용한 의존성 주입_Injection -->
	<bean id="service2" class="com.service.UserService">
		<property name="dao" ref="userDAO" />
	</bean>
	
	<!-- 3. @Autowired를 이용한 자동 의존성 주입_Injection -->
	<bean id="service3" class="com.service.UserService" />

</beans>

 

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

* context 활성화 방법

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

 

 

 

* 출력 화면 

 

 Spring @Autowired_required_false

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 service3 = ctx.getBean("service3", UserService.class);
		List<String> list3 = service3.list();
		System.out.println(list3);
	}
}

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;
	}
}

UserService.java

package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.dao.UserDAO;

public class UserService {

	@Autowired(required = false) // 가장 많이 사용
	UserDAO dao;

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

	<bean id="dao" class="com.dao.UserDAO" />
	
	<!-- @ 어노테이션 활성화  -->
	<context:annotation-config />
	
	<!-- 3. @Autowired를 이용한 자동 의존성 주입_Injection -->
	<bean id="service3" class="com.service.UserService" />

</beans>

* 출력 화면 

 

 Spring @Autowired_@Qualifier

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 service3 = ctx.getBean("service3", UserService.class);
		List<String> list3 = service3.list();
		System.out.println(list3);
	}
}

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;
	}
}

UserService.java

package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.dao.UserDAO;

public class UserService {

	@Autowired // 가장 많이 사용
	@Qualifier("userDAO") // 명시적으로 누구를 쓸 것인지 찍어서 설정하면 에러가 안남 ㅋ
	UserDAO dao;

	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 />
	
	<!-- 3. @Autowired를 이용한 자동 의존성 주입_Injection -->
	<bean id="service3" class="com.service.UserService" />
	<bean id="userDAO" class="com.dao.UserDAO" />
	<bean id="userDAO2" class="com.dao.UserDAO" />

</beans>

 

* 출력 화면 

 

 출처

 

@Autowired : 

+ 강의 교재

 

실습 3일차_@Required

 

@Required Annotation은 Spring 2부터 제공되며, 필수 Property를 명시할 때 사용된다. 

필수 Property를 지정하려면 먼저 Property 설정 Method에 @Required Annotation을 붙여야 한다.

 

 Spring @Required

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) {
		
		ApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/config/user.xml");
		
		UserService service = ctx.getBean("service", UserService.class);
		System.out.printf("service: %s", service);

		UserService service2 = ctx.getBean("service2", UserService.class);
		System.out.printf("service2: %s", service2);
		
	}
}

UserService.java

package com.service;

import org.springframework.beans.factory.annotation.Required;

public class UserService {
	
	String mesg; // null

	// setter 메서드 주입
	@Required // 넣어줘야 에러 안 뜸
	public void setMesg(String mesg) {
		this.mesg = mesg;
	}

	@Override
	public String toString() {
		return "UserService [mesg=" + 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: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="service" class="com.service.UserService" />
	
	<bean id="service2" class="com.service.UserService">
		<property name="mesg" value="helloworld" />
	</bean>
	
</beans>

 

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

* context 활성화 방법

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

 

 

 

* 출력 화면 

 

 출처

 

@Required : https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=rex4314&logNo=158814986 

+ 강의 교재

 

실습 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>

* 출력 화면 :

 

 출처

 

+ 강의 교재

Hashing

 

 문제 설명

 

APC에 온 것을 환영한다. 만약 여러분이 학교에서 자료구조를 수강했다면 해시 함수에 대해 배웠을 것이다. 해시 함수란 임의의 길이의 입력을 받아서 고정된 길이의 출력을 내보내는 함수로 정의한다. 해시 함수는 무궁무진한 응용 분야를 갖는데, 대표적으로 자료의 저장과 탐색에 쓰인다.

이 문제에서는 여러분이 앞으로 유용하게 쓸 수 있는 해시 함수를 하나 가르쳐주고자 한다. 먼저, 편의상 입력으로 들어오는 문자열에는 영문 소문자(a, b, ..., z)로만 구성되어있다고 가정하자. 영어에는 총 26개의 알파벳이 존재하므로 a에는 1, b에는 2, c에는 3, ..., z에는 26으로 고유한 번호를 부여할 수 있다. 결과적으로 우리는 하나의 문자열을 수열로 변환할 수 있다. 예를 들어서 문자열 "abba"은 수열 1, 2, 2, 1로 나타낼 수 있다.

해시 값을 계산하기 위해서 우리는 문자열 혹은 수열을 하나의 정수로 치환하려고 한다. 간단하게는 수열의 값을 모두 더할 수도 있다. 해시 함수의 정의에서 유한한 범위의 출력을 가져야 한다고 했으니까 적당히 큰 수 M으로 나눠주자. 짜잔! 해시 함수가 완성되었다. 이를 수식으로 표현하면 아래와 같다.

해시 함수의 입력으로 들어올 수 있는 문자열의 종류는 무한하지만 출력 범위는 정해져있다. 다들 비둘기 집의 원리에 대해서는 한 번쯤 들어봤을 것이다. 그 원리에 의하면 서로 다른 문자열이더라도 동일한 해시 값을 가질 수 있다. 이를 해시 충돌이라고 하는데, 좋은 해시 함수는 최대한 충돌이 적게 일어나야 한다. 위에서 정의한 해시 함수는 알파벳의 순서만 바꿔도 충돌이 일어나기 때문에 나쁜 해시 함수이다. 그러니까 조금 더 개선해보자.

어떻게 하면 순서가 달라졌을때 출력값도 달라지게 할 수 있을까? 머리를 굴리면 수열의 각 항마다 고유한 계수를 부여하면 된다는 아이디어를 생각해볼 수 있다. 가장 대표적인 방법은 항의 번호에 해당하는 만큼 특정한 숫자를 거듭제곱해서 곱해준 다음 더하는 것이 있다. 이를 수식으로 표현하면 아래와 같다.

보통 r과 M은 서로소인 숫자로 정하는 것이 일반적이다. 우리가 직접 정하라고 하면 힘들테니까 r의 값은 26보다 큰 소수인 31로 하고 M의 값은 1234567891(놀랍게도 소수이다!!)로 하자.

이제 여러분이 할 일은 위 식을 통해 주어진 문자열의 해시 값을 계산하는 것이다. 그리고 이 함수는 간단해 보여도 자주 쓰이니까 기억해뒀다가 잘 써먹도록 하자.

 

 입력

 

첫 줄에는 문자열의 길이 L이 들어온다. 둘째 줄에는 영문 소문자로만 이루어진 문자열이 들어온다.

입력으로 주어지는 문자열은 모두 알파벳 소문자로만 구성되어 있다.

 

 출력

 

문제에서 주어진 해시함수와 입력으로 주어진 문자열을 사용해 계산한 해시 값을 정수로 출력한다.

 

 Python 코드

 

n = int(input()) #제시할 문자열의 길이를 입력받는다.
str_ = list(input()) #문자열을 입력받아 리스트에 대입한다.
res = 0 # 출력할 변수 res를 선언한다.

for i in range(n): # 문자열의 길이만큼 반복한다.
    res += ((ord(str_[i]) - 96) * (31 ** i))
# 리스트 내 각각의 요소들은 아스키코드값으로 변경 후 96을 빼면 
# a는 1, b는 2의 값을 지니게 된다.
# 계수가 31이고 문자열의 순서에 따라 지수가 높아지므로 이를 고려하여 식을 짜면 위와 같다.

print(res % 1234567891)
# 해시 함수의 정의에서 유한한 범위의 출력을 가져야 한다고 했으므로 M을 나누어 출력한다.

* 참고 링크 : https://velog.io/@cornflower_blue/%EB%B0%B1%EC%A4%80%ED%8C%8C%EC%9D%B4%EC%8D%AC-15829%EB%B2%88-Hashing-%ED%92%80%EC%9D%B4

# readline을 사용하기 위해 Import
from sys import stdin

# 첫 줄에는 문자열의 길이 L을 입력
# 1 <= L <= 50
# 정수형으로 변환합니다.
L = int(stdin.readline())

# 둘째 줄에는 영문 소문자로만 이루어진 문자열을 입력
# 맨 끝의 \n은 떼어준다.
string = stdin.readline().rstrip()

# 해시 값을 계산할 때 필요한 r, M의 값을 저장하는 변수를 선언
r = 31
M = 1234567891

# mod M을 구하기 전의 ai * r^i의 합계를 저장할 변수를 선언
ar_sum = 0

# 입력한 문자열에서 한 글자씩 반복
for idx in range(L):
    # 현재 글자의 고유 번호를 저장하는 변수를 선언
    ai = ord(string[idx]) -ord('a') +1

    #현재 글자의 ai * r^i 값을 ar_sum에 더해준다.
    ar_sum += ai * (r ** idx)

# 해시값인 ar_sum을 M으로 나눈 뒤의 나머지의 값을 출력
print(ar_sum % M)

 

 C++ 코드

 

#include <iostream> 
#include <string> 
using namespace std; 

const int MOD = 1234567891; 
const int MULTIPLY = 31; 

int main(void) { 
int L; 
cin >> L; 
string s; 
cin >> s; 

long long sum = 0; 
long long R = 1; 

for (int i = 0; i < s.length(); i++) { 
	sum = (sum + (s[i] - 'a' + 1) * R) % MOD; 
	R = (R*MULTIPLY) % MOD; 
} 

cout << sum << "\n"; 
return 0; 
}

* 참고 링크 : https://jaimemin.tistory.com/1445

 

 출처

 

https://www.acmicpc.net/problem/15829

전자레인지

 

 문제 설명

 

3개의 시간조절용 버튼 A B C가 달린 전자레인지가 있다. 각 버튼마다 일정한 시간이 지정되어 있어 해당 버튼을 한번 누를 때마다 그 시간이 동작시간에 더해진다. 버튼 A, B, C에 지정된 시간은 각각 5분, 1분, 10초이다.

냉동음식마다 전자레인지로 요리해야할 시간 T가 초단위로 표시되어 있다. 우리는 A, B, C 3개의 버튼을 적절히 눌러서 그 시간의 합이 정확히 T초가 되도록 해야 한다. 단 버튼 A, B, C를 누른 횟수의 합은 항상 최소가 되어야 한다. 이것을 최소버튼 조작이라고 한다. 

만일 요리시간이 100초라고 하면(T=100) B를 1번, C는 4번 누르면 된다. 이와 다르게 C를 10번 눌러도 100초가 되지만 이 경우 10번은 최소 횟수가 아니기 때문이 답이 될 수 없다. 이 경우 B 1번, C 4번, 총 5번이 최소버튼 조작이다. 그리고 T=234와 같이 3개의 버튼으로 시간을 정확히 맞출 수 없는 경우도 있다. 

여러분은 주어진 요리시간 T초를 맞추기 위한 최소버튼 조작 방법을 구하는 프로그램을 작성해야 한다. 

 

 입력

 

첫 번째 줄에는 요리시간 T(초)가 정수로 주어져 있으며 그 범위는 1 ≤ T ≤ 10,000 이다. 

 

 출력

 

여러분은 T초를 위한 최소버튼 조작의 A B C 횟수를 첫 줄에 차례대로 출력해야 한다. 각각의 횟수 사이에는 빈 칸을 둔다. 해당 버튼을 누르지 않는 경우에는 숫자 0을 출력해야한다. 만일 제시된 3개의 버튼으로 T초를 맞출 수 없으면 음수 -1을 첫 줄에 출력해야 한다. 

 

 Python 코드

 

T = int(input())                # 요리 시간 T를 int type으로 입력을 받는다.

button = [300, 60 ,10]          # 버튼 300, 60, 10을 리스트에 담아준다.

if T % 10 != 0:                 # 만약 T를 10으로 나누었을 때 나머지가 0이 아니면 -1 출력
    print(-1)
else:                           # 그게 아니라면
    for i in button:            # button 안에 있는 i 요소 반복
        print(T//i, end = " ")  # T를 i로 나누었을 때 몫을 띄어쓰기로 출력
        T = T % i               # T는 T를 i로 나누었을 때 몫으로 바꾼다.

 

* 참고 링크 : https://www.youtube.com/watch?v=FoTqNiXgd-0 

 

 C++ 코드

 

#include<iostream>
using namespace std;

int main() {
	
	// A : 300초, B : 60초, C : 10초
	int a, b, c = 0;
	int t;
	cin >> t;

	if (t % 10 != 0) cout << "-1";
	else {
		a = t / 300;
		b = (t % 300) / 60;
		c = ((t % 300) % 60) / 10;
		cout << a << " " << b << " " << c;
	}

	return 0;

}

* 참고 링크 : https://jeongminhee99.tistory.com/86

 

 출처

 

https://www.acmicpc.net/problem/10162

실습 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>

 

* 출력 화면

 

 출처

 

+ 강의 교재

Not Boring Movies

 

 문제 설명

 

Create table If Not Exists cinema (id int, movie varchar(255), description varchar(255), rating float(2, 1))
Truncate table cinema
insert into cinema (id, movie, description, rating) values ('1', 'War', 'great 3D', '8.9')
insert into cinema (id, movie, description, rating) values ('2', 'Science', 'fiction', '8.5')
insert into cinema (id, movie, description, rating) values ('3', 'irish', 'boring', '6.2')
insert into cinema (id, movie, description, rating) values ('4', 'Ice song', 'Fantacy', '8.6')
insert into cinema (id, movie, description, rating) values ('5', 'House card', 'Interesting', '9.1')

Table: Cinema

+----------------+----------+
| Column Name    | Type     |
+----------------+----------+
| id             | int      |
| movie          | varchar  |
| description    | varchar  |
| rating         | float    |
+----------------+----------+
id is the primary key for this table.
Each row contains information about the name of a movie, its genre, and its rating.
rating is a 2 decimal places float in the range [0, 10]

 

Write an SQL query to report the movies with an odd-numbered ID and a description that is not "boring".

Return the result table ordered by rating in descending order.

The query result format is in the following example.

 

 입출력 예

 

Example 1:

Input: 
Cinema table:
+----+------------+-------------+--------+
| id | movie      | description | rating |
+----+------------+-------------+--------+
| 1  | War        | great 3D    | 8.9    |
| 2  | Science    | fiction     | 8.5    |
| 3  | irish      | boring      | 6.2    |
| 4  | Ice song   | Fantacy     | 8.6    |
| 5  | House card | Interesting | 9.1    |
+----+------------+-------------+--------+
Output: 
+----+------------+-------------+--------+
| id | movie      | description | rating |
+----+------------+-------------+--------+
| 5  | House card | Interesting | 9.1    |
| 1  | War        | great 3D    | 8.9    |
+----+------------+-------------+--------+
Explanation: 
We have three movies with odd-numbered IDs: 1, 3, and 5. The movie with ID = 3 is boring so we do not include it in the answer.

 

 Oracle Query

 

select * 
from cinema 
where description!='boring' and mod(id, 2) = 1 
order by rating desc;

* 참고 링크 : https://leetcode.com/problems/not-boring-movies/discuss/1192216/simple-or-100-memory-or-oracle

 

MOD ( ) - 나눈 나머지 값 반환

select mod(3,2)
from dual
-- 결과값: 1

* 참고 링크 : https://devjhs.tistory.com/404, https://20140501.tistory.com/80

 출처

 

https://leetcode.com/problems/not-boring-movies/

+ Recent posts