Spring & Springboot/올인원 스프링 프레임워크

학사 관리 시스템 -3

YJ_ma 2023. 9. 14. 00:18

MainClass.java

MainClass.java를 생성하여 main() 메서드에서 GenericXmlApplicationContext와 IoC 컨테이너에 생성된 빈을 이용해본다.

src/main/java > ch04_pgt_01.ems 패키지 생성 > MainClass.java

생성 결과

만약 ch04_pgt_01.ems 패키지 생성 시 오류 발생하면 ?

우클릭 > class 생성 Package 변경 : ch04_pjt_01.ems
Name : MainClass

 

MainClass의 구조는 다음과 같다.

1. applicationContext.xml와 GenericXmlApplicationContext를 이용하여 Ioc 컨테이너를 생성한다.

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

 

2. InitSampleData에 있는 샘플 데이터를 이용해서 데이터베이스에 학생을 등록한다.

// 샘플 데이터
InitSampleData initSampleData = ctx.getBean("initSampleData", InitSampleData.class);
String[] sNums = initSampleData.getsNums();
String[] sIds = initSampleData.getsIds();
String[] sPws = initSampleData.getsPws();
String[] sNames = initSampleData.getsNames();
int[] sAges = initSampleData.getsAges();
char[] sGenders = initSampleData.getsGenders();
String[] sMajors = initSampleData.getsMajors();

// 데이터베이스에 샘플 데이터 등록
StudentRegisterService registerService = ctx.getBean("studentRegisterService", StudentRegisterService.class);
for (int i = 0; i < sNums.length; i++) {
    registerService
    .register(new Student(sNums[i], sIds[i], sPws[i], sNames[i], sAges[i], sGenders[i], sMajors[i]));
}

 

3. PrintStudentInformationService를 이용해서 모든 학생 정보를 출력한다.

2번의 regissterService를 이용해서 학번이 hbs006인 새로운 학생 정보를 등록한다.

// 학생 리스트
PrintStudentInformationService printStudentInformatinService = ctx.getBean("printStudentInformationService",
        PrintStudentInformationService.class);
printStudentInformatinService.printStudentsInfo(); // 학생 리스트

// 학생 등록
registerService = ctx.getBean("studentRegisterService", StudentRegisterService.class);
registerService.register(new Student("hbs006", "deer", "p0006", "melissa", 26, 'w', "Music"));

printStudentInformatinService.printStudentsInfo(); // 학생 리스트

 

4. StudentSelectService를 이용해서 학번이 hbs600인 학생 정보를 조회한다.

// 학생 출력
StudentSelectService selectService = ctx.getBean("studentSelectService", StudentSelectService.class);
Student selectedstudent = selectService.select("hbs006");

System.out.println("STUDENT START ------------------");
System.out.print("sNum:" + selectedstudent.getsNum() + "\t");
System.out.print("|sId:" + selectedstudent.getsId() + "\t");
System.out.print("|sPw:" + selectedstudent.getsPw() + "\t");
System.out.print("|sName:" + selectedstudent.getsName() + "\t");
System.out.print("|sAge:" + selectedstudent.getsAge() + "\t");
System.out.print("|sGender:" + selectedstudent.getsGender() + "\t");
System.out.println("|sMajor:" + selectedstudent.getsMajor());
System.out.println("END ----------------------------");

 

5. StudentModfityService를 이용해서 학번이 hbs006인 학생 정보를 수정한다.

// 학생 수정
StudentModifyService modifyService = ctx.getBean("studentModifyService", StudentModifyService.class);
modifyService.modify(new Student("hbs006", "pig", "p0066", "melissa", 27, 'w', "Computer"));

printStudentInformatinService.printStudentsInfo(); // 학생 리스트

 

6. StudentDeleteService를 이용해서 학번이 hbs005인 학생 정보를 삭제한다.

// 학생 삭제
StudentDeleteService deleteService = ctx.getBean("studentDeleteService", StudentDeleteService.class);
deleteService.delete("hbs005");

printStudentInformatinService.printStudentsInfo(); // 학생 리스트

 

