ch02. 스프링 시작

728x90
참고 도서 : 스프링5 프로그래밍 입문 - 최범균 저

ch02. 스프링 시작

1. 스프링 프로젝트 시작

[스프링 이용 프로젝트 진행 과정] : 폴더 생성 -> 프로젝트 생성 -> 프로젝트 import -> 설정파일/자바코드 작성-> 실행

 메이븐 프로젝트 생성 OR 그레이들 프로젝트 생성 // 최근 그레이들 선호 
 이클립스에서 메이븐 프로젝트 임포트
 스프링에 맞는 자바 코드, 설정 파일 작성
 실행

[프로젝트 폴더 생성] : 메이븐, 그레이들 모두 동일 폴더 구조 사용

[프로젝트 생성-(1)] 

(1) 메이븐 이용

① [메이븐 프로젝트 생성] : pom.xml 파일 작성

-메이븐 프로젝트 설정 파일 XML 파일로 작성

                                                  *XML 파일 :문서 데이터 구조 형식 정의한 마크업 언어

    >> pom.xml 파일

* 
메이븐 프로젝트 핵심 = pom.xml 파일

-모든 메이븐 프로젝트는 프로젝트의 루트 폴더에 pom.xml 파일을 갖는다.
-메이븐 프로젝트 설정 정보 관리하는 파일
<?xml version="1.0" encoding="UTF-8"?>
<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>sp5</groupId>
	<artifactId>sp5-chap02</artifactId> 
<version>0.0.1-SNAPSHOT</version>

<dependencies>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>5.0.2.RELEASE</version>
	</dependency>
</dependencies>

<build>
	<plugins>
		<plugin>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>3.7.0</version>
			<configuration>
				<source>1.8</source>
				<target>1.8</target>
				<encoding>utf-8</encoding>
			</configuration>
		</plugin>
	</plugins>
</build>

</project>

[프로젝트 import]

② [메이븐 프로젝트 임포트] : File – Import – Maven – Existing ... -> Finish

    이클립스에 임포트된 메이븐 프로젝트 모습

--[src/main/java 폴더] : 소스 폴더로 정의되어있음

--[Maven Dependencies]

                                  - -> 메이븐 의존에 설정한 아티팩트가 이클립스 프로젝트 클래스패스에 추가됨


                 <메이븐 의존 설정>

<dependencies>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>5.0.2.RELEASE</version>
	</dependency>
</dependencies>
-메이븐은 한 개 모듈을 아티팩트 단위로 관리
-위 설정은 5,0,2 RELEASE 버전 아티팩트에 의존을 추가한 것,
-, 메이븐 프로젝트의 소스 코드를 컴파일,실행 할 때,
사용할 클래스 패스에 spring-context-5.0.2 RELEASE.jar 파일을 추가한다는 의미.

 

                <메이븐 리포지토리> : 등록의 개념

-원격 리포지토리
-로컬 리포지토리

                 <메이븐 의존 전이>

: 메이븐은 의존 대상 뿐 아니라 의존 대상이 다시 의존하는 대상도 함께 다운로드한다.
의존 전이 :의존 대상이 의존하고 있는 대상까지도 의존 대상에 포함하는 형태

                 <메이븐 기본 폴더 구조>

-src/main/java 폴더: 자바 소스코드 위치
-src/main/resources 폴더 : 다른 자원 파일
-src/main/webapp 폴더 : 웹 어플리케이션 기준 폴더
 

[프로젝트 생성-(2)] 

(2) 그레이들 이용  더 이용/선호

 [그레이들 프로젝트 생성] :build.gradle 파일 작성

apply plugin: 'java'  //그레이들 java 플러그인 적용 

sourceCompatibility = 1.8 //소스와 컴파일 결과를 1.8 버전에 맞춤
targetCompatibility = 1.8 
compileJava.options.encoding = "UTF-8" //소스 인코딩으로 UTF-8 사용 

repositories { //의존 모듈을 메이븐 중앙 리포짙리에서 다운로드함 
    mavenCentral()
}

dependencies {
    compile 'org.springframework:spring-context:5.0.2.RELEASE'
} //spring-context 모듈에 대한 의존을 설정 

task wrapper(type: Wrapper) { //그레이들 래퍼 설정 
    gradleVersion = '4.4'
}

