Hello World 프로젝트 생성하기

|

프로젝트 생성하기

프로젝트 생성은 Spring Initializer 웹사이트를 이용해서 생성할 수 있습니다. 또는 CLI(Command line interface)를 이용해서도 동일한 결과를 얻을 수 있습니다.


start.spring.io 사이트 이용

해당 페이지에 접속해서 다음과 같이 항목을 선택합니다.

  • Gradle Project
  • Kotlin
  • 2.2.1
  • Group: com.snowdeer
  • Artifact: hello
  • Dependencies: Spring Web

그리고 Generate 버튼을 누르면 hello.zip 파일이 생성될 것입니다. 원하는 경로에 압축을 풉니다.


CLI를 이용한 경우

spring init \
--dependencies=web \
--groupId=com.snowdeer \
--artifactId=hello \
--name="Hello SnowDeer" \
--package-name=com.snowdeer.hello \
--language=kotlin \
--version=2.2.0 \
--build gradle \
hello

위 명령어를 이용해서 빈 프로젝트를 생성할 수 있습니다.


curl을 이용해서 다운로드하는 방법

그 외에도 curl 명령어를 이용해서 가져오는 방법이 있는데, 3가지 전부 start.spring.io로부터 가져오는 방법이라 동일합니다. [여기(https://spring.io/guides/tutorials/spring-boot-kotlin/)를 참고하세요.


실행 확인

해당 프로젝트가 있는 디렉토리로 이동하여

gradle bootRun

명령을 내리면 기본 웹사이트가 구동이 됩니다. http://localhost:8080으로 접속해서 확인을 해봅니다. ‘Whitelabel Error Page’ 페이지가 뜨면 정상 동작하고 있는 것입니다.


Hello World 요청 페이지 구현하기

이제 해당 프로젝트의 src/main/kotlin/com/snowdeer/hello 디렉토리로 이동합니다. 아마 HelloSnowDeerApplication.kt 파일은 자동으로 만들어졌을 것입니다. 같은 디렉토리에 HelloController.kt 파일을 생성하고 아래 내용을 입력합니다.

package com.snowdeer.hello

import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RequestMapping

@RestController
class HelloController {
  
 	@RequestMapping("/")
 	fun hello() : String {
 		return "Hello, SnowDeer"
 	}
}

여기까지 구현한 다음, 해당 프로젝트를 새로 실행합니다. 그리고 http://localhost:8080에 접속하면 위에서 구현한 페이지가 정상적으로 출력되는 것을 확인할 수 있습니다.

  • @RestController: 클래스 앞에 붙으며, 해당 클래스가 REST 컨트롤러 기능을 수행하도록 함
  • @RequestMapping: 메소드 앞에 붙으며, 해당 함수를 실행할 수 있는 주소를 설정함


컴포넌트 스캔

위에서 HelloController 클래스를 생성하고 그 뒤로 아무런 작업을 안해도 어플리케이션이 컨트롤러를 찾고 요청을 처리하는 것을 볼 수 있습니다. 스프링 부트 어플리케이션이 시작될 때, 어플리케이션 컨텍스트 클래스 아래의 모든 클래스와 패키지를 반복적으로 스캔하고, 어떤 클래스라고 하더라도 컴포넌트 어노테이션만 추가하면 클래스의 인스턴스를 생성하고 스프링 부트 어플리케이션 컨텍스트에 추가합니다. 이러한 기능을 컴포넌트 스캔(Component Scan)이라고 합니다.

좀 더 정확히 말하면 컴포넌트 스캔은 @Component 어노테이션이 붙은 모든 클래스를 스캔합니다. 위에서 @RestController 어노테이션을 사용했고, 그 외에도 보통 @Controller 어노테이션을 사용하는데 선언부로 가면 다음과 같이 @Component 어노테이션이 포함되어 있는 것을 확인할 수 있습니다.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

	@AliasFor(annotation = Component.class)
	String value() default "";

}

CLI 이용해서 Spring Boot 프로젝트 생성하는 방법

|

스프링 부트 프로젝트 시작하기

다음 명령어를 이용해서 간단한 스프링 부트 프로젝트를 생성할 수 있습니다.

$ spring init

Using service at https://start.spring.io
Content saved to 'demo.zip'

명령어 실행 후 디렉토리를 보면 demo.zip 파일이 있으며 이 안에는 maven 기반의 pom.xml 빌드 명세가 들어 있는 기본 프로젝트가 들어 있습니다.

프로젝트 구조는 다음과 같습니다.

.
├── HELP.md
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── example
    │   │           └── demo
    │   │               └── DemoApplication.java
    │   └── resources
    │       └── application.properties
    └── test
        └── java
            └── com
                └── example
                    └── demo
                        └── DemoApplicationTests.java

12 directories, 7 files


빌드 옵션 추가하기

다음과 같이 spring init 명령어 다음에 파라메터를 이용하여 커스텀 옵션을 추가할 수 있습니다.

$ spring init --d web,jpa,security --build gradle

Using service at https://start.spring.io
Content saved to 'demo.zip'

빌드 타입을 gradle로 설정했으며, 데이터 영속성으로 JPA를 사용하고, Spring Security로 보안을 적용하는 예제입니다.

또한 demo.zip 압축 파일이 아니라 snowdeer라는 이름의 디렉토리에 war 형태의 프로젝트를 생성하려면 다음과 같은 명령어를 사용합니다.

spring init -dweb,jpa,security --build gradle -p war snowdeer

Using service at https://start.spring.io
Project extracted to '/Users/snowdeer/Workspace/SpringBoot/snowdeer'

이 때 디렉토리 구조는 다음과 같습니다. gradle 기반이라 안드로이드 개발자들에겐 더 친숙한 구조 같습니다.

.
├── HELP.md
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── example
    │   │           └── snowdeer
    │   │               ├── DemoApplication.java
    │   │               └── ServletInitializer.java
    │   └── resources
    │       ├── application.properties
    │       ├── static
    │       └── templates
    └── test
        └── java
            └── com
                └── example
                    └── snowdeer
                        └── DemoApplicationTests.java

16 directories, 11 files


도움말

그 외에 spring help init 명령어나 spring init --list 명령어를 이용해서 도움말이나 지원하는 서비스 리스트를 확인할 수 있습니다.


실행

실행은 터미널에서 다음 명령어를 입력하면 됩니다.

gradle bootRun

그런 다음 웹 브라우저에서 http://127.0.0.1:8080를 입력하면 페이지가 하나 출력이 될 것입니다.

만약 포트 번호를 바꾸려면 application.properties 파일을 수정하면 됩니다. 이 파일은 src/main/resources 디렉토리 아래에 있으며 기본적으로 아무 것도 적혀 있지 않은 빈 파일입니다.

아래와 같이 속성 값을 수정해서 기본 포트 번호를 8080에서 8000으로 변경할 수도 있습니다.

server.port=8000

Spring Boot 설치(Mac OS)

|

Spring Boot 설치 방법(Mac OS 기준)

여기서는 brew를 이용해서 설치하는 방법을 포스팅 합니다.

brew tap pivotal/tap

brew install springboot


설치 후 다음 명령으로 스프링 부트 버전을 확인할 수 있습니다.

$ spring --version

Spring CLI v2.2.1.RELEASE

그리고 gradle도 다음과 같이 설치할 수 있습니다.

brew install gradle

Spring Boot 특징

|

Spring Boot 특징

2004년 Spring Framework 1.0이 나왔습니다. 정말 강력하고 많은 기능들 덕분에 많은 프로젝트에서 스프링 프레임워크를 사용해왔습니다. 스프링 부트는 기존의 스프링 개발 방식의 불편했던 설정이나 버전 충돌 등의 단점을 줄이고, 빠르고 쉽게 서버를 구축하고 테스트 할 수 있는 것을 목표로 만들어졌습니다.

스프링 부트는 다음과 같은 특징이 있습니다.

자동화된 라이브러리 관리

기존에도 Maven이나 Gradle을 이용하여 의존성 관리를 쉽게 할 수 있었지만, 스프링 부트는 더욱 더 간편하게 할 수 있습니다.

자동 설정

특정 라이브러리를 사용하기로 결정하면, 그에 필요한 설정은 자동으로 구성해주기 때문에 더욱 쉽게 사용할 수 있습니다. 또한 현재 버전에 맞는 라이브러리들을 자동으로 가져오기 때문에 버전 문제로 발생하는 문제도 줄어들었습니다.

XML 없는 환경 구축

XML을 이용해서 라이브러리를 설정하거나 환경을 설정하지 않아도 동작할 수 있습니다.

테스트 환경과 Tomcat 내장

스프링 부트 프로젝트는 기본적으로 Tomcat을 내장하고 있습니다. 실행할 때도 별도의 설정 없이 main 메소드를 호출하는 것만으로 실행이 되어 서버를 훨씬 빠르게 구동시킬 수 있습니다.

HTML5 Canvas를 이용해서 주사위 게임 만들기

|

dicegame.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dice Game</title>

    <script src="/js/dice.js"></script>
</head>
<body>
    <canvas id="canvas" width="400" height="200">
        이 브라우저는 HTML5 Canvas를 지원하지 않습니다.
    </canvas>

    <br>

    <button onClick="throwDices();">주사위 던지기</button>

    <script>
        window.onload = function() {
            init();
        }
    </script>
</body>
</html>


dice.js

var cwidth = 400;
var cheight = 300;
var dicex = 50;
var dicey = 50;
var diceWidth = 100;
var diceHeight = 100;
var dotrad = 6;
var ctx;

function init() {
    var ch = 1 + Math.floor(Math.random() * 6);
    drawFace(ch);
}

function drawFace(n) {
    ctx = document.getElementById("canvas").getContext("2d");
    ctx.lineWidth = 5;
    ctx.clearRect(dicex, dicey, diceWidth, diceHeight);
    ctx.strokeRect(dicex, dicey, diceWidth, diceHeight);
    ctx.fillStyle = "#009966";

    switch(n) {
        case 1:
            draw1();
            break;

        case 2:
            draw2();
            break;

        case 3:
            draw2();
            draw1();
            break;

        case 4:
            draw4();
            break;

        case 5:
            draw4();
            draw1();
            break;

        case 6:
            draw4();
            draw2mid();
            break;
    }
}

function draw1() {
    var dotx;
    var doty;

    ctx.beginPath();

    dotx = dicex + 0.5 * diceWidth;
    doty = dicey + 0.5 * diceHeight;
    ctx.arc(dotx, doty, dotrad, 0, Math.PI * 2, true);

    ctx.closePath();
    ctx.fill();
}

function draw2() {
    var dotx;
    var doty;

    ctx.beginPath();

    dotx = dicex + 3 * dotrad;
    doty = dicey + 3 * dotrad;
    ctx.arc(dotx, doty, dotrad, 0, Math.PI * 2, true);

    dotx = dicex + diceWidth - 3 * dotrad;
    doty = dicey + diceHeight - 3 * dotrad;
    ctx.arc(dotx, doty, dotrad, 0, Math.PI * 2, true);

    ctx.closePath();
    ctx.fill();
}

function draw4() {
    var dotx;
    var doty;

    ctx.beginPath();

    dotx = dicex + 3 * dotrad;
    doty = dicey + 3 * dotrad;
    ctx.arc(dotx, doty, dotrad, 0, Math.PI * 2, true);

    dotx = dicex + diceWidth - 3 * dotrad;
    doty = dicey + diceHeight - 3 * dotrad;
    ctx.arc(dotx, doty, dotrad, 0, Math.PI * 2, true);

    ctx.closePath();
    ctx.fill();
    ctx.beginPath();

    dotx = dicex + 3 * dotrad;
    doty = dicey + diceHeight - 3 * dotrad;
    ctx.arc(dotx, doty, dotrad, 0, Math.PI * 2, true);

    dotx = dicex + diceWidth - 3 * dotrad;
    doty = dicey + 3 * dotrad;
    ctx.arc(dotx, doty, dotrad, 0, Math.PI * 2, true);

    ctx.closePath();
    ctx.fill();
}

function draw2mid() {
    var dotx;
    var doty;

    ctx.beginPath();

    dotx = dicex + 3 * dotrad;
    doty = dicey + 0.5 * diceHeight;
    ctx.arc(dotx, doty, dotrad, 0, Math.PI * 2, true);

    dotx = dicex + diceWidth - 3 * dotrad;
    doty = dicey + 0.5 * diceHeight;
    ctx.arc(dotx, doty, dotrad, 0, Math.PI * 2, true);

    ctx.closePath();
    ctx.fill();
}

function throwDices() {
    var ch = 1 + Math.floor(Math.random() * 6);
    drawFace(ch);
}