7. EMSInformationService를 이용해서 시스템 정보를 출력한다. 

그리고 GenericXmlApplicationContext를 이용해서 콘텍스트를 닫는다.

// 시스템 정보
EMSInformationService emsInformationService = ctx.getBean("eMSInformationService", EMSInformationService.class);
emsInformationService.printEMSInformation();

 

실행결과

1. 전체 학생 정보 출력

2. hbs006 학생 등록

3. hbs006 학생 조회

4. hbs006 학생 수정

5. hbs005 학생 삭제

6. 프로그램, 관리자, 데이터베이스 정보 출력

실행결과 1
실행결과 2

MainClass.java의 전체 코드는 다음과 같다.

package ch04_pjt_01.ems;

import org.springframework.context.support.GenericXmlApplicationContext;

import ch04_pjt_01.ems.member.Student;
import ch04_pjt_01.ems.member.service.EMSInformationService;
import ch04_pjt_01.ems.member.service.PrintStudentInformationService;
import ch04_pjt_01.ems.member.service.StudentDeleteService;
import ch04_pjt_01.ems.member.service.StudentModifyService;
import ch04_pjt_01.ems.member.service.StudentRegisterService;
import ch04_pjt_01.ems.member.service.StudentSelectService;
import ch04_pjt_01.ems.utils.InitSampleData;

public class MainClass {

	public static void main(String[] args) {
		
		//IoC 컨테이너 생성 
		GenericXmlApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:applicationContext.xml");

		// 샘플 데이터
		InitSampleData initSampleData = ctx.getBean("initSampleData", InitSampleData.class);
		String[] sNums = initSampleData.getsNums();
		String[] sIds = initSampleData.getsIds();
		String[] sPws = initSampleData.getsPws();
		String[] sNames = initSampleData.getsNames();
		int[] sAges = initSampleData.getsAges();
		char[] sGenders = initSampleData.getsGenders();
		String[] sMajors = initSampleData.getsMajors();

		// 데이터베이스에 샘플 데이터 등록
		StudentRegisterService registerService = ctx.getBean("studentRegisterService", StudentRegisterService.class);
		for (int i = 0; i < sNums.length; i++) {
			registerService
			.register(new Student(sNums[i], sIds[i], sPws[i], sNames[i], sAges[i], sGenders[i], sMajors[i]));
		}
		// 학생 리스트
		PrintStudentInformationService printStudentInformatinService = ctx.getBean("printStudentInformationService",
				PrintStudentInformationService.class);
		printStudentInformatinService.printStudentsInfo(); // 학생 리스트

		// 학생 등록
		registerService = ctx.getBean("studentRegisterService", StudentRegisterService.class);
		registerService.register(new Student("hbs006", "deer", "p0006", "melissa", 26, 'w', "Music"));

		printStudentInformatinService.printStudentsInfo(); // 학생 리스트


		// 학생 출력
		StudentSelectService selectService = ctx.getBean("studentSelectService", StudentSelectService.class);
		Student selectedstudent = selectService.select("hbs006");

		System.out.println("STUDENT START ------------------");
		System.out.print("sNum:" + selectedstudent.getsNum() + "\t");
		System.out.print("|sId:" + selectedstudent.getsId() + "\t");
		System.out.print("|sPw:" + selectedstudent.getsPw() + "\t");
		System.out.print("|sName:" + selectedstudent.getsName() + "\t");
		System.out.print("|sAge:" + selectedstudent.getsAge() + "\t");
		System.out.print("|sGender:" + selectedstudent.getsGender() + "\t");
		System.out.println("|sMajor:" + selectedstudent.getsMajor());
		System.out.println("END ----------------------------");

		// 학생 수정
		StudentModifyService modifyService = ctx.getBean("studentModifyService", StudentModifyService.class);
		modifyService.modify(new Student("hbs006", "pig", "p0066", "melissa", 27, 'w', "Computer"));

		printStudentInformatinService.printStudentsInfo(); // 학생 리스트

		// 학생 삭제
		StudentDeleteService deleteService = ctx.getBean("studentDeleteService", StudentDeleteService.class);
		deleteService.delete("hbs005");

		printStudentInformatinService.printStudentsInfo(); // 학생 리스트

		// 시스템 정보
		EMSInformationService emsInformationService = ctx.getBean("eMSInformationService", EMSInformationService.class);
		emsInformationService.printEMSInformation();

		ctx.close();
	}
}

 

