Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

Everything has an expiration date

[inflearn] 20240108 [스프링-프레임워크] - 12-2강 필기 본문

[Inflearn]/자바 스프링 프레임워크(renew ver.)

[inflearn] 20240108 [스프링-프레임워크] - 12-2강 필기

Jelly-fish 2024. 1. 10. 05:49

12-2강 - 어노테이션을 이용한 스프링 설정 Ⅱ

XML 을 이용한 스프링 설정파일 제작을 Java 파일로 제작할 수 있는 방법에 대해서 학습한다.

12-2-1 Java 파일 분리
12-2-2 @Import 어노테이션

 

 

12-2-1 Java 파일 분리

 


[applicationContext.xml 을 3개로 분리]

 

.xml 파일
ⓐ 1.xml ⓑ 2.xml ③ 3.xml​


이후, Main.java 클래스에서

`GenericXmlApplicationContext` 를 통해
스프링 컨테이너(IoC)를 생성한다.

방법 ① : 모든 .xml 파일들의 파일명을 문자열 배열로 저장하여 매개변수로 전달.
String[] appCtxs = {"classpath:appCtx1.xml", "classpath:appCtx2.xml", "classpath:appCtx3.xml"};

GenericXmlApplicationContext ctx
 = new GenericXmlApplicationContext(appCtxs);​


방법 ② : 하나의 파일에 다른 분리된 파일들을 import 하여,
               다른 파일들을 import 한 파일 하나만으로 컨테이너 생성.


[다른 분리된 파일들을 import 한 xml 파일 - appCtxImport.xml]
<!-- appCtxImport.xml -->

<import resource="classpath:appCtx2.xml">
<import resource="classpath:appCtx3.xml">

<!-- appCtx1.xml 의 경우에는, 이 파일에 적어 주었다. -->​


[메인 클래스 - MainClass.java]

// MainClass.java

// appCtxImport.xml에서 appCtx2.xml, appCtx3.xml을 모두 import 해 주었으므로
// appCtxImport.xml 파일 하나의 스프링 컨테이너(IoC)만 생성하면 된다!

GenericXmlApplicationContext ctx
= new GenericXmlApplicationContext("classpath:appCtxImport.xml");




[스프링 설정파일을 대체한 .java 파일을 3개로 분리]

.java 파일
ⓐ 1.java 
   : DAO (Data Access Object) - DB 데이터 접근 관련 설정
ⓑ 2.java 
   : Service - 서비스 객체들의 모음
ⓒ 3.java 
   : Util - 프로젝트 전역에서 사용되는 특정 로직이나 독립적인 기능 구현​


이후, Main.java 클래스에서
`AnnotationConfigApplicationContext` 를 통해
스프링 설정파일을 대체한 자바 파일(클래스)을 생성한다.

AnnotationConfigApplicationContext ctx
 = new AnnotationConfigApplicationContext(MemberConfig.class);

 

 

 

MemberConfig1.java (DataBase를 통한 서비스 객체 모음)
package ems.member.configration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import ems.member.dao.StudentDao;
import ems.member.service.StudentAllSelectService;
import ems.member.service.StudentDeleteService;
import ems.member.service.StudentModifyService;
import ems.member.service.StudentRegisterService;
import ems.member.service.StudentSelectService;

@Configuration
public class MemberConfig1 {

	@Bean
	public StudentDao studentDao() {
		return new StudentDao();
	}
	
	@Bean
	public StudentRegisterService registerService() {
		return new StudentRegisterService(studentDao());
	}
	
	@Bean
	public StudentModifyService modifyService() {
		return new StudentModifyService(studentDao());
	}
	
	@Bean
	public StudentSelectService selectService() {
		return new StudentSelectService(studentDao());
	}
	
	@Bean
	public StudentDeleteService deleteService() {
		return new StudentDeleteService(studentDao());
	}
	
	@Bean
	public StudentAllSelectService allSelectService() {
		return new StudentAllSelectService(studentDao());
	}
	
}

MemberConfig2.java (DataBase 연결)

 

package ems.member.configration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import ems.member.DataBaseConnectionInfo;

