course 2021/Spring

Spring01 - 12/02

코딩하는토끼 2021. 12. 14. 23:55

* 이클립스 Window - Perspective - Open Perspective - Other 클릭 - Spring 선택하여 Open

* Package Explorer 창에서 우클릭 - New - Spring Legacy Project 클릭 -

Project name 작성 (ex00) 하고 Spring MVC Project 선택 후 Next 클릭 - 

package name 작성 (org.zerock.controller) 하고 Finish

 * 프로젝트 (ex00) 열어서 pom.xml 파일 열어서 수정 (버전설정)

* 프로젝트 우클릭 - Maven - Update Project 클릭 - 프로젝트 선택 후 OK (새로고침)

* 프로젝트 우클릭 - Run As - Run on Server 클릭 (테스트 실행)

(더 나은 서버 실행환경을 위해 기존에 추가되어있던 jsp 프로젝트를 remove 하고 실행하기)

↑ 실행결과

 

* 깃허브 설정

import 받아온 프로젝트가 실행되지 않으면, 

server 탭에서 import 한 프로젝트를 remove 하여 내 프로젝트만 남김 ↓

import 한 프로젝트 우클릭 - properties - Web project settings 검색하여 context root 를 다음과 같이 변경

 

* Lombok 라이브러리 설치

https://projectlombok.org

download - 1.18.22 download https://projectlombok.org/download

설치 완료하기

* 구글 maven repository 검색 https://mvnrepository.com

lombok 검색하여 project lombok 클릭

알맞은 버전 선택

maven 탭의 코드 복사

 

pom.xml 의 <dependencies> 아래에 붙여넣기

정렬 (cmd+shift+F) 후 저장 (cmd+S)

 

* pom.xml 수정

저장 후 이클립스 종료, 재시작


* src/main/java 에 새 패키지 만들기 - name: lecture.p01lombok

패키지 안에 새 클래스 만들기 - name: Customer

 

< lombok 사용하기 >

https://projectlombok.org/features/all 참고 (Features > Stable)

▼ @Getter, @Setter

lecture.p01lombok

Customer

package lecture.p01lombok;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter

public class Customer {
	
		private int id;
		private String name;
		private String city;
		private String address;

}

getter, setter 메소드를 직접 만들지 않아도 import, annotation 만 작성해주면 자동으로 생성됨

outline 에서 확인할 수 있음

App

확인해보자

package lecture.p01lombok;

public class App {
	public static void main(String[] args) {
		Customer c1 = new Customer();

		c1.setAddress("gangnam");
		c1.setId(1);
		c1.setCity("jeju");
		c1.setName("korea");

		System.out.println(c1.getAddress());
		System.out.println(c1.getCity());
		System.out.println(c1.getId());
		System.out.println(c1.getName());

		System.out.println(c1.toString());
		System.out.println(c1);

	}
}

결과를 보면 c1.toString 과 c1 의 결과가 동일함

toString 메소드를 재정의하지 않았기 때문

 

※ 클래스 우클릭 - Run As - Java Application 로 실행하기! (Run On Server 아님)

 

▼ @ToString

lombok 을 사용하지 않았다면 Source - Generate toString() 에서 field 선택하여 사용했을 것

하지만 우리는 annotation 으로 @ToString 작성하여 바로 사용할 수 있음

Customer 클래스에 @ToString 추가하기

package lecture.p01lombok;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString

public class Customer {
	
		private int id;
		private String name;
		private String city;
		private String address;

}

App 실행결과가 다음과 같이 바뀜

 

▼ @AllArgsConstructor, @NoArgsConstructor

이번에는 한번에 값을 저장해보기

App

public class App {

