post-custom-banner

Spring Framework

Spring Project Core
중요한 개념 2가지 
=> DI / AOP => Spring MVC가 나온다(Spring으로 구성된 model2 <- 구형) => Spring Boot(신형)로 발전

DI (Dependency Injection : 의존성 주입)
		IoC를 중심으로 객체의 관리 => 생성, 소멸의 관리를 spring이 대신하는 것
        생성, 소멸의 관리설정을 => 
        		XML - Spring Bean Configuration File
                - Annotaion
                
       
        의존성 주입
        		멤버필드에 대한 초기화 시키기
                - 생성자 주입 초기화 방법
                - setter메서드를 통해 초기화 방법



Srping으로 Project 구성할 때

1. Java Project에서 + 수동 라이브러리 적용

2. Maven Project에서 적용
			- Maven Project		- jdk설정
            - Java Project를 -> Maven Project로 변경하여 사용하는 방법
   Gradle Project

3. STS(String Tool Suit)
   eclipse + 라이브러리 포장 ( 내부적인 라이브러리나 gradle 사용)



Spring - Maven Project 설정

ex02 자바 프로젝트 생성 -> 생성 후 오른쪽클릭 -> 컨피규어 -> 컨버트 메이븐 프로젝트 누르고 설정

spring 라이브러리 가져오기 -> pom.java.txt파일에서 에서 빨간줄 밑부분 전체 복사 후

빨간줄 밑쪽부분에 붙여넣기

기존 pom.xml파일에 있던 코드 밑에 붙여주기

배포파일을 맞춰주면 맞춰줘야함

설정 바꿔주기

라이브러리 생성된 것



Spring - Maven Project

--- 주입 ---

setter 메서드를 통하여 주입하는 방식

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 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
	
	<bean name="to" class="com.exam.spring02.BoardTO" scope="prototype">
		<!-- property : set 메서드에 연결 -->
		<property name="seq" value="1" />
		<property name="subject" value="제목 1" />
	</bean>

</beans>

BoardTO

package com.exam.spring02;

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

App1

package com.exam.spring02;

public class App1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BoardTO to = new BoardTO();
		to.setSeq(1);
		to.setSubject("제목 1");
		
		System.out.println(to.getSeq());
		System.out.println(to.getSubject());
	}

}


App2

package com.exam.spring02;

import org.springframework.context.support.GenericXmlApplicationContext;

public class App2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/exam/spring02/context.xml");
		
		BoardTO to = (BoardTO)ctx.getBean("to");
		System.out.println(to.getSeq());
		System.out.println(to.getSubject());
		
		to.setSeq(2);
		to.setSubject("제목 2");
		
		System.out.println(to.getSeq());
		System.out.println(to.getSubject());
		
		ctx.close();
	}

}


WriteAction

package com.exam.spring02;

public class WriteAction {
	private BoardTO to;
	
	public WriteAction(BoardTO to) {
		// TODO Auto-generated constructor stub
		System.out.println("WriteAction(BoardTO to) 호출");
		
		this.to = to;
	}
	
	public void execute() {
		System.out.println(to.getSeq());
		System.out.println(to.getSubject());
	}
}

App3

package com.exam.spring02;

public class App3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BoardTO to = new BoardTO();
		to.setSeq(1);
		to.setSubject("제목 1");
		
		WriteAction writeAction = new WriteAction(to);
		writeAction.execute();
	}

}



--- Spring으로 출력 ---

WriteAction 과 App4클래스를 context.xml파일을 통하여 출력

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 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
	
	<bean name="to" class="com.exam.spring02.BoardTO" scope="prototype">
		<!-- property : set 메서드에 연결 -->
		<property name="seq" value="1" />
		<property name="subject" value="제목 1" />
	</bean>
	
	<bean name="writeAction1" class="com.exam.spring02.WriteAction" scope="prototype">
		<constructor-arg ref="to" />
	</bean>
</beans>

WriteAction

package com.exam.spring02;

public class WriteAction {
	private BoardTO to;
	
	public WriteAction(BoardTO to) {
		// TODO Auto-generated constructor stub
		System.out.println("WriteAction(BoardTO to) 호출");
		
		this.to = to;
	}
	
	public void execute() {
		System.out.println(to.getSeq());
		System.out.println(to.getSubject());
	}
}

App4

코드를보면 객체를 직접 생성하여 set으로 코드를 넣어주고 하는 방법들이 생략되어 편하다.

package com.exam.spring02;

