전체 글 (306)
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>

* 출력 화면 :

 

 출처

 

+ 강의 교재

반응형
2022-03-10 17:13:29
반응형

실습 1일차_Injection (Constructor)

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

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

Constructor Injection 방식을 권장하는 이유

생성자 주입 방식을 권장하는 이유
- 단일 책임의 원칙
생성자의 인자가 많아지면서 하나의 클래스가 많은 책임을 떠안는다는 걸 알게된다.
그래서 Constructor Injection을 사용해 의존관계, 복잡성을 쉽게 알 수 있다.
 
- 의존성이 숨는다
DI(Dependency Injection) 컨테이너를 사용한다는 것은 클래스가 자신의 의존성만 책임지는게 아니다.
제공된 의존성 또한 책임진다. 그래서 클래스가 어떤 의존성을 책임지지 않을 때, 메소드나 생성자를 통해
커뮤니케이션이 되어야한다. 하지만 Field Injection은 숨은 의존성만 제공해준다.
 
- DI 컨테이너의 결합성과 테스트의 용이성
DI 프레임워크의 핵심은 관리되는 클래스가 DI 컨테이너에 의존성이 없어야한다.
즉, 필요한 의존성을 전달하면 독립적으로 인스턴스화 할 수 있는 단순 POJO여야한다.
DI 컨테이너 없이 유닛테스트에서 인스턴스화 가능하며, 테스트 가능하다.
컨테이너 결합성이 없다면 관리하거나 관리하지 않는 클래스를 사용할 수 있고, 다른 DI 컨테이너로 전환할 수 있다.
 
- Immutability (불변 객체)
생성자 주입 방식에서 필드는 final로 선언할 수 있다.
하지만, 필드 주입 방식에서는 final로 선언할 수 없어 객체가 변경 가능한 상태가 된다.
 
- 순환 의존성
생성자 주입 방식에서 순환 의존성을 가질 경우 BeanCurrentlyCreationExcepiton을 발생시킴으로써 순환 의존성을 알 수 있다.
1번 클래스가 2번 클래스를 참조하는데, 다시 2번 클래스가 1번 클래스를 참조하는 경우 순환 의존성이라고 부른다.

 

 Spring Constructor 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 ==> 외부에서 문자열을 주입
	
	// 생성자 주입
	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"
	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");
	 -->
</beans>

* 출력 화면 

 

 Spring Constructor 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);
		
		UserService service2 =
				ctx.getBean("service2", UserService.class);
		System.out.println(service2);
		
		UserService service3 =
				ctx.getBean("service3", UserService.class);
		System.out.println(service3);	
	}
}

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;
		
	}
	
	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"
	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="홍길동"></constructor-arg> 
		<!-- 홍길동이 생성자에 의해서 mesg 변수에 저장이 됨 -->
	</bean>

	<bean id="service2" class="com.service.UserService">
		<constructor-arg name="n" value="20"></constructor-arg>
	</bean>
	
	<bean id="service3" class="com.service.UserService">
		<constructor-arg name="m" value="이순신"></constructor-arg>
		<constructor-arg name="n" value="44"></constructor-arg>
	</bean>

</beans>

* 출력 화면

 

 Spring Constructor 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 com.dao.UserDAO;

public class UserService {

	UserDAO dao;
	
	// 생성자 주입
	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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="dao" class="com.dao.UserDAO" />
	<!-- UserDAO dao = new UserDAO(); -->
	<bean id="service" class="com.service.UserService">
		<constructor-arg name="dao" ref="dao" /> <!-- 생성자를 이용하여 주입하면  constructor-arg-->
	</bean>
	<!-- 
		UserService service = new UserService();
	 -->
</beans>

* 출력 화면 :

 

 출처

 

Constructor Injection 방식을 권장하는 이유 : https://n1tjrgns.tistory.com/230

+ 강의 교재

반응형
2022-03-10 15:22:38
반응형

Spring 실습 1일차_Bean Create

 

 Bean Create

Main.java

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

public class Main {
	public static void main(String[] args) {
		
		// IoC 컨테이너 생성 ==> XXXXApplicationContext	
		ApplicationContext ctx = new GenericXmlApplicationContext("user.xml");
		
		// 생성된 빈 접근
		UserService service = ctx.getBean("service", UserService.class);
		System.out.println(service.getMesg());
	}
}

UserDAO.java

package com.dao;

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

public class UserDAO {
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	
	public UserDAO() {
		logger.info("UserDAO 생성자");
	}
}

UserService.java

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

// POJO Class
public class UserService {

	private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	
	public UserService() {
		logger.info("UserService 생성자");
	}
	
	// 메서드 추가
	public String getMesg() {
		return "UserService";
	}
}

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 등록  (/:empty tag) -->
	<bean id="service" class="com.service.UserService" />
	<bean id="dao" class="com.dao.UserDAO"/>
</beans>

 

* Console 출력값 : 

 

Bean Create_Pakage 추가

MainClass.java

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

public class MainClass {

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

UserService.java

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

// POJO Class
public class UserService {

	private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	public UserService() {
		logger.info("UserService 생성자");
	}
	
	// 메서드 추가
	public String getMesg() {
		return "UserService";
	}
}

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 등록  (/:empty tag) -->
	<bean id="service2" class="com.service.UserService" />
</beans>

 

 출처

 

 

+ 강의 교재

반응형