@Configuration
public class MemberConfig2 {

	@Bean
	public DataBaseConnectionInfo dataBaseConnectionInfoDev() {
		DataBaseConnectionInfo infoDev = new DataBaseConnectionInfo();
		infoDev.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:xe");
		infoDev.setUserId("scott");
		infoDev.setUserPw("tiger");
		
		return infoDev;
	}
	
	@Bean
	public DataBaseConnectionInfo dataBaseConnectionInfoReal() {
		DataBaseConnectionInfo infoReal = new DataBaseConnectionInfo();
		infoReal.setJdbcUrl("jdbc:oracle:thin:@192.168.0.1:1521:xe");
		infoReal.setUserId("masterid");
		infoReal.setUserPw("masterpw");
		
		return infoReal;
	}
	
}

MemberConfig3.java

 

package ems.member.configration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import ems.member.DataBaseConnectionInfo;
import ems.member.service.EMSInformationService;

@Configuration
public class MemberConfig3 {

	
	@Autowired
	DataBaseConnectionInfo dataBaseConnectionInfoDev;
	
	@Autowired
	DataBaseConnectionInfo dataBaseConnectionInfoReal;
	
	@Bean
	public EMSInformationService informationService() {
		EMSInformationService info = new EMSInformationService();
		info.setInfo("Education Management System program was developed in 2015.");
		info.setCopyRight("COPYRIGHT(C) 2015 EMS CO., LTD. ALL RIGHT RESERVED. CONTACT MASTER FOR MORE INFORMATION.");
		info.setVer("The version is 1.0");
		info.setsYear(2015);
		info.setsMonth(1);
		info.setsDay(1);
		info.seteYear(2015);
		info.seteMonth(2);
		info.seteDay(28);
		
		ArrayList<String> developers = new ArrayList<String>();
		developers.add("Cheney.");
		developers.add("Eloy.");
		developers.add("Jasper.");
		developers.add("Dillon.");
		developers.add("Kian.");
		info.setDevelopers(developers);
		
		Map<String, String> administrators = new HashMap<String, String>();
		administrators.put("Cheney", "cheney@springPjt.org");
		administrators.put("Jasper", "jasper@springPjt.org");
		info.setAdministrators(administrators);
		
		Map<String, DataBaseConnectionInfo> dbInfos = new HashMap<String, DataBaseConnectionInfo>();
		dbInfos.put("dev", dataBaseConnectionInfoDev);
		dbInfos.put("real", dataBaseConnectionInfoReal);
		info.setDbInfos(dbInfos);
		
		return info;
	}
	
}

 


위의 코드에서, 다음과 같이 구성한 이유는

 

[MemberConfig3.java]
@Autowired
DataBaseConnectionInfo dataBaseConnectionInfoDev;

@Autowired
DataBaseConnectionInfo dataBaseConnectionInfoReal;

 

MemberConfig2.java 파일에 존재하는

`DataBaseConnectionInfo()` 메소드를 호출해서 `DataBaseConnectionInfo` 라는 객체를 얻기 위함이다.

 

MemberConfig2 파일과, MemberConfig3 파일은 모두

같은 스프링 컨테이너에 담길 것이기 때문에

 

MemberConfig2.java 에서 생성된 빈 객체 `DataBaseConnectionInfo`가

MemberConfig3.java 의 `dataBaseConnectionInfoDev`로 자동 주입이 될 수 있는 것이다.

 

[MemberConfig2.java]
@Bean
public DataBaseConnectionInfo dataBaseConnectionInfoDev()
{	
    DataBaseConnectionInfo infoDev = new DataBaseConnectionInfo();
    infoDev.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:xe");
    infoDev.setUserId("scott");
    infoDev.setUserPw("tiger");
    
    return infoDev;
}

 

↓ (의존객체 자동주입)

 

[MemberConfig3.java]
@Autowired
DataBaseConnectionInfo dataBaseConnectionInfoDev;

@Autowired
DataBaseConnectionInfo dataBaseConnectionInfoReal;

 

MemberConfig3.java에는 `DataBaseConnectionInfo` 객체를 생성해 주는