import org.springframework.context.support.GenericXmlApplicationContext;

public class App4 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/exam/spring02/context.xml");
		
		WriteAction writeAction = (WriteAction)ctx.getBean("writeAction1");
		writeAction.execute();
		
		ctx.close();
	}

}



--- Property ---

setter메서드에 값을 넣어주는 태그

context.xml에 추가

<bean name="writeAction2" class="com.exam.spring02.WriteAction" scope="prototype">
		<constructor-arg>
			<bean class="com.exam.spring02.BoardTO" scope="prototype">
				<property name="seq" value="2" />
				<property name="subject" value="제목 2" />
			</bean>
		</constructor-arg>
	</bean>

App4 클래스에 추가

WriteAction writeAction2 = (WriteAction)ctx.getBean("writeAction2");
		writeAction2.execute();



--- getter / setter ---

TO에 대한 getter / setter 만들어서 해보기



BoardTO 클래스에 to에 대한 getter / setter 클래스 생성

package com.exam.spring02;

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

ListAction 클래스( WriteAction 복사 )

package com.exam.spring02;

public class ListAction {
	private BoardTO to;
	
	// getter / setter 생성자 생성
	public BoardTO getTo() {
		return to;
	}

	public void setTo(BoardTO to) {
		this.to = to;
	}

	public ListAction(BoardTO to) {
		// TODO Auto-generated constructor stub
		System.out.println("WriteAction(BoardTO to) 호출");
		
		this.to = to;
	}
	
	public void execute() {
		System.out.println(to.getSeq());
		System.out.println(to.getSubject());
	}
}

context.xml

<bean name="listAction1" class="com.exam.spring02.ListAction">
		<!-- ref로 to 참조 -->
		<property name="to">
			<bean class="com.exam.spring02.BoardTO" scope="prototype">
				<property name="seq" value="2" />
				<property name="subject" value="제목 2" />
			</bean>
		</property>
	</bean>

App4

ListAction listAction1 = (ListAction)ctx.getBean("listAction1");
		listAction1.execute();



--- 네임스페이스 ---

Xml의 기술 양식

XML 네임스페이스(namespace)
XML 네임스페이스는 XML 요소 간의 이름에 대한 충돌을 방지해 주는 방법을 제공.

XML 네임스페이스는 요소의 이름과 속성의 이름을 하나의 그룹으로 묶어주어 이름에 대한 충돌을 해결.

이러한 XML 네임스페이스는 URI(Uniform Resource Identifiers)로 식별됩니다.

<요소이름 xmlns:prefix="URI">

context.xml

xmlns의 ns는 name space로 이름공간을 뜻함.

<?xml version="1.0" encoding= "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	
   	이름공간 p라는곳에 생성
	xmlns:p="http://www.springframework.org/schema/p"
	
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
	
	<bean id="to1" class="com.exam.spring03.BoardTO" scope="prototype">
		<property name="seq" value="1" />
		<property name="subject" value="제목 1" />
	</bean>
	
	<bean id="to2" class="com.exam.spring03.BoardTO" p:seq="2" p:subject="제목 2" scope="prototype" />
</beans>

BoardTO

package com.exam.spring03;

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

App

package com.exam.spring03;

import org.springframework.context.support.GenericXmlApplicationContext;

public class App {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/exam/spring03/context.xml");
		
		BoardTO to1 = (BoardTO)ctx.getBean("to1");
		System.out.println(to1.getSeq());
		System.out.println(to1.getSubject());
		
		BoardTO to2 = (BoardTO)ctx.getBean("to2");
		System.out.println(to2.getSeq());
		System.out.println(to2.getSubject());
	}

}



--- 배열형식 ---

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 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
	
	<bean id="listTO" class="com.exam.spring04.BoardListTO">
		<property name="userLists">
			<list>
				<value>홍길동</value>
				<value>박문수</value>
			</list>
		</property>
	</bean>
</beans>

BoardListTO

package com.exam.spring04;

import java.util.ArrayList;

public class BoardListTO {
	private ArrayList<String> userLists;

	public ArrayList<String> getUserLists() {
		return userLists;
	}

	public void setUserLists(ArrayList<String> userLists) {
		this.userLists = userLists;
	}
	
}

App

package com.exam.spring04;

import java.util.ArrayList;

public class App {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		
		ArrayList<String> userList = new ArrayList();
		userList.add("홍길동");
		userList.add("박문수");
		
		BoardListTO listTO = new BoardListTO();
		listTO.setUserLists(userList);
		