	public static void main(String[] args) {
		Customer c1 = new Customer();

		c1.setAddress("gangnam");
		c1.setId(1);
		c1.setCity("jeju");
		c1.setName("korea");

		System.out.println(c1.getAddress());
		System.out.println(c1.getCity());
		System.out.println(c1.getId());
		System.out.println(c1.getName());

		System.out.println(c1.toString());
		System.out.println(c1);

		Customer c2 = new Customer(2, "usa", "ny", "queens");
		System.out.println(c2);

Customer

package lecture.p01lombok;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor

public class Customer {
	
		private int id;
		private String name;
		private String city;
		private String address;

}

annotation @AllArgsConstructor, @NoArgsConstructor 작성하여

Customer c2 = new Customer(2, "usa", "ny", "queens");

Customer c1 = new Customer();

가능하게 함

Customer(int, String, String, String) 은 아래 코드가 작성된 순서대로 설정됨

 

▼ @Data

Employee 

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor

public class Employee {
	
	private int id;
	private String name;
	private String notes;
}

@Data 로 한번에 Getter, Setter, toString (+ equals, hashCode) 생성 가능

App

		Employee emp1 = new Employee(1, "kim", "korea");
		System.out.println(emp1);

위 코드 추가로 작성

 

▼ @Log

App

package lecture.p01lombok;

import lombok.extern.java.Log;

@Log

public class App {
	public static void main(String[] args) {
		Customer c1 = new Customer();

		c1.setAddress("gangnam");
		c1.setId(1);
		c1.setCity("jeju");
		c1.setName("korea");

		System.out.println(c1.getAddress());
		System.out.println(c1.getCity());
		System.out.println(c1.getId());
		System.out.println(c1.getName());

		System.out.println(c1.toString());
		System.out.println(c1);

		Customer c2 = new Customer(2, "usa", "ny", "queens");
		System.out.println(c2);
		
		Employee emp1 = new Employee(1, "kim", "korea");
		System.out.println(emp1);

//		log.log(Level.INFO, emp1.toString());
		
		log.severe(emp1.toString());
		log.warning(emp1.toString());
		log.info(emp1.toString());
		log.config(emp1.toString());
		
	}
}

@Log 작성 (import 도 하기)

https://docs.oracle.com/javase/8/docs/api/ 참고 (cmd+F 찾기하여 logger 검색)

기본적으로 info 이상만 작동하도록 설정되어있다

결과 ↓

로그가 출력되었다 (날짜, 시간, 패키지, 클래스 까지 자세히 출력됨)

- info, warning, severe 만 출력되었음 (info: 정보, warning: 경고, severe: 심각), config 는 출력되지 않았음

 

▼ 연습

Supplier

package lecture.p01lombok;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor

public class Supplier {
	
	// 필드 작성 및 
	// lombok 어노테이션으로
	// getter, setter, toString
	// 생성자 등을 만들기
	
	private int id;
	private String name;

}

* pom.xml 수정

<scope>runtime</scope> 지우기 - 저장

* src/main/resources 폴더의 log4j.xml 수정

표시된 두번째 줄을 다음과 같이 변경 ↓

<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">

저장


 

▼ @log4j (위의 작업은 log4j 를 사용하기 위한 사전작업이었음)

lecture.p02lombok

App

package lecture.p02lombok;

import lecture.p01lombok.Employee;

@log4j
public class App {
	
	public static void main(String[] args) {
		Employee e1 = new Employee(3, "seoul", "korea");

		log.info(e1.toString());
		log.info(e1);

		log.debug(e1);
		log.info(e1);
		log.warn(e1);
		log.error(e1);
		log.fatal(e1);
	}
}

※ annotation 으로 @log4j 작성했는데 오류 뜰 경우

→ 커서 올려서 힌트 얻어 작성하기 (Change to 'Log4j' (lombok.extern.log4j) 선택)

 

@log 와 차이 

1) log.info(e1.toString()) 처럼 toString() 을 작성하지 않고 log.info(e1) 로 작성해도 된다

2) level 에 debug - info - warn - error - fatal  가 있다

 

> 기본적으로 warn 이상만 작동하도록 설정되어있다

바꾸려면, pom.xml 파일에서 다음 부분을 수정 ↓

 

결과 ↓


Spring

DI : Dependency Injection 의존성 주입

 

lecture.p03core

App

package lecture.p03core;

public class App {
	public static void main(String[] args) {
		
		MyServlet s1 = new MyServlet();
		s1.setDao(new MyDao()); // 
		
		s1.doGet();
	}
}

MyServlet

package lecture.p03core;

import lombok.Setter;

@Setter
public class MyServlet {
	private MyDao dao = new MyDao();

	public void doGet() {
		// 0. 사전작업
		
		// 2. request handle
		
		// 3. business logic
		dao.update();
		
		// 4. add attribute
		
		// 5. forward / redirect
	}
}

MyDao

package lecture.p03core;

public class MyDao {
	public void update() {
		
	}
}

lecture.p04core

이번에도 App, MyServlet, MyDao 파일을 만들건데, 설명서(Spring Bean) context.xml 도 만들기

context.xml

패키지 우클릭 - New - Spring Bean Configuration File, name: context 로 작성

↓ 처음 생성하면 다음과 같음

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


</beans>

↓ 1차 작성 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean class="lecture.p04core.MyServlet"></bean>

	<bean class="lecture.p04core.MyDao"></bean>

</beans>

<bean class="lecture.p04core.MyServlet"></bean> 와 같이 작성하면 Spring 이 시작될 때 이 파일을 읽고 bean 을 생성

Servlet 의 bean : <bean class="lecture.p04core.MyServlet"></baen>

Dao 의 bean : <bean class="lecture.p04core.MyDao"></bean>

 

* MyServlet, MyDao 는 생성만 해놓은 상태

 

App

package lecture.p04core;

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

import lombok.extern.log4j.Log4j;

@Log4j
public class App {
	public static void main(String[] args) {

		String contextFilePath = "lecture/p04core/context.xml";
		ApplicationContext context = new ClassPathXmlApplicationContext(contextFilePath);

		MyServlet s1 = context.getBean(MyServlet.class);
		MyDao d1 = context.getBean(MyDao.class);

		log.warn(s1);
		log.warn(d1);

	}
}

xml 로 작성했으므로, ApplicationContext context = new ClassPathXmlApplicationContext("xml 파일 경로") 로 작성

(ApplicationContext 가 spring)

이 코드를 읽고 context.xml → bean 이 생성됨

MyServlet 의 bean : MyServlet s1 = context.getBean(MyServlet.class)

MyDao 의 bean : context.getBean(MyDao.class)

→ 잘 작동하는지 출력해보기 (log 출력해보기)


2차 작성

MyServlet

package lecture.p04core;

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class MyServlet {

	private MyDao myDao;
	
}

 

* MyDao 는 생성만 해놓은 상태 그대로 아무것도 작성하지 않음

 

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

	<bean class="lecture.p04core.MyServlet">
		<property name="myDao" ref="myDao"></property>
	</bean>

	<bean id="myDao" class="lecture.p04core.MyDao"></bean>

</beans>

 

App

package lecture.p04core;

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

import lombok.extern.log4j.Log4j;

@Log4j
public class App {
	public static void main(String[] args) {

		String contextFilePath = "lecture/p04core/context.xml";
		ApplicationContext context = new ClassPathXmlApplicationContext(contextFilePath);

		MyServlet s1 = context.getBean(MyServlet.class);
		MyDao d1 = context.getBean(MyDao.class);

		log.warn(s1);
		log.warn(d1);
		
		log.warn(s1.getMyDao());
	}
}

 

결과


lecture.p05coreExercise

Memory

package lecture.p05coreExercise;

public class Memory {

}

생성 후 작성X

 

Computer

package lecture.p05coreExercise;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Computer {

	private Memory memory;
	
}

 

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


<!--  Computer 빈, Memory 빈 만들기 -->
<!--  Computer 빈에 Memory 빈 주입 -->

<bean class="lecture.p05coreExercise.Computer">
	<property name="memory" ref="memory"></property>
</bean>

<bean id="memory" class="lecture.p05coreExercise.Memory"></bean>

</beans>

(property name 은 set/get 메소드에서 set/get 을 제외한 나머지!)

 

App

package lecture.p05coreExercise;

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

import lombok.extern.log4j.Log4j;

@Log4j
public class App {
	public static void main(String[] args) {
		
		String configLocation = "lecture/p05coreExercise/context.xml";
		ApplicationContext context = new ClassPathXmlApplicationContext(configLocation);
		
		Computer c = context.getBean(Computer.class);
//		context.getBean(Memory.class);
		Memory m = (Memory) context.getBean("memory");
		
		log.warn(c);
		log.warn(m);
		log.warn(c.getMemory());
	}
}

 

결과