스프링 설정 파일 분리

파일 분리 방법 1 : IoC 컨테이너에서 조합하기

applicationContext.xml 파일을 3개 파일로 분리한다.

파일 이름은 appCtx1.xml, appCtx2.xml, appCtx3.xml로 한다.

applicationContext.xml appCtx1.xml appCtx2.xml appCtx3.xml
InitSampleData
Dao
Service
DBConnectionInfo
EMSInformationService
InitSampleData
Dao
Service
DBConnectionInfo EMSInformationService

 

appCtx1.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 
    https://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- InitSampleData 빈 -->
	<bean id="initSampleData"
		class="ch04_pjt_01.ems.utils.InitSampleData">
		<property name="sNums">
			<array>
				<value>hbs001</value>
				<value>hbs002</value>
				<value>hbs003</value>
				<value>hbs004</value>
				<value>hbs005</value>
			</array>
		</property>
		<property name="sIds">
			<array>
				<value>rabbit</value>
				<value>hippo</value>
				<value>raccoon</value>
				<value>elephant</value>
				<value>lion</value>
			</array>
		</property>
		<property name="sPws">
			<array>
				<value>p0001</value>
				<value>p0002</value>
				<value>p0003</value>
				<value>p0004</value>
				<value>p0005</value>
			</array>
		</property>
		<property name="sNames">
			<array>
				<value>agatha</value>
				<value>barbara</value>
				<value>chris</value>
				<value>doris</value>
				<value>elva</value>
			</array>
		</property>
		<property name="sAges">
			<array>
				<value>19</value>
				<value>22</value>
				<value>20</value>
				<value>27</value>
				<value>19</value>
			</array>
		</property>
		<property name="sGenders">
			<array>
				<value>M</value>
				<value>W</value>
				<value>W</value>
				<value>M</value>
				<value>M</value>
			</array>
		</property>
		<property name="sMajors">
			<array>
				<value>English</value>
				<value>Korean</value>
				<value>French</value>
				<value>Philosophy</value>
				<value>History</value>
			</array>
		</property>
	</bean>


	<!-- StudentDao 빈 -->
	<bean id="studentDao"
		class="ch04_pjt_01.ems.member.dao.StudentDao" />

	<!-- StudentRegisterService 빈 생성 -->
	<bean id="studentRegisterService"
		class="ch04_pjt_01.ems.member.service.StudentRegisterService">
		<constructor-arg ref="studentDao" />
	</bean>

	<!-- StudentModifyService 빈 생성 -->
	<bean id="studentModifyService"
		class="ch04_pjt_01.ems.member.service.StudentModifyService">
		<constructor-arg ref="studentDao" />
	</bean>

	<!-- StudentDeleteService 빈 생성 -->
	<bean id="studentDeleteService"
		class="ch04_pjt_01.ems.member.service.StudentDeleteService">
		<constructor-arg ref="studentDao" />
	</bean>

	<!-- StudentSelectService 빈 생성 -->
	<bean id="studentSelectService"
		class="ch04_pjt_01.ems.member.service.StudentSelectService">
		<constructor-arg ref="studentDao" />
	</bean>

	<!-- StudentAllSelectService 빈 생성 -->
	<bean id="studentAllSelectService"
		class="ch04_pjt_01.ems.member.service.StudentAllSelectService">
		<constructor-arg ref="studentDao" />
	</bean>

	<!-- PrintStudentInformationService 빈 생성 -->
	<bean id="printStudentInformationService"
		class="ch04_pjt_01.ems.member.service.PrintStudentInformationService">
		<constructor-arg ref="studentAllSelectService" />
	</bean>