		// Java적으로 처리
		for(String user : listTO.getUserLists()) {
			System.out.println(user);
		}
	}

}


App2

package com.exam.spring04;

import org.springframework.context.support.GenericXmlApplicationContext;

public class App2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/exam/spring04/context.xml");

		BoardListTO listTO = (BoardListTO)ctx.getBean("listTO");

		// Java적으로 처리
		for (String user : listTO.getUserLists()) {
			System.out.println(user);
		}
		
		ctx.close();
	}

}



--- ArrayList로 가져오기 ---

BoardTO

package com.exam.spring04;

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

BoardListTO

package com.exam.spring04;

import java.util.ArrayList;

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

App

package com.exam.spring04;

import java.util.ArrayList;

public class App {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		
		ArrayList<String> userList = new ArrayList();
		userList.add("홍길동");
		userList.add("박문수");
		
		BoardListTO listTO = new BoardListTO();
		listTO.setUserLists(userList);
		
		// spring적으로 처리 가능
		for(String user : listTO.getUserLists()) {
			System.out.println(user);
		}
		
		BoardTO to1 = new BoardTO();
		to1.setSeq(1);
		to1.setSubject("제목 1");
		
		BoardTO to2 = new BoardTO();
		to2.setSeq(2);
		to2.setSubject("제목 2");
		
		ArrayList<BoardTO> boardLists = new ArrayList();
		boardLists.add(to1);
		boardLists.add(to2);
		
		listTO.setBoardLists(boardLists);
		
		// 출력
		for(BoardTO to : boardLists) {
			System.out.println(to.getSeq());
			System.out.println(to.getSubject());
		}
	}

}



--- ArrayList를 Spring으로 ---

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 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
	
	<bean id="listTO" class="com.exam.spring04.BoardListTO">
		<property name="userLists">
			<list>
				<value>홍길동</value>
				<value>박문수</value>
			</list>
		</property>
		<property name="boardLists">
			<list>
				<bean class="com.exam.spring04.BoardTO" scope="prototype">
					<property name="seq" value="1" />
					<property name="subject" value="제목 1" />					
				</bean>
				<bean class="com.exam.spring04.BoardTO" scope="prototype">
					<property name="seq" value="2" />
					<property name="subject" value="제목 2" />					
				</bean>
			</list>
		</property>
	</bean>
	
</beans>

BoardTO

package com.exam.spring04;

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

BoardListTO

package com.exam.spring04;

import java.util.ArrayList;

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

App2

package com.exam.spring04;

import org.springframework.context.support.GenericXmlApplicationContext;

public class App2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/exam/spring04/context.xml");

		BoardListTO listTO = (BoardListTO)ctx.getBean("listTO");

		// spring적으로 처리
		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();
	}

}



--- 선언하여 사용하기 ---

context.xml에 추가

<!-- 미리 선언하기 -->
	<bean id="to1" class="com.exam.spring04.BoardTO" scope="prototype">
		<property name="seq" value="1" />
		<property name="subject" value="제목 1" />
	</bean>
	
	<bean id="to2" class="com.exam.spring04.BoardTO" scope="prototype">
		<property name="seq" value="2" />
		<property name="subject" value="제목 2" />
	</bean>
	
	
	<bean id="listTO2" class="com.exam.spring04.BoardListTO">
		<property name="userLists">
			<list>
				<value>홍길동</value>
				<value>박문수</value>
			</list>
		</property>
		<property name="boardLists">
			<list>
				<ref bean="to1" />
				<ref bean="to2" />
			</list>
		</property>
	</bean>

App2

package com.exam.spring04;

import org.springframework.context.support.GenericXmlApplicationContext;

public class App2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/exam/spring04/context.xml");

		BoardListTO listTO = (BoardListTO)ctx.getBean("listTO2");

		// spring적으로 처리
		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();
	}

}



--- HashMap ---

BoardListTO

package com.exam.spring04;

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

public class BoardListTO {
	private ArrayList<String> userLists;
	private ArrayList<BoardTO> boardLists;
	
	private HashMap<String, String> userMaps;
	private HashMap<String, BoardTO> boardMaps;
	
