지구정복

[Spring] 01/25 | 전자정부프레임워크(개념 및 설치), Spring(속성을 통해서 객체 초기화, HashMap으로 객체생성, HashSet으로 객체생성, Properties 객체사용, 복잡한 클래스의 DI사용, 데이터베이스 연동, .. 본문

데이터 엔지니어링 정복/HTML-CSS-JavaScript-Spring-Node.js

[Spring] 01/25 | 전자정부프레임워크(개념 및 설치), Spring(속성을 통해서 객체 초기화, HashMap으로 객체생성, HashSet으로 객체생성, Properties 객체사용, 복잡한 클래스의 DI사용, 데이터베이스 연동, ..

eeaarrtthh 2021. 1. 25. 17:49
728x90
반응형

1. 전자정부프레임워크

더보기

1. 개념 및 설치

개발프레임워크는 정보시스템 개발을 위해 필요한 기능 및 아키텍처를 미리 만들어 제공함으로써 효율적인 어플리케이션 구축을 지원한다.

주로 정부 및 공공기관, 공기업 등의 웹사이트에 자주 쓰이는 공통 기능들을 Java의 Spring 프레임워크와 유명 Java 라이브러리 (iBatis/MyBatis 등)를 가지고 미리 만들어 놓은 공통 컴포넌트와 이를 개발하는 개발환경, 실행환경, 운영환경, 관리환경 등으로 구성되어 있다.

 

사용하는 이유는 Spring은 확장성이 뛰어나며 Java로 이루어져 있다. 그런데 이러한 뛰어난 범용성과 확장성만큼 플러그인들끼리 충돌로 인한 오동작이 있을 수 있기에 이를 위해서 한가지 형태로 통합해서 배포하는 것이다.

즉, 정부기관에서 관리하는 검증된 오픈 소스로 구성된 무료 프레임워크이다.

따라서 전자정부프레임워크를 다운로드받으면 그 안에는 Java와 Spring사용을 위한 각종 라이브리와 테스트, 배포, 외부라이브러리 관리에 필요한 설정이 되어있는 이클립스가 다운로드된다.

 

 

설치방법은 아래와 같다.

www.egovframe.go.kr/

 

eGovFrame Portal 온라인 지원 포탈

묻고 답하기 더보기 자주하는 질문 더보기 공지사항 더보기

www.egovframe.go.kr

위 사이트에서 다운로드 - 개발환경 - 3.x 다운로드에서 아래와 같이 선택하고 다운로드 한다.

3.10.0 beta버전도 다운로드 한다.

다운로드된 것 중에서 3.9~.exe를 압축을 풀면 아래와 같은 폴더가 나온다.

이클립스 폴더에서 이클립스를 실행해준다.

 아래와 같이 워크스페이스를 아까 압축을 푼 워크스페이스로 설정을한다.

Perspective를 Spring으로 바꿔준다.

 그리고 먼저 Maven 프로젝트를 만든다.

그리고 기존에 쓰던 pom.xml의 내용을 복사해서 붙여넣는다.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	
	<groupId>com.exam</groupId>
	<artifactId>spring1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	
	<name>spring1</name>
	<url>http://maven.apache.org</url>
	
	<properties>
	
		<!-- Generic properties -->
		<java.version>1.8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	
		<!-- Spring -->
		<spring-framework.version>5.2.8.RELEASE</spring-framework.version>
	
		<!-- Hibernate / JPA -->
		<hibernate.version>4.2.1.Final</hibernate.version>
	
		<!-- Logging -->
		<logback.version>1.0.13</logback.version>
		<slf4j.version>1.7.5</slf4j.version>
	
		<!-- Test -->
		<junit.version>4.11</junit.version>
	</properties>

	<dependencies>
		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

		<!-- Logging with SLF4J & LogBack -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- Test Artifacts -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-framework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

	</dependencies>
</project>

그러면 예전처럼 이클립스 plug-in에서 spring sts를 다운로드 하지 않아도 된다.

그리고 아래처럼 Spring 프로젝트를 만든다.

 

 

2. Spring

더보기

1. 속성을 통해서 객체 초기화하기

패키지 새로 만들고 BoardTO.java를 아래와 같이 작성한다.

BoardTO에서 setter를 설정해놓으면 bean configuration 파일에서 객체필드 초기화작업을 할 수 있다.

package com.exam.spring5;

public class BoardTO {
	private int seq;
	private String subject;
	
	public BoardTO() {
		System.out.println( "BoardTO() 생성자 호출" );
	}
	public int getSeq() {
		return seq;
	}
	public String getSubject() {
		return subject;
	}
	
	public void setSeq(int seq) {
		this.seq = seq;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
}

그리고 spring configuration파일인 context를 아래와 같은 설정으로 만든다. beands와 p를 선택한다.

 아래와 같이 작성한다.

-context.xml

p 속성값에 boardTO 필드값의 초기값을 주고 객체를 생성하게 한다.

<?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="to" class="com.exam.spring5.BoardTO" p:seq="1" p:subject="제목" />

</beans>

 -App.java (실행클래스)

package com.exam.spring5;

import org.springframework.context.support.GenericXmlApplicationContext;

public class App {

	public static void main(String[] args) {
		GenericXmlApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/exam/spring5/context.xml");
		
		BoardTO to = (BoardTO)ctx.getBean( "to" );
		System.out.println( to.getSeq() );
		System.out.println( to.getSubject() );
		
		ctx.close();
	}
}

 

 

새로운 패키지를 만들고 BoardTO.java와 BoardListTO.java를 만든다.

-BoardTO.java

package com.exam.spring6;

public class BoardTO {
	private int seq;
	private String subject;
	
	public BoardTO() {
		System.out.println( "BoardTO() 생성자 호출" );
	}
	public int getSeq() {
		return seq;
	}
	public String getSubject() {
		return subject;
	}
	
	public void setSeq(int seq) {
		this.seq = seq;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
}

-BoardListTO.java

package com.exam.spring6;

import java.util.ArrayList;

public class BoardListTO {
	private ArrayList<String> userLists;
	private ArrayList<BoardTO> boardLists;
	
	public ArrayList<String> getUserLists() {
		return userLists;
	}
	public ArrayList<BoardTO> getBoardLists() {
		return boardLists;
	}
	
	public void setUserLists(ArrayList<String> userLists) {
		this.userLists = userLists;
	}
	public void setBoardLists(ArrayList<BoardTO> boardLists) {
		this.boardLists = boardLists;
	}
}

-context.xml (spring bean configuration file)

<?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-4.3.xsd">

	<bean id="listTO" class="com.exam.spring6.BoardListTO" scope="prototype">
		<property name="userLists">
			<list>
				<value>홍길동</value>
				<value>박문수</value>
			</list>
		</property>
	</bean>

</beans>

-AppEx02.java (실행클래스)

package com.exam.spring6;

import org.springframework.context.support.GenericXmlApplicationContext;

public class AppEx02 {

	public static void main(String[] args) {
		GenericXmlApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/exam/spring6/context.xml");
		BoardListTO listTO = (BoardListTO)ctx.getBean("listTO");
		
		for( String user : listTO.getUserLists() ) {
			System.out.println( user );
		}
		
		ctx.close();

	}

}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
10:43:14.980 [main] DEBUG o.s.b.f.xml.XmlBeanDefinitionReader - Loaded 1 bean definitions from class path resource [com/exam/spring6/context.xml]
10:43:14.983 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@704d6e83
홍길동
박문수
10:43:15.093 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Closing org.springframework.context.support.GenericXmlApplicationContext@704d6e83, started on Mon Jan 25 10:43:14 KST 2021

 

 이번에는 BoardListTO를 통해서 BoardTO의 필드값을 출력해보자.

-BoardTO.java

package com.exam.spring6;

public class BoardTO {
	private int seq;
	private String subject;
	
	public BoardTO() {
		System.out.println( "BoardTO() 생성자 호출" );
	}
	public int getSeq() {
		return seq;
	}
	public String getSubject() {
		return subject;
	}
	
	public void setSeq(int seq) {
		this.seq = seq;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
}

-BoardListTO.java

package com.exam.spring6;

import java.util.ArrayList;

public class BoardListTO {
	private ArrayList<String> userLists;
	private ArrayList<BoardTO> boardLists;
	
	public ArrayList<String> getUserLists() {
		return userLists;
	}
	public ArrayList<BoardTO> getBoardLists() {
		return boardLists;
	}
	
	public void setUserLists(ArrayList<String> userLists) {
		this.userLists = userLists;
	}
	public void setBoardLists(ArrayList<BoardTO> boardLists) {
		this.boardLists = boardLists;
	}
}

-context.xml (spring bean configuration file)

<?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-4.3.xsd">

	<bean id="listTO" class="com.exam.spring6.BoardListTO" scope="prototype">
		<property name="userLists">
			<list>
				<value>홍길동</value>
				<value>박문수</value>
			</list>
		</property>
		
            <property name="boardLists">
			<list>
				<bean class="com.exam.spring6.BoardTO">
					<property name="seq" value="1" />
					<property name="subject" value="제목1" />
				</bean>
				<bean class="com.exam.spring6.BoardTO">
					<property name="seq" value="2" />
					<property name="subject" value="제목2" />
				</bean>
			</list>
		</property> 
	</bean>
</beans>

-AppEx02.java (실행클래스)

package com.exam.spring6;

import org.springframework.context.support.GenericXmlApplicationContext;

public class AppEx02 {

	public static void main(String[] args) {
		GenericXmlApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/exam/spring6/context.xml");
		BoardListTO listTO = (BoardListTO)ctx.getBean("listTO");
		
		for( String user : listTO.getUserLists() ) {
			System.out.println( user );
		}
		
		for( BoardTO to : listTO.getBoardLists() ) {
			System.out.println( to.getSeq() );
			System.out.println( to.getSubject() );
		}
		
		ctx.close();

	}
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
10:53:39.005 [main] DEBUG o.s.b.f.xml.XmlBeanDefinitionReader - Loaded 1 bean definitions from class path resource [com/exam/spring6/context.xml]
10:53:39.008 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@704d6e83
BoardTO() 생성자 호출
BoardTO() 생성자 호출
홍길동
박문수
1
제목1
2
제목2
10:53:39.136 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Closing org.springframework.context.support.GenericXmlApplicationContext@704d6e83, started on Mon Jan 25 10:53:39 KST 2021

또는 context.xml을 아래와 같이 사용할 수 있다.

미리 to 초기화값을 설정한 bean을 만들고 이를 참조해서 사용한다.

-context.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-4.3.xsd">

	<!-- to를 미리 만들어놓고 다른 곳에서 사용하기  -->
	<bean id="to1" class="com.exam.spring6.BoardTO" scope="prototype">
		<property name="seq" value="1" />
		<property name="subject" value="제목1" />
	</bean>
	
	<bean id="to2" class="com.exam.spring6.BoardTO" scope="prototype">
		<property name="seq" value="2" />
		<property name="subject" value="제목2" />
	</bean>

	<bean id="listTO" class="com.exam.spring6.BoardListTO" scope="prototype">
		<property name="userLists">
			<list>
				<value>홍길동</value>
				<value>박문수</value>
			</list>
		</property>

		<property name="boardLists">
			<list>
				<!--
				<bean class="com.exam.spring6.BoardTO">
					<property name="seq" value="1" />
					<property name="subject" value="제목1" />
				</bean>
				<bean class="com.exam.spring6.BoardTO">
					<property name="seq" value="2" />
					<property name="subject" value="제목2" />
				</bean>
				-->
				
				<!-- 미리 만들어놓은 to를 참조해서 객체초기화하기  -->
				<ref bean="to1" />
				<ref bean="to2" />
			</list>
		</property> 

		

	</bean>
	

</beans>

 

2. HashMap 이용하기

-BoardTO.java

package com.exam.spring6;

public class BoardTO {
	private int seq;
	private String subject;
	
	public BoardTO() {
		System.out.println( "BoardTO() 생성자 호출" );
	}
	public int getSeq() {
		return seq;
	}
	public String getSubject() {
		return subject;
	}
	
	public void setSeq(int seq) {
		this.seq = seq;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
}

-BoardListTO.java

package com.exam.spring7;

import java.util.HashMap;

public class BoardListTO {
	private HashMap<String, BoardTO> boardMaps;

	public HashMap<String, BoardTO> getBoardMaps() {
		return boardMaps;
	}
	
	public void setBoardMaps(HashMap<String, BoardTO> boardMaps) {
		this.boardMaps = boardMaps;
	}
}

-context.xml (spring bean configuration file)

<?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-4.3.xsd">

	<bean id="to1" class="com.exam.spring7.BoardTO" scope="prototype">
		<property name="seq" value="1" />
		<property name="subject" value="제목1" />
	</bean>
	<bean id="to2" class="com.exam.spring7.BoardTO" scope="prototype">
		<property name="seq" value="2" />
		<property name="subject" value="제목2" />
	</bean>

	<bean id="listTO" class="com.exam.spring7.BoardListTO">
		<property name="boardMaps">
			<map>
				<entry key="to1">
					<ref bean="to1"/>
				</entry>
				<entry key="to2">
					<ref bean="to2"/>
				</entry>
			</map>
		</property>
	</bean>

</beans>

-AppEx02.java (실행클래스)

package com.exam.spring7;

import org.springframework.context.support.GenericXmlApplicationContext;

public class AppEx02 {

	public static void main(String[] args) {
		GenericXmlApplicationContext ctx =
				new GenericXmlApplicationContext("classpath:com/exam/spring7/context.xml");
		BoardListTO listTO = (BoardListTO)ctx.getBean("listTO");
		
		for( BoardTO to : listTO.getBoardMaps().values() ) {
			System.out.println( to.getSeq() );
			System.out.println( to.getSubject() );
		}
		
		
	}
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
11:39:03.054 [main] DEBUG o.s.b.f.xml.XmlBeanDefinitionReader - Loaded 3 bean definitions from class path resource [com/exam/spring7/context.xml]
11:39:03.057 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@704d6e83
11:39:03.086 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'listTO'
BoardTO() 생성자 호출
BoardTO() 생성자 호출
1
제목1
2
제목2

 

3. HashSet으로 이용하기

-BoardTO.java

package com.exam.spring6;

public class BoardTO {
	private int seq;
	private String subject;
	
	public BoardTO() {
		System.out.println( "BoardTO() 생성자 호출" );
	}
	public int getSeq() {
		return seq;
	}
	public String getSubject() {
		return subject;
	}
	
	public void setSeq(int seq) {
		this.seq = seq;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
}

-BoardListTO.java

package com.exam.spring7;

import java.util.HashMap;
import java.util.HashSet;

public class BoardListTO {
	private HashMap<String, BoardTO> boardMaps;
	private HashSet<BoardTO> boardSets;

	public HashMap<String, BoardTO> getBoardMaps() {
		return boardMaps;
	}
	public void setBoardMaps(HashMap<String, BoardTO> boardMaps) {
		this.boardMaps = boardMaps;
	}

	public HashSet<BoardTO> getBoardSets() {
		return boardSets;
	}
	public void setBoardSets(HashSet<BoardTO> boardSets) {
		this.boardSets = boardSets;
	}
	
}

-context.xml (spring bean configuration file)

<?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-4.3.xsd">

	<bean id="to1" class="com.exam.spring7.BoardTO" scope="prototype">
		<property name="seq" value="1" />
		<property name="subject" value="제목1" />
	</bean>
	<bean id="to2" class="com.exam.spring7.BoardTO" scope="prototype">
		<property name="seq" value="2" />
		<property name="subject" value="제목2" />
	</bean>

	<bean id="listTO" class="com.exam.spring7.BoardListTO">
		<property name="boardMaps">
			<map>
				<entry key="to1">
					<ref bean="to1"/>
				</entry>
				<entry key="to2">
					<ref bean="to2"/>
				</entry>
			</map>
		</property>
		<property name="boardSets">
			<set>
				<ref bean="to1"/>
				<ref bean="to2"/>
			</set>
		</property>
	</bean>

</beans>

-AppEx02.java (실행클래스)

package com.exam.spring7;

import java.util.HashSet;

import org.springframework.context.support.GenericXmlApplicationContext;

public class AppEx04 {

	public static void main(String[] args) {
		GenericXmlApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/exam/spring7/context.xml");
		
		BoardListTO listTO = (BoardListTO)ctx.getBean("listTO");
		for( BoardTO to : listTO.getBoardSets() ) {
			System.out.println( to.getSeq() );
			System.out.println( to.getSubject() );
		}
		
	}
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
11:39:03.054 [main] DEBUG o.s.b.f.xml.XmlBeanDefinitionReader - Loaded 3 bean definitions from class path resource [com/exam/spring7/context.xml]
11:39:03.057 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@704d6e83
11:39:03.086 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'listTO'
BoardTO() 생성자 호출
BoardTO() 생성자 호출
1
제목1
2
제목2

 

4. Properties 객체 사용

-BookClient.java

package com.exam.spring8;

import java.util.Properties;

public class BookClient {
	private Properties configs;

	public Properties getConfigs() {
		return configs;
	}
	public void setConfigs(Properties configs) {
		this.configs = configs;
	}
	
}

-AppEx01.java

package com.exam.spring8;

import java.util.Properties;

public class AppEx01 {

	public static void main(String[] args) {
		//properties란 객체는 프로그램 환경설정에 대한 내용을 저장하는 것이다.
		Properties config = new Properties();
		config.put("server", "127.0.0.1");
		config.put("connectionTimeout", "5000");
		
		BookClient client = new BookClient();
		client.setConfigs(config);
		
		//저장된 환경설정값을 출력하기
		Properties newConfig = client.getConfigs();
		System.out.println( newConfig.getProperty("server") );
		System.out.println( newConfig.getProperty("connectionTimeout") );
	}

}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
127.0.0.1
5000

 

이를 DI 기법으로 만들어보자.

-context.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-4.3.xsd">

	<bean id="client" class="com.exam.spring8.BookClient" scope="prototype">
		<property name="configs">
			<props>
				<prop key="server">127.0.0.1</prop>
				<prop key="connectionTimeout">5000</prop>
			</props>
		</property>
	</bean>

</beans>

 -AppEx02.java

package com.exam.spring8;

import java.util.Properties;

import org.springframework.context.support.GenericXmlApplicationContext;

public class AppEx02 {

	public static void main(String[] args) {
		GenericXmlApplicationContext ctx = 
				new GenericXmlApplicationContext("classpath:com/exam/spring8/context.xml");
		
		BookClient client = (BookClient)ctx.getBean( "client" );
		Properties config = client.getConfigs();
		
		System.out.println( config.getProperty("server") );
		System.out.println( config.getProperty("connectionTimeout") );
		
		ctx.close();
	}

}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
12:24:35.845 [main] DEBUG o.s.b.f.xml.XmlBeanDefinitionReader - Loaded 1 bean definitions from class path resource [com/exam/spring8/context.xml]
12:24:35.848 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@704d6e83
127.0.0.1
5000
12:24:35.970 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Closing org.springframework.context.support.GenericXmlApplicationContext@704d6e83, started on Mon Jan 25 12:24:35 KST 2021

 

5. 복잡한 클래스가 있을 때 DI 사용의 효율성

메이븐 프로젝트를 다시 만들고 아래와 같이 코딩한다.

-pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	
	<groupId>com.exam</groupId>
	<artifactId>spring3</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	
	<name>spring3</name>
	<url>http://maven.apache.org</url>
	
	<properties>
	
		<!-- Generic properties -->
		<java.version>1.8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	
		<!-- Spring -->
		<spring-framework.version>5.2.8.RELEASE</spring-framework.version>
	
		<!-- Hibernate / JPA -->
		<hibernate.version>4.2.1.Final</hibernate.version>
	
		<!-- Logging -->
		<logback.version>1.0.13</logback.version>
		<slf4j.version>1.7.5</slf4j.version>
	
		<!-- Test -->
		<junit.version>4.11</junit.version>
	</properties>

	<dependencies>
		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

		<!-- Logging with SLF4J & LogBack -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- Test Artifacts -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-framework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

	</dependencies>
</project>

-Article.java

package com.exam.spring4;

public class Article {
	public Article() {
		System.out.println( "Article 생성자 호출" );
	}
}

-ArticleDAO.java(인터페이스)

package com.exam.spring4;

public interface ArticleDAO {
	public abstract void insert( Article article );
}

-DatabaseArticleDAO.java

package com.exam.spring4;

public class DatabaseArticleDAO implements ArticleDAO {

	@Override
	public void insert(Article article) {
		System.out.println( "DatabaseArticleDAO insert() 호출" );

	}
}

-WriteAricleService.java(인터페이스)

package com.exam.spring4;

public interface WriteArticleService {
	public abstract void write( Article article );
}

-WriteArticleServiceImpl.java

package com.exam.spring4;

public class WriteArticleServiceImpl implements WriteArticleService {
	private ArticleDAO articleDAO;
	
	public WriteArticleServiceImpl( ArticleDAO articleDAO ) {
		System.out.println( "WriteArticleService 생성자호출");
		this.articleDAO = articleDAO;
	}
	
	@Override
	public void write(Article article) {
		System.out.println( "write() 호출" );
		articleDAO.insert(article);
	}
}

-context.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-4.3.xsd">

	<bean id="article" class="com.exam.spring4.Article" />
	
	<bean id="articleDAO" class="com.exam.spring4.DatabaseArticleDAO" />
	
	<bean id="writeArticleServiceImpl" class="com.exam.spring4.WriteArticleServiceImpl">
		<constructor-arg>
			<ref bean="articleDAO" />
		</constructor-arg>
	</bean>

</beans>

-App.java(실행클래스)

package com.exam.spring4;

import org.springframework.context.support.GenericXmlApplicationContext;

public class App {
    public static void main( String[] args ) {
    	GenericXmlApplicationContext ctx = 
				new GenericXmlApplicationContext( "classpath:com/exam/spring4/context.xml");
		
    	Article article = (Article)ctx.getBean("article");
    	
		WriteArticleService writeArticleService = 
				(WriteArticleService)ctx.getBean( "writeArticleServiceImpl");
		writeArticleService.write( article );
		
		ctx.close();
    }
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
14:34:21.414 [main] DEBUG o.s.b.f.xml.XmlBeanDefinitionReader - Loaded 2 bean definitions from class path resource [com/exam/spring4/context.xml]
14:34:21.417 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@704d6e83
14:34:21.451 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'articleDAO'
14:34:21.468 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'writeArticleServiceImpl'
WriteArticleService 생성자호출
Article 생성자 호출
write() 호출
DatabaseArticleDAO insert() 호출
14:34:21.518 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Closing org.springframework.context.support.GenericXmlApplicationContext@704d6e83, started on Mon Jan 25 14:34:21 KST 2021

 

위 코드를 자바코드로 사용하면 아래와 같다.

-AppEx02.java

package com.exam.spring4;

public class AppEx02 {

	public static void main(String[] args) {
		Article article = new Article();
		
		DatabaseArticleDAO articleDAO = new DatabaseArticleDAO();
		
		WriteArticleServiceImpl writeArticleServiceImpl =
				new WriteArticleServiceImpl(articleDAO);
		
		writeArticleServiceImpl.write(article);
	}
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
Article 생성자 호출
WriteArticleServiceImpl 생성자호출
write() 호출
DatabaseArticleDAO insert() 호출

 

 6. 데이터베이스에서 데이터 가져오기

마리아디비 라이브러리를 pom에 추가한다. 그리고 dept 테이블을 조회해본다.

-pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	
	<groupId>com.exam</groupId>
	<artifactId>spring3</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	
	<name>spring3</name>
	<url>http://maven.apache.org</url>
	
	<properties>
	
		<!-- Generic properties -->
		<java.version>1.8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	
		<!-- Spring -->
		<spring-framework.version>5.2.8.RELEASE</spring-framework.version>
	
		<!-- Hibernate / JPA -->
		<hibernate.version>4.2.1.Final</hibernate.version>
	
		<!-- Logging -->
		<logback.version>1.0.13</logback.version>
		<slf4j.version>1.7.5</slf4j.version>
	
		<!-- Test -->
		<junit.version>4.11</junit.version>
	</properties>

	<dependencies>
		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

		<!-- Logging with SLF4J & LogBack -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- Test Artifacts -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-framework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
		<dependency>
			<groupId>org.mariadb.jdbc</groupId>
			<artifactId>mariadb-java-client</artifactId>
			<version>2.7.1</version>
		</dependency>
		

	</dependencies>
</project>

 -BoardAction.java(인터페이스)

package com.exam.spring4;

public interface BoardAction {
	public abstract void write( BoardTO to );
}

-BoardTO.java

package com.exam.spring4;

public class BoardTO {
	public BoardTO() {
		System.out.println( "BoardTO 생성자 호출" );
	}
}

-BoardDAO.java(인터페이스)

package com.exam.spring4;

public interface BoardDAO {
	public abstract void insert( BoardTO to );
	public void list( BoardTO to );
}

 -MariadbBoardDAO.java

package com.exam.spring4;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MariadbBoardDAO implements BoardDAO{
	
	public void insert(BoardTO to) {
	}
	
	public void list( BoardTO to ) {
		System.out.println( "MariadbBoardDAO list() 호출" );
		
		String url = "jdbc:mysql://localhost:3307/sample";
		String user = "root";
		String password = "!123456";
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			Class.forName("org.mariadb.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			
			String sql = "select deptno, dname, loc from dept";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			while( rs.next() ) {
				System.out.println( rs.getString( "deptno" ) );
			}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(rs!=null) try {rs.close();} catch(SQLException e) {} 
			if(conn!=null) try {conn.close();} catch(SQLException e) {} 
			if(pstmt!=null) try {pstmt.close();} catch(SQLException e) {} 
		}
		
	}
}

 -ListAction.java

package com.exam.spring4;

public class ListAction implements BoardAction {
	private BoardDAO dao;
	
	public ListAction( BoardDAO dao ) {
		this.dao = dao;
	}

	public void write(BoardTO to) {
		dao.list(to);
	}
}

 -context.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-4.3.xsd">

	<bean id="to" class="com.exam.spring4.BoardTO" />
	
	<!-- 데이터베이스를 중간에 교환해서 사용할 수 있다.  -->
	<!-- <bean id="articleDAO" class="com.exam.spring4.DatabaseBoardDAO" /> -->
	<bean id="dao" class="com.exam.spring4.MariadbBoardDAO" />
	
	<bean id="action" class="com.exam.spring4.ListAction">
	<!-- <bean id="action" class="com.exam.spring4.InsertAction"> -->
		<constructor-arg>
			<ref bean="dao" />
		</constructor-arg>
	</bean>

</beans>

 -App.java (실행클래스)

package com.exam.spring4;

import org.springframework.context.support.GenericXmlApplicationContext;

public class App {
    public static void main( String[] args ) {
    	GenericXmlApplicationContext ctx = 
				new GenericXmlApplicationContext( "classpath:com/exam/spring4/context.xml");
		
    	BoardTO to = (BoardTO)ctx.getBean("to");
    	
		BoardAction action = 
				(BoardAction)ctx.getBean( "action" );
		action.write( to );
		
		ctx.close();
    }
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
15:41:55.327 [main] DEBUG o.s.b.f.xml.XmlBeanDefinitionReader - Loaded 3 bean definitions from class path resource [com/exam/spring4/context.xml]
15:41:55.330 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@eb21112
15:41:55.365 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'to'
BoardTO 생성자 호출
15:41:55.380 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'dao'
15:41:55.381 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'action'
MariadbBoardDAO list() 호출
10
20
30
40
50
60
15:41:55.618 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Closing org.springframework.context.support.GenericXmlApplicationContext@eb21112, started on Mon Jan 25 15:41:55 KST 2021

 

실행순서를 정리하면 다음과 같다.

  1. App.java에서 ctx를 먼저 만들고 BoardTO to를 "to" Bean을 이용해 만든다.
  2. context.xml에서 to 생성자를 만든다.
  3. App.java에서 BoardAction action을 "action" Bean을 이용해 만든다.
  4. context.xml에서 "action" Bean은 ListAction클래스로 만들어지는데 이때 생성자의 매개변수값은 MariadbBoardDAO이다.
  5. ListAction.java에서 ListAction이 생성될 때 BoardDAO dao타입의 MariadbBoardDAO가 같이 만들어진다.
  6. MariadbBoardDAO.java는 BoardDAO 인터페이스를 구현하기 때문에 2개의 메서드인 insert와 list를 메소드 재정의를 한다. list메서드는 데이터베이스와 연동해서 dept테이블의 deptno을 출력하는 기능을 가지고 있다.
  7. 다시 App.java로 돌아와서 이렇게 만들어진 BoardAction 타입의 action을 이용해서 write메서드를 실행해주고 매개변수값은 to이다. 여기서 action은 ListAction.java 객체이므로 LIstAction의 wirte메서드가 실행된다.
  8. ListAction의 write메서드는 MariadbBoardDAO dao의 list메서드를 실행시키고 매개변수값은 App.java에서 받아온 to이다.
  9. MariadbBoardDAO의 list메서드가 실행되면서 데이터베이스와 연동되고 deptno가 출력되면서 프로그램이 종료된다.

 

 

7. 어노테이션기법 사용하기

앞서까지 사용한 context.xml대신 자바클래스의 어노테이션을 이용할 수 있다.

-pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	
	<groupId>com.exam</groupId>
	<artifactId>spring5</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	
	<name>spring5</name>
	<url>http://maven.apache.org</url>
	
	<properties>
	
		<!-- Generic properties -->
		<java.version>1.8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	
		<!-- Spring -->
		<spring-framework.version>5.2.8.RELEASE</spring-framework.version>
	
		<!-- Hibernate / JPA -->
		<hibernate.version>4.2.1.Final</hibernate.version>
	
		<!-- Logging -->
		<logback.version>1.0.13</logback.version>
		<slf4j.version>1.7.5</slf4j.version>
	
		<!-- Test -->
		<junit.version>4.11</junit.version>
	</properties>

	<dependencies>
		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

		<!-- Logging with SLF4J & LogBack -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- Test Artifacts -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-framework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
		<dependency>
			<groupId>org.mariadb.jdbc</groupId>
			<artifactId>mariadb-java-client</artifactId>
			<version>2.7.1</version>
		</dependency>
		

	</dependencies>
</project>

 -HelloBean.java

package com.exam.spring5;

public class HelloBean {

	public HelloBean() {
		System.out.println( "HelloBean 생성자" );
	}
	
	public void sayHello( String name ) {
		System.out.println( name + " 님 안녕하세요" );
	}
}

-BeanConfig.java(context.xml대체)

package com.exam.spring5;

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

@Configuration
@Scope( "prototype" )
public class BeanConfig {
	//xml을 대체하는 환경설정용 java파일
	
	@Bean
	public HelloBean helloBean() {
		return new HelloBean();
	}
}

-App.java (실행클래스)

package com.exam.spring5;

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

public class App {
    public static void main( String[] args ) {
        AnnotationConfigApplicationContext ctx = 
        		new AnnotationConfigApplicationContext( BeanConfig.class );
        
        //getBean의 이름은 메소드 이름이다.
        HelloBean helloBean = (HelloBean)ctx.getBean("helloBean");
        helloBean.sayHello( "홍길동" );
        
        ctx.close();
    }
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
16:17:11.593 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@706a04ae
16:17:11.616 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
16:17:11.742 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
16:17:11.744 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
16:17:11.746 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
16:17:11.754 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'helloBean'
HelloBean 생성자
홍길동 님 안녕하세요
16:17:11.793 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@706a04ae, started on Mon Jan 25 16:17:11 KST 2021

 

 

BeanConfig.java에서 Bean의 이름은 메소드의 이름이지만 이를 설정할 수 있다.

-BeanConfig.java

package com.exam.spring5;

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

@Configuration
@Scope( "prototype" )
public class BeanConfig {
	//xml을 대체하는 환경설정용 java파일
	
	@Bean
	public HelloBean helloBean() {
		return new HelloBean();
	}
	
	@Bean(name = "hello")
	public HelloBean helloBean1() {
		return new HelloBean();
	}
}

 -App.java

package com.exam.spring5;

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

public class App {
    public static void main( String[] args ) {
        AnnotationConfigApplicationContext ctx = 
        		new AnnotationConfigApplicationContext( BeanConfig.class );
        
        //getBean의 이름은 메소드 이름이다.
        HelloBean helloBean = (HelloBean)ctx.getBean("hello");
        helloBean.sayHello( "홍길동" );
        
        ctx.close();
    }
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
16:24:23.261 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@706a04ae
16:24:23.284 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
16:24:23.420 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
16:24:23.422 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
16:24:23.424 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
16:24:23.430 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'helloBean'
HelloBean 생성자
16:24:23.447 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'hello'
HelloBean 생성자
홍길동 님 안녕하세요
16:24:23.469 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@706a04ae, started on Mon Jan 25 16:24:23 KST 2021

 

다음은 먼저 새로운 패키지를 아래와 같이 각 클래스의 용도별로 패키지를 나눠서 작성한다.

 

-HelloBean.java

package com.exam.spring6.beans;

public class HelloBean {
	private String name;
	
	//생성자 주입
	public HelloBean() {
		System.out.println( "HelloBean 생성자 호출" );
	}
	
	public HelloBean( String name ) {
		System.out.println( "HelloBean(String name) 생성자 호출" );
		this.name = name;
	}
	
	public void sayHello() {
		System.out.println( name + " 님 안녕하세요" );
	}
	
}

-BeanConfig.java

package com.exam.spring6.config;

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

import com.exam.spring6.beans.HelloBean;

@Configuration
@Scope("prototype")
public class BeanConfig {
	
	@Bean
	public HelloBean helloBean1() {
		return new HelloBean();
	}
	
	//생성자를 통한 데이터 주입 (생성자 주입)
	@Bean
	public HelloBean helloBean2() {
		return new HelloBean("홍길동");
	}
}

-App.java (실행클래스)

package com.exam.spring6;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.exam.spring6.beans.HelloBean;
import com.exam.spring6.config.BeanConfig;

public class App {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx =
				new AnnotationConfigApplicationContext( BeanConfig.class );
		
		HelloBean helloBean1 = (HelloBean)ctx.getBean( "helloBean1" );
		HelloBean helloBean2 = (HelloBean)ctx.getBean( "helloBean2" );
		helloBean1.sayHello();
		helloBean2.sayHello();
	}

}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
16:40:34.999 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@706a04ae
16:40:35.022 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
16:40:35.153 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
16:40:35.156 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
16:40:35.157 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
16:40:35.163 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'helloBean1'
HelloBean 생성자 호출
16:40:35.180 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'helloBean2'
HelloBean(String name) 생성자 호출
null 님 안녕하세요

 

 프로퍼티를 이용한 생성자 주입

-BoardTO.java (com.exam.spring6.beans 패키지 안)

package com.exam.spring6.beans;

public class BoardTO {
	private int seq;
	private String subject;
	
	public int getSeq() {
		return seq;
	}
	public void setSeq(int seq) {
		this.seq = seq;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	
}

-BeanConfig.java

package com.exam.spring6.config;

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

import com.exam.spring6.beans.BoardTO;
import com.exam.spring6.beans.HelloBean;

@Configuration
@Scope("prototype")
public class BeanConfig {
	
	@Bean
	public HelloBean helloBean1() {
		return new HelloBean();
	}
	
	//생성자를 통한 데이터 주입 (생성자 주입)
	@Bean
	public HelloBean helloBean2() {
		return new HelloBean("홍길동");
	}
	
	//property를 이용한 생성자 주입
	@Bean
	public BoardTO to() {
		BoardTO to = new BoardTO();
		to.setSeq(1);
		to.setSubject("제목1");
		
		return to;
	}
}

-App.java

package com.exam.spring6;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.exam.spring6.beans.BoardTO;
import com.exam.spring6.beans.HelloBean;
import com.exam.spring6.config.BeanConfig;

public class App {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx =
				new AnnotationConfigApplicationContext( BeanConfig.class );
		
		HelloBean helloBean1 = (HelloBean)ctx.getBean( "helloBean1" );
		HelloBean helloBean2 = (HelloBean)ctx.getBean( "helloBean2" );
		helloBean1.sayHello();
		helloBean2.sayHello();
		
		BoardTO to =(BoardTO)ctx.getBean( "to" );
		System.out.println( to.getSeq() );
		System.out.println( to.getSubject() );
		
		ctx.close();
	}

}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
16:45:41.886 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@706a04ae
16:45:41.910 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
16:45:42.046 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
16:45:42.048 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
16:45:42.050 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
16:45:42.055 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'helloBean1'
HelloBean 생성자 호출
16:45:42.073 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'helloBean2'
HelloBean(String name) 생성자 호출
16:45:42.075 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'to'
null 님 안녕하세요
홍길동 님 안녕하세요
1
제목1
16:45:42.099 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@706a04ae, started on Mon Jan 25 16:45:41 KST 2021

 

 

 실습) 위에 했던 6번 내용을 어노테이션기법을 이용해서 출력하기

 -실행결과

17:35:06.067 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@706a04ae
17:35:06.091 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
17:35:06.231 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
17:35:06.233 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
17:35:06.234 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
17:35:06.240 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'to'
BoardTO 생성자 호출 
17:35:06.256 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'dao'
17:35:06.257 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'action'
17:35:06.263 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Autowiring by type from bean name 'action' via factory method to bean named 'dao'
MariadbBoardDAO list() 호출
10
20
30
40
50
60
17:35:06.408 [main] DEBUG o.s.c.a.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@706a04ae, started on Mon Jan 25 17:35:06 KST 2021

 -디렉터리 구성 (빨간선 표시된 것만 사용)

-AppEx01.java (실행클래스)

package com.exam.spring6;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.exam.spring6.beans.BoardAction;
import com.exam.spring6.beans.BoardTO;
import com.exam.spring6.config.BeanConfig01;

public class AppEx01 {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx =
				new AnnotationConfigApplicationContext( BeanConfig01.class );
		
		BoardTO to = (BoardTO)ctx.getBean("to");
		BoardAction action = (BoardAction)ctx.getBean( "action" );
		action.write(to);
		
		ctx.close();

	}
}

-BeanConfig01.java

package com.exam.spring6.config;

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

import com.exam.spring6.beans.BoardDAO;
import com.exam.spring6.beans.BoardTO;
import com.exam.spring6.beans.HelloBean;
import com.exam.spring6.beans.ListAction;
import com.exam.spring6.beans.MariadbBoardDAO;

@Configuration
@Scope("prototype")
public class BeanConfig01 {
	
	@Bean
	public BoardTO to() {
		return new BoardTO();
	}
	
	@Bean
	public MariadbBoardDAO dao() {
		return new MariadbBoardDAO();
	}
	
	@Bean
	public ListAction action( BoardDAO dao ) {
		return new ListAction(dao);
	}
}

-BoardTO.java

package com.exam.spring6.beans;

public class BoardTO {
	
	public BoardTO() {
		System.out.println( "BoardTO 생성자 호출 ");
	}
}

 -BoardDAO.java (인터페이스)

package com.exam.spring6.beans;

public interface BoardDAO {
	public abstract void insert( BoardTO to );
	public void list( BoardTO to );
}

 -MariadbBoardDAO.java

package com.exam.spring6.beans;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MariadbBoardDAO implements BoardDAO {

	public void insert(BoardTO to) {
	}

	public void list(BoardTO to) {
System.out.println( "MariadbBoardDAO list() 호출" );
		
		String url = "jdbc:mysql://localhost:3307/sample";
		String user = "root";
		String password = "!123456";
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			Class.forName("org.mariadb.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			
			String sql = "select deptno, dname, loc from dept";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			while( rs.next() ) {
				System.out.println( rs.getString( "deptno" ) );
			}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(rs!=null) try {rs.close();} catch(SQLException e) {} 
			if(conn!=null) try {conn.close();} catch(SQLException e) {} 
			if(pstmt!=null) try {pstmt.close();} catch(SQLException e) {} 
		}
	}

}

-BoardAction.java (인터페이스)

package com.exam.spring6.beans;

public interface BoardAction {
	public abstract void write( BoardTO to );
}

-ListAction.java

package com.exam.spring6.beans;

public class ListAction implements BoardAction {
	private BoardDAO dao;
	
	public ListAction( BoardDAO dao ) {
		this.dao = dao;
	}
	
	public void write(BoardTO to) {
		dao.list(to);
	}
}

 

728x90
반응형
Comments