메소드가 없으므로 (현재 MemberConfig2.java에 분리해 둔 상태)

이를 `@Autowired` 어노테이션을 통해 의존객체 자동주입으로 받아와서

속성변수(프로퍼티)인 `dataBaseConnectionInfoDev`와 `dataBaseConnectionInfoReal`에

저장해 주는 것이다.

 

그리고, 이렇게 자동 주입을 통해 얻어낸 프로퍼티를

MemberConfig3.java의 `informationService()` 메소드에서

`Map` 자료구조 `Value` 값에 넣어주면 된다.

 

[MemberConfig3.java]
@Bean
public EMSInformationService informationService()
{
		
        ...
		
	Map<String, String> administrators = new HashMap<String, String>();
	administrators.put("Cheney", "cheney@springPjt.org");
	administrators.put("Jasper", "jasper@springPjt.org");
	info.setAdministrators(administrators);
		
	Map<String, DataBaseConnectionInfo> dbInfos = new HashMap<String, DataBaseConnectionInfo>();
	dbInfos.put("dev", dataBaseConnectionInfoDev);		//-- check!!!
	dbInfos.put("real", dataBaseConnectionInfoReal);	//-- check!!!
	info.setDbInfos(dbInfos);
		
	return info;
}

 

 


 

위에서 분리한 스프링 설정파일.java
(MemberConfig1.java, MemberConfig2.java, MemberConfig3.java) 를
Main 클래스에서 불러내어 스프링 컨테이너(IoC)를 생성하는 방법.

 

`AnnotationConfigApplicationContext`에 하나씩전부 나열해 주면 된다.

AnnotationConfigApplicationContext ctx
 = new AnnotationConfigApplicationContext
   (MemberConfig1.class, MemberConfig2.class, MemberConfig3.class);


12-2-2 @Import 어노테이션

 

분리된 파일들을 하나씩 명시하지 않고, 하나의 파일에서 분리된 다른 파일들을 import 해 온다면이 파일 하나만 MainClass.java 에서 컨테이너를 생성하더라도같은 결과를 기대할 수 있다.

 

.java

↓

분리

ⓐ 1.java ⓑ 2.java ⓒ 3.java

↓

import

1+2+3.java

 

@Configuration
@import ({MemberConfig2.class, MemberConfig3.class})
public class MemberConfigImport
{
	...
}

 


 

12-2-1 에서 모두 분리한 스프링 설정파일들을(MemberConfig2.java, MemberConfig3.java)

하나의 파일에서 import 처리하여 사용할 수 있다.

 

MemberConfigImport.java
package ems.member.configration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import ems.member.dao.StudentDao;
import ems.member.service.StudentAllSelectService;
import ems.member.service.StudentDeleteService;
import ems.member.service.StudentModifyService;
import ems.member.service.StudentRegisterService;
import ems.member.service.StudentSelectService;


@Configuration
// @import 어노테이션을 통해서, 분리된 다른 파일들을 불러온다.
@Import({MemberConfig2.class, MemberConfig3.class})
public class MemberConfigImport {

	@Bean
	public StudentDao studentDao() {
		return new StudentDao();
	}
	
	@Bean
	public StudentRegisterService registerService() {
		return new StudentRegisterService(studentDao());
	}
	
	@Bean
	public StudentModifyService modifyService() {
		return new StudentModifyService(studentDao());
	}
	
	@Bean
	public StudentSelectService selectService() {
		return new StudentSelectService(studentDao());
	}
	
	@Bean
	public StudentDeleteService deleteService() {
		return new StudentDeleteService(studentDao());
	}
	
	@Bean
	public StudentAllSelectService allSelectService() {
		return new StudentAllSelectService(studentDao());
	}
	
}

 

이렇게 구성된 스프링 설정파일.java를 통해

MainClass 에서 스프링 컨테이너를 생성(초기화)하면 된다.

 

AnnotationConfigApplicationContext ctx 
 = new AnnotationConfigApplicationContext(MemberConfigImport.class);

 

* 실무에서는 @import 를 잘 사용하지 않는다.