	public ArrayList<String> getUserLists() {
		return userLists;
	}
	public void setUserLists(ArrayList<String> userLists) {
		this.userLists = userLists;
	}
	public ArrayList<BoardTO> getBoardLists() {
		return boardLists;
	}
	public void setBoardLists(ArrayList<BoardTO> boardLists) {
		this.boardLists = boardLists;
	}
	public HashMap<String, String> getUserMaps() {
		return userMaps;
	}
	public void setUserMaps(HashMap<String, String> userMaps) {
		this.userMaps = userMaps;
	}
	public HashMap<String, BoardTO> getBoardMaps() {
		return boardMaps;
	}
	public void setBoardMaps(HashMap<String, BoardTO> boardMaps) {
		this.boardMaps = boardMaps;
	}
	
	
}

App3

package com.exam.spring04;

import java.util.HashMap;

public class App3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashMap<String, String> userMaps = new HashMap();
		userMaps.put("key1", "홍길동");
		userMaps.put("key2", "박문수");
		
		BoardListTO listTO = new BoardListTO();
		listTO.setUserMaps(userMaps);
		
        // values() : "key", "value" 중 value값
		for(String value : listTO.getUserMaps().values()) {
			System.out.println(value);
		}
	}

}



--- HashMap을 Spring으로 ---

context.xml

코드 추가

	<!-- HashMap -->
	<bean id="mapTO" class="com.exam.spring04.BoardListTO">
		<property name="userMaps">
			<map>
				<entry key="key1">
					<value>홍길동</value>
				</entry>
				<entry key="key2">
					<value>박문수</value>
				</entry>
			</map>
		</property>
	</bean>

BoardListTO

package com.exam.spring04;

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

public class BoardListTO {
	private ArrayList<String> userLists;
	private ArrayList<BoardTO> boardLists;
	
	private HashMap<String, String> userMaps;
	private HashMap<String, BoardTO> boardMaps;
	
	public ArrayList<String> getUserLists() {
		return userLists;
	}
	public void setUserLists(ArrayList<String> userLists) {
		this.userLists = userLists;
	}
	public ArrayList<BoardTO> getBoardLists() {
		return boardLists;
	}
	public void setBoardLists(ArrayList<BoardTO> boardLists) {
		this.boardLists = boardLists;
	}
	public HashMap<String, String> getUserMaps() {
		return userMaps;
	}
	public void setUserMaps(HashMap<String, String> userMaps) {
		this.userMaps = userMaps;
	}
	public HashMap<String, BoardTO> getBoardMaps() {
		return boardMaps;
	}
	public void setBoardMaps(HashMap<String, BoardTO> boardMaps) {
		this.boardMaps = boardMaps;
	}
	
	
}

App4

package com.exam.spring04;

import org.springframework.context.support.GenericXmlApplicationContext;

public class App4 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/exam/spring04/context.xml");
		
		BoardListTO mapTO = (BoardListTO)ctx.getBean("mapTO");
		
		for(String value : mapTO.getUserMaps().values()) {
			System.out.println(value);
		}
		
		ctx.close();
	}

}



--- Properties ---

spring05 패키지

BoardPropertiesTO

package com.exam.spring05;

import java.util.Properties;

public class BoardPropertiesTO {
	private Properties configs;

	public Properties getConfigs() {
		return configs;
	}

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

App

package com.exam.spring05;

import java.util.Properties;

public class App {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Properties configs = new Properties();
		configs.put("server", "192.168.1.100");
		configs.put("connectionTime", "5000");
		
		// 집어넣기
		BoardPropertiesTO configsTO = new BoardPropertiesTO();
		configsTO.setConfigs(configs);
		
		Properties newConfigs = configsTO.getConfigs();
		// 데이터 빼기
		System.out.println(newConfigs.getProperty("server"));
		System.out.println(newConfigs.getProperty("connectionTime"));
	}

}



--- Spring으로 뽑기 ---

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 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
	
	<bean id="configTO" class="com.exam.spring05.BoardPropertiesTO">
		<property name="configs">
			<props>
				<prop key="server">192.168.1</prop>
				<prop key="connectionTimeout">5000</prop>
			</props>
		</property>
	</bean>
</beans>

BoardPropertiesTO

package com.exam.spring05;

import java.util.Properties;

public class BoardPropertiesTO {
	private Properties configs;

	public Properties getConfigs() {
		return configs;
	}

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

App2

package com.exam.spring05;

import org.springframework.context.support.GenericXmlApplicationContext;

public class App2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/exam/spring05/context.xml");
		
		BoardPropertiesTO configs = (BoardPropertiesTO)ctx.getBean("configTO");
		
        // 객체가 Object인 이유는 Map 형식으로 값을 가졌기때문에 Object 형식으로 값을 받아줘야한다.
		for(Object to : configs.getConfigs().values()) {
			
		}
	}

}



--- Spring으로 DB 연결 / 세팅 ---

ex03 프로젝트 생성


ex03 자바 프로젝트 생성 -> 메이븐 프로젝트로 바꿔주고 -> pom.xml에 아까처럼 코드 추가 해주고 -> 메이븐 레파지토리 홈페이지 가서 -> 마리아디비 검색 -> 3.1.4 클릭 후 코드를마지막 dependency에 넣어주기



DB 만들기

com.exam.spring.model1
		BoardDAO
        		생성자
                List를 출력할 boardList()
com.exam.spring.model2
		Action(인터페이스)
        		execute
        ListAction
        		생성자
        		execute
                
com.exam.spring



--- 기존 방법 ---

BoardDAO

package com.exam.spring.model1;

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

public class BoardDAO {
	private Connection conn;
	
	public BoardDAO() {
		// TODO Auto-generated constructor stub
		String url = "jdbc:mariadb://localhost:3306/board";
		String user = "board";
		String password = "1234";
		
		try {
			Class.forName("org.mariadb.jdbc.Driver");
			this.conn = DriverManager.getConnection(url, user, password);
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("[에러] : " + e.getMessage());
		}
		
	}
	
	public ArrayList<String> boardList() {
		PreparedStatement pstmt = null;
		ResultSet rs= null;
		
		ArrayList<String> lists = new ArrayList();
		
		try {
			String sql = "select * from board1 limit 0, 5";
			pstmt = conn.prepareStatement(sql);
			
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				String data = String.format("%s [%s] %s",
						rs.getString("seq"), rs.getString("writer"),
						rs.getString("subject"));
				
				lists.add(data);
			}
					
		} catch(SQLException e) {
			System.out.println("[에러] : " + e.getMessage());
		} finally {
			if(rs != null) try {rs.close();} catch(SQLException e) {}
			if(pstmt != null) try {pstmt.close();} catch(SQLException e) {}
			if(conn != null) try {conn.close();} catch(SQLException e) {}
		}
		
		return lists;
	}
}



Action(인터페이스)

package com.exam.spring.model2;

public interface Action {
	void execute();
}



ListAction

package com.exam.spring.model2;

import java.util.ArrayList;

import com.exam.spring.model1.BoardDAO;

public class ListAction implements Action {
	private BoardDAO dao;
	
	public ListAction(BoardDAO dao) {
		// TODO Auto-generated constructor stub
		this.dao = dao;
	}
	
	@Override
	public void execute() {
		// TODO Auto-generated method stub
		ArrayList<String> lists = dao.boardList();
		for(String data : lists) {
			System.out.println(data);
		}
	}

}



App1

package com.exam.spring;

import com.exam.spring.model1.BoardDAO;
import com.exam.spring.model2.Action;
import com.exam.spring.model2.ListAction;

// 실행시키는 클래스
public class App1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BoardDAO dao = new BoardDAO();
		
		Action action = new ListAction(dao);
		action.execute();
	}

}



--- Spring으로 만들기 ---

Context.xml을 spring패키지에 넣기

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 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
	
	<bean id="dao" class="com.exam.spring.model1.BoardDAO" scope="prototype" />
	<bean id="action" class="com.exam.spring.model2.ListAction">
		<constructor-arg ref="dao" />
	</bean>
</beans>



실행할 App2 클래스

package com.exam.spring;

import org.springframework.context.support.GenericXmlApplicationContext;

import com.exam.spring.model2.Action;

public class App2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:com/exam/spring/context.xml");
		
		// DAO 생성 부분이 없어진다
		Action action = (Action)ctx.getBean("action");
	    action.execute();
	    
	    ctx.close();
	}

}



--- 어노테이션기법 ---

ex04 프로젝트 생성하여 똑같이 설정

pom.xml은 mariadb빼고 설정



Hello(인터페이스 클래스)

package com.exam.spring01.model;

public interface Hello {
	void sayHello(String name);
}



HelloBean1

package com.exam.spring01.model;

public class HelloBean1 implements Hello {
	
	public HelloBean1() {
		// TODO Auto-generated constructor stub
		System.out.println("HelloBean1() 호출");
	}

	@Override
	public void sayHello(String name) {
		// TODO Auto-generated method stub
		System.out.println(name + "님 안녕하세요");
	}

}



HelloBean2

package com.exam.spring01.model;

public class HelloBean2 implements Hello {

	public HelloBean2() {
		// TODO Auto-generated constructor stub
		System.out.println("HelloBean2() 호출");
	}