</beans>

 appCtx2.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 
    https://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- DBConnectionInfo 빈 -->
	
	<!-- 개발에 이용하는 데이터베이스 빈 생성 -->
	<bean id="dev_DBConnectionInfoDev"
		class="ch04_pjt_01.ems.member.DBConnectionInfo">
		<property name="url" value="000.000.000.000" />
		<property name="userId" value="admin" />
		<property name="userPw" value="0000" />
	</bean>

	<!-- 실제 서비스에 이용하는 데이터베이스 빈 생성 -->
	<bean id="real_DBConnectionInfo"
		class="ch04_pjt_01.ems.member.DBConnectionInfo">
		<property name="url" value="111.111.111.111" />
		<property name="userId" value="master" />
		<property name="userPw" value="1111" />
	</bean>

</beans>

 

 appCtx3.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 
    https://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- EMSInformationService 빈 -->
	<bean id="eMSInformationService"
		class="ch04_pjt_01.ems.member.service.EMSInformationService">
		<property name="info"
			value="Education Management System program was developed in 2022." />
		<property name="copyRight"
			value="COPYRIGHT(C) 2022 EMS CO., LTD. ALL RIGHT RESERVED. CONTACT MASTER FOR MORE INFORMATION." />
		<property name="ver" value="The version is 1.0" />
		<property name="sYear" value="2022" />
		<property name="sMonth" value="3" />
		<property name="sDay" value="1" />
		<property name="eYear" value="2022" />
		<property name="eMonth" value="4" />
		<property name="eDay" value="30" />
		<property name="developers">
			<list>
				<value>Cheney.</value>
				<value>Eloy.</value>
				<value>Jasper.</value>
				<value>Dillon.</value>
				<value>Kian.</value>
			</list>
		</property>

		<!-- administrators 필드 초기화 -->
		<property name="administrators">
			<map>
				<entry>
					<key>
						<value>Cheney</value>
					</key>
					<value>cheney@springPjt.org</value>
				</entry>
				<entry>
					<key>
						<value>Jasper</value>
					</key>
					<value>jasper@springPjt.org</value>
				</entry>
			</map>
		</property>

		<!-- dbInfos 필드 초기화 -->
		<property name="dbInfos">
			<map>
				<entry>
					<key>
						<value>dev</value>
					</key>
					<ref bean="dev_DBConnectionInfoDev" />	
				</entry>
				<entry>
					<key>
						<value>real</value>
					</key>
					<ref bean="real_DBConnectionInfo" />	
				</entry>
			</map>
		</property>
	</bean>

</beans>

 

스프링 설정 파일을 분리해도 ref 속성에서 다른 파일의 빈을 참조할 수 있다.

파일을 분리해도 모든 빈이 동일한 스프링 컨테이너에 의해 관리되기 때문이다.

Ex, appCtx3.xml에서 appCtx2.xml의 dev_DBConnectionInfoDev, real_DBConnectionInfo 빈 참조가 가능하다.

 

MainClass.java의 main() 메서드를 다음과 같이 수정해준다.

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

		String[] appCtxs = {"classpath:appCtx1.xml", "classpath:appCtx2.xml", "classpath:appCtx3.xml"}; 
		GenericXmlApplicationContext ctx = 
				new GenericXmlApplicationContext(appCtxs);
                
                ....
          
    }
}

 

이제 실행해보면 이전과 동일한 결과(6가지)가 나타나는 것을 알 수 있다.

 

파일 분리 방법 2 : <import> 태그 이용하기

스프링 설정 파일을 분리하는 또 다른 방법은 분리된 설정 파일을 <import> 태그로 연결하는 것이다.

1. appCtx1.xml을 복사해서 appCtxImport.xml을 생성한다.

2. appCtxImport.xml에 appCtx2.xml와 appCtx3.xml을 임포트하는 <import> 태그를 추가해준다.

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

 

3. IoC 컨테이너를 수정하는 부분도 수정하기 위해 MainClass에서 main() 메서드를 다음과 같이 수정한다.

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