전체 글 (254)
2022-03-11 17:18:44
반응형

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

* 출력 화면 :

 

 출처

 

+ 강의 교재

반응형
2022-03-11 17:10:15
반응형

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

* 출력 화면 :

 

 

 출처

 

+ 강의 교재

반응형
2022-03-11 16:32:25
반응형

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

 

* 출력 화면

 

 출처

 

+ 강의 교재

반응형
2022-03-11 00:26:00
반응형

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/

반응형
2022-03-10 22:21:11
반응형

Classes More Than 5 Students

 

 문제 설명

 

Table: Courses

Create table If Not Exists Courses (student varchar(255), class varchar(255))
Truncate table Courses
insert into Courses (student, class) values ('A', 'Math')
insert into Courses (student, class) values ('B', 'English')
insert into Courses (student, class) values ('C', 'Math')
insert into Courses (student, class) values ('D', 'Biology')
insert into Courses (student, class) values ('E', 'Math')
insert into Courses (student, class) values ('F', 'Computer')
insert into Courses (student, class) values ('G', 'Math')
insert into Courses (student, class) values ('H', 'Math')
insert into Courses (student, class) values ('I', 'Math')
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| student       | varchar |
| class           | varchar |
+-------------+---------+

(student, class) is the primary key column for this table.
Each row of this table indicates the name of a student and the class in which they are enrolled.

Write an SQL query to report all the classes that have at least five students.

Return the result table in any order.

The query result format is in the following example.

 

5명 이상의 학생이 있는 클래스 쿼리 확인

 

 입출력 예

 

Example 1:

Input: 
Courses table:
+---------+----------+
| student | class    |
+---------+----------+
| A       | Math     |
| B       | English  |
| C       | Math     |
| D       | Biology  |
| E       | Math     |
| F       | Computer |
| G       | Math     |
| H       | Math     |
| I       | Math     |
+---------+----------+
Output: 
+---------+
| class   |
+---------+
| Math    |
+---------+
Explanation: 
- Math has 6 students, so we include it.
- English has 1 student, so we do not include it.
- Biology has 1 student, so we do not include it.
- Computer has 1 student, so we do not include it.

 

 Oracle Query

 

/* Write your PL/SQL query statement below */
select class 
from courses
group by class
having count(distinct student) > 4

* 참고 링크 : https://leetcode.com/problems/classes-more-than-5-students/discuss/927995/Oracle-Solution

  • 5명 이상의 학생이 있는 class 쿼리— having절은 group by와 같이 사용될 수 있음having count(distinct student) > 4having절은 집계함수를 가지고 조건비교를 할 때 사용한다. 집계함수 종류
  • distinct 중복값 처리 (5명 이상의 학생이 중복되는 경우를 having절로 카운트)
  • (5명 이상의 학생이 있는 클래스를 찾는 것이니 class로 묶어줌
  • group by class

 

 출처

 

https://leetcode.com/problems/classes-more-than-5-students/

반응형
2022-03-10 18:00:52
반응형

실습 2일차_Setter Injection

의존성 주입의 방법으로는 크게 3가지가 있다.

  • 생성자 주입(Constructor Injection)
  • 필드 주입(Field Injection)
  • 세터 주입(Setter Injection)

 

 Spring Setter Injection 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.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"
	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");
	 -->
</beans>

* 출력 화면 

 

Spring Setter Injection 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.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"
	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="35" />
	</bean>
	<!-- setter based injection -->
</beans>

* 출력 화면

 

Spring Setter Injection 3_Service_dao 추가

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.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"
	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);
	 -->
</beans>

* 출력 화면 :

 

 출처

 

+ 강의 교재

반응형