	@Override
	public void sayHello(String name) {
		// TODO Auto-generated method stub
		System.out.println("Hello " + name);
	}

}



BeanConfig

package com.exam.spring01.config;

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

import com.exam.spring01.model.HelloBean1;
import com.exam.spring01.model.HelloBean2;

// 환경설정 할거야 라는 것
@Configuration
public class BeanConfig {
	
	@Bean
	@Scope("prototype")
	public HelloBean1 helloBean1() {
		System.out.println("helloBean1() 호출");
		
		// 이 new는 singleton(default)로 인스턴스화 시킨다.
		return new HelloBean1();
	}
	
	@Bean
	@Scope("prototype")
	public HelloBean2 helloBean2() {
		System.out.println("helloBean2() 호출");
		return new HelloBean2();
	}
}



App

package com.exam.spring01;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.exam.spring01.config.BeanConfig;
import com.exam.spring01.model.Hello;
import com.exam.spring01.model.HelloBean1;
import com.exam.spring01.model.HelloBean2;

public class App {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// BeanConfig.class 를 쓴다는 것
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(BeanConfig.class);
		
		HelloBean1 helloBean1 = (HelloBean1)ctx.getBean("helloBean1");
		helloBean1.sayHello("홍길동");
		
		// 다형성의 원리로 인해 Hello로 부르기
		Hello hello = (Hello)ctx.getBean("helloBean1");
		hello.sayHello("박문수");
		
		HelloBean2 helloBean2 = (HelloBean2)ctx.getBean("helloBean2");
		helloBean2.sayHello("이몽룡");
		
		
		ctx.close();
				
	}

}



@Bean

Bean 어노테이션에 이름을 정해주면 그 이름으로 호출해야한다. / helloBean2를 helloBean으로 바꿈

실행시 호출



--- 또 다른 선언법 ---

BeanConfig 클래스에 추가


App 클래스에 추가


실행시



--- 생성자 주입 ---

ex04 프로젝트

com.exam.spring02 패키지 생성하여 진행



HelloBean

package com.exam.spring02.model;

public class HelloBean {
	private String name;
	
	public HelloBean() {
		// TODO Auto-generated constructor stub
		System.out.println("HelloBean() 호출");
		this.name = "홍길동";
	}
	
	// 생성자 주입할 오버로딩된 생성자
	public HelloBean(String name) {
		// TODO Auto-generated constructor stub
		System.out.println("HelloBean(String name) 호출");
		this.name = name;
	}
	
	public void sayHello() {
		System.out.println(name + "님 안녕하세요");
	}
}



BeanConfig

package com.exam.spring02.config;

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

import com.exam.spring02.model.HelloBean;

@Configuration
// 전부 다 prototype으로 선언해주기위해 클래스에다 선언
@Scope("prototype")
public class BeanConfig {

	@Bean
	public HelloBean helloBean1() {
		return new HelloBean();
	}
	
	// 생성자 인젝션
	@Bean
	public HelloBean helloBean2() {
		
		// 생성자 주입
		return new HelloBean("박문수");
	}
}



App

package com.exam.spring02;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.exam.spring02.config.BeanConfig;
import com.exam.spring02.model.HelloBean;

public class App {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(BeanConfig.class);
		
		HelloBean helloBean = (HelloBean)ctx.getBean("helloBean1");
		helloBean.sayHello();
		
		helloBean = (HelloBean)ctx.getBean("helloBean2");
		helloBean.sayHello();
	}

}



--- 응용해보기 ---



--- setter를 통한 주입 ---



BoardTO

package com.exam.spring04.model;

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

package com.exam.spring04.config;

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

import com.exam.spring04.model.BoardTO;

@Configuration
@Scope("prototype")
public class BeanConfig {
	
	// setter 주입
	@Bean
	public BoardTO boardTO() {
		BoardTO to = new BoardTO();
		to.setSeq(1);
		to.setSubject("제목 1");
		
		return to;
	}
}



App

package com.exam.spring04;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.exam.spring04.config.BeanConfig;
import com.exam.spring04.model.BoardTO;

public class App {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(BeanConfig.class);
		
		BoardTO to = (BoardTO)ctx.getBean("boardTO");
		System.out.println(to.getSeq());
		System.out.println(to.getSubject());
		
		ctx.close();
	}
	
}



ex03번에 있는 것을 어노테이션 기법으로 하기

profile
개발자 꿈나무
post-custom-banner

0개의 댓글