[프로젝트 import]

 [메이븐 프로젝트 임포트] : File  Import  Gradle   Existing ... -> Finish

                              //그레이들 프로젝트가 이클립스 프로젝트로 임포트됨.


<스프링 기본 예제 코드 작성>

*(Bean) 객체 : 스프링이 생성하는 객체

[Greeter.java] : 콘솔에 간단한 메시지 출력 자바 클래스

public class Greeter {
	//필드 
	private String format;
	//메소드 
	public String greet(String guest) {  //String 문자열 포맷 이용 -> 새 문자열 생성 메소드 
		return String.format(format, guest);
	}
	//setter 메소드 
	public void setFormat(String format) { //greeat() 메소드에서 사용될 포맷을 여기서 setting
		this.format = format;
	}
}

[AppContext.java] : 스프링 설정 파일

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

@Configuration // 해당 클래스를 스프링 설정 클래스로 지정한다. 
public class AppContext {

	@Bean //해당 메소드가 생성한 객체를 스프링이 관리하는 빈 객체로 등록 
	public Greeter greeter() {
		Greeter g = new Greeter();
		g.setFormat("%s, 안녕하세요!"); 
		return g;
	}
}

[Main.java] : main() 메소드를 토대로 스프링과 Greeter 실행하는 메인 클래스

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

	public static void main(String[] args) {
		// 자바 설정 정보 읽어와서 빈객체 생성, 관리 클래스 
		AnnotationConfigApplicationContext ctx = 
				new AnnotationConfigApplicationContext(AppContext.class);
		
		//getBean("빈 객체 이름", 빈 객체 리턴 type)
		Greeter g = ctx.getBean("greeter", Greeter.class);
		String msg = g.greet("스프링");
		System.out.println(msg);
		
		ctx.close();
	}
}

2. 스프링은 객체 컨테이너 

* 스프링의 핵심 기능 : 객체 생성, 초기화하는 것

[관련 인터페이스]

-[BeanFactory] 인터페이스: 객체 생성, 검색, 제공 기능 <- getBean() 정의
-[ApplicationContext] 인터페이스 : 객체 생성,초기화 + 환경 변수 처리 기능

 

[위 인터페이스의 구현 클래스]

<AnnotationConfigApplicationContext 클래스>

  -ApplicationContext 인터페이스의 구현 클래스

  -자바 애노테이션 이용 클래스로부터 객체 설정 정보 가져옴

<GenericXmlApplicationContext>

  -XML로부터 객체 설정 정보 가져옴

<GenericGroovyApplicationContext>

  -그루비 코드 이용해서 설정 정보 가져옴

* 어떤 구현 클래스를 사용하건, 각 구현 클래스는 (1)설정 정보로부터 빈(Bean)객체생성 후 (2) getBean()으로 객체 제공

(1) AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppContext.class);
				//빈 객체 생성 후 
(2) Greeter g = ctx.getBean("greeter", Greeter.class); //해당 빈 객체 가져옴

이처럼 Application / BeanFactory 는 빈객체 생성,초기화,보관,제거 등의 관리자 역할을 하므로                                                                            =>  " 스프링 컨테이너 " 라고 부른다.


[싱글톤 객체] : 단일 객체

 - (별도 설정X) 스프링은 한 개의 빈 객체만을 생성하며, 이때 빈 객체는 싱글톤 범위 가짐

 - 기본적으로 스프링은 한 개의 @Bean 애노테이션에 대해 한 개의 빈 객체를 생성한다.

		Greeter g1 = ctx.getBean("greeter", Greeter.class);
		Greeter g2 = ctx.getBean("greeter", Greeter.class);

		System.out.println("(g1 == g2) = " + (g1 == g2)); //True 나옴

//만약 다른 객체로 getBean() 하고자 한다면앞서 스프링은 한 개의 @Bean 노테이션에 대해 기본적으로 한 개의 빈 객체민을 생성한다고 하였으므로, “greeter”과 다른 이름의 메소드를 만들어 @Bean 애노테이션을 한 번 더 사용하며 된다.

@Bean
public Greeter greeter() {
	....
}

@Bean
public Greeter greeter1234() {
	... 
}
 

728x90