CORS란 무엇인가?

CORS(Cross-Origin Resource Sharing)는 웹 브라우저의 보안 정책 중 하나로, 서로 다른 출처(Origin) 간의 리소스 요청을 제한하는 기능입니다. 즉, 클라이언트(예: React)와 서버(예: Spring Boot)가 다른 도메인에서 실행될 경우, 브라우저는 보안상의 이유로 기본적으로 요청을 차단합니다.

예를 들어, http://localhost:9000에서 실행 중인 프론트엔드가 http://localhost:8080의 API를 호출하면 CORS 정책에 의해 차단될 수 있습니다.

대표적인 CORS 오류 메시지

Access to fetch at 'http://localhost:8080/api/data' from origin 'http://localhost:9000' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

스프링 부트에서 CORS 해결 방법

1. WebMvcConfigurer 설정하기 (권장)

Spring Boot에서는 WebMvcConfigurer 인터페이스를 구현하여 CORS 정책을 설정할 수 있습니다.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 모든 경로에 대해 CORS 허용
                .allowedOrigins("http://localhost:9000") // 허용할 오리진 설정
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 허용할 HTTP 메서드 지정
                .allowedHeaders("*") // 모든 헤더 허용
                .allowCredentials(true) // 쿠키 허용
                .maxAge(3600); // 캐시 시간 (초)
    }
}

장점: 설정이 간단하고, Spring Security와도 쉽게 연동할 수 있음.


2. @CrossOrigin 어노테이션 사용하기 (컨트롤러별 적용)

각각의 컨트롤러 혹은 특정 API 메서드에 대해 CORS 설정을 적용할 수도 있습니다.

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:9000") // 특정 오리진 허용
public class MyController {

    @GetMapping("/data")
    public String getData() {
        return "CORS 요청 성공!";
    }
}

장점: 특정 API 엔드포인트만 CORS 허용하고 싶을 때 유용함.


3. CorsFilter를 사용한 설정 (필터 방식, 확장 가능)

Spring Boot의 필터를 직접 구현하여 CORS 정책을 설정할 수도 있습니다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:9000"); // 허용할 오리진
        config.addAllowedHeader("*");
        config.addAllowedMethod("*"); // 모든 HTTP 메서드 허용
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

장점: 필요에 따라 동적으로 CORS 정책을 변경할 때 유용함.


정리

스프링 부트에서 CORS 문제를 해결하는 방법은 여러 가지가 있으며, 가장 일반적으로는 WebMvcConfigurer 방식이 추천됩니다. 특정 컨트롤러에만 적용할 경우 @CrossOrigin을, 보다 유연한 정책을 적용하려면 CorsFilter를 사용할 수 있습니다.

 

Ubuntu 서버에서 Spring Boot 애플리케이션을 강력하고 확장성 꿈은 배포 방식을 적용할 수 있도록, Git, Gradle, Tomcat을 활용하는 방법을 정리합니다.

  • GitHub에서 파일 가져오기
  • Gradle을 이용한 빌드 (bootJar)
  • Spring Boot JAR 파일을 시작하는 방법
  • Tomcat을 이용한 WAR 배포
  • 반응 성능 확장 & 우수화

1. GitHub에서 파일 가져오기

Git 설치 (필수)

sudo apt update
sudo apt install -y git

GitHub에서 소스 클론

git clone https://github.com/[내 git]/my-project-001.git
cd my-project-001

2. Gradle을 이용한 빌드

Gradle 설치

sudo apt install -y gradle
gradle -v

JAR 배포 원하면 bootJar 실행

./gradlew bootJar

빌드 결과 확인

ls -l build/libs/

3. Spring Boot 시작 & 반응 공유

필요시 JAR 배포 시작

java -jar build/libs/myapp-0.0.1-SNAPSHOT.jar

반균 시작 (nohup)

nohup java -jar build/libs/myapp-0.0.1-SNAPSHOT.jar > app.log 2>&1 &

자동 시작 (systemd)

sudo nano /etc/systemd/system/myapp.service
[Unit]
Description=Spring Boot Application
After=network.target

[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/my-project-001
ExecStart=/usr/bin/java -jar /home/ubuntu/my-project-001/build/libs/myapp-0.0.1-SNAPSHOT.jar
SuccessExitStatus=143
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp

👉 5. Tomcat을 활용한 WAR 배포

Spring Boot WAR 배포 빌드

build.gradle 수정:

plugins {
    id 'war'
}

dependencies {
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}

bootWar {
    archiveBaseName = 'myapp'
    archiveVersion = '0.0.1'
}
./gradlew bootWar

Tomcat 설치

wget https://dlcdn.apache.org/tomcat/tomcat-9/v9.0.83/bin/apache-tomcat-9.0.83.tar.gz
tar -xvf apache-tomcat-9.0.83.tar.gz
sudo mv apache-tomcat-9.0.83 /opt/tomcat
sudo chmod +x /opt/tomcat/bin/*.sh

WAR 파일 배포 & Tomcat 시작

cp build/libs/myapp-0.0.1.war /opt/tomcat/webapps/
/opt/tomcat/bin/startup.sh

🔧 6. 성능 확장 & 우수화

Reverse Proxy 매핑 (Nginx, HAProxy)

Connection Pool 설정 (server.xml 수정)

반복 시작 필합 (CI/CD 개선)

로드 밸런서 적용


👉 7. 결말

Ubuntu에서 Spring Boot을 가능한 모든 방식으로 배포할 수 있도록 해보았습니다.

✨ 일반적인 배포: java -jar + nohup 또는 systemd ✨ 클래스터 분류 가능: WAR + Tomcat

'Back-End > Java & Spring' 카테고리의 다른 글

CORS 오류 해결하기(Spring)  (0) 2025.03.02
Spring Boot에서 Bean Scope 설정하기  (0) 2025.02.18
H2 Database 설정하기(feat.Spring Boot)  (0) 2025.02.18

Spring Boot에서 Bean Scope는 객체의 생명 주기와 생성 방식을 결정하는 중요한 요소입니다.

이를 적절히 설정하면 성능과 메모리 사용을 최적화할 수 있습니다.

1. Bean Scope란?

Bean Scope는 Spring 컨테이너가 관리하는 Bean이 언제 생성되고, 어떻게 공유되며, 언제 소멸되는지를 정의하는 개념입니다. 기본적으로 Spring은 모든 Bean을 Singleton으로 생성하지만, 필요에 따라 다른 Scope를 설정할 수 있습니다.

2. Spring Boot에서 지원하는 Bean Scope 종류

2.1 Singleton (기본값)

  • 한 개의 Bean 인스턴스를 생성하여 애플리케이션 전역에서 공유
  • 메모리 절약성능 최적화에 유리하지만, 상태를 변경하면 모든 곳에서 공유됨

설정 방법

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("singleton") // 생략 가능 (기본값)
public class SingletonBean {
    public SingletonBean() {
        System.out.println("Singleton Bean 생성됨");
    }
}

2.2 Prototype

  • 매번 새로운 Bean 인스턴스를 생성
  • 상태를 가지는 Bean이나 멀티스레드 환경에서 유용하지만, 메모리 사용량 증가 가능

설정 방법

@Component
@Scope("prototype")
public class PrototypeBean {
    public PrototypeBean() {
        System.out.println("Prototype Bean 생성됨");
    }
}

2.3 Request (웹 애플리케이션 전용)

  • HTTP 요청마다 새로운 Bean 인스턴스 생성
  • Spring MVC에서 요청 범위의 데이터를 처리할 때 유용

설정 방법

@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestBean {
    public RequestBean() {
        System.out.println("Request Bean 생성됨");
    }
}

2.4 Session (웹 애플리케이션 전용)

  • 사용자의 세션이 유지되는 동안 같은 Bean을 공유
  • 로그인 정보 또는 사용자 세션 정보를 저장할 때 유용

설정 방법

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionBean {
    public SessionBean() {
        System.out.println("Session Bean 생성됨");
    }
}

2.5 Application (웹 애플리케이션 전용)

  • 애플리케이션 실행 동안 단 하나의 Bean을 공유
  • 글로벌 설정 정보를 유지할 때 유용

설정 방법

@Component
@Scope(value = "application", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ApplicationBean {
    public ApplicationBean() {
        System.out.println("Application Bean 생성됨");
    }
}

3. Bean Scope 설정이 미치는 영향

Scope 생성 시점 공유 범위 주요 사용 예
Singleton 애플리케이션 시작 시 1회 애플리케이션 전체 공용 서비스, 설정 정보
Prototype 매번 새로 생성 공유 없음 상태를 가지는 객체
Request HTTP 요청 시 생성 요청 범위 요청별 사용자 정보
Session 세션 시작 시 생성 세션 범위 로그인 정보 관리
Application 애플리케이션 시작 시 1회 애플리케이션 전체 글로벌 설정 정보

4. 정리

Spring Boot에서 Bean Scope는 애플리케이션의 성능과 메모리 관리에 중요한 영향을 줍니다. 기본적으로 Singleton을 사용하지만, 필요에 따라 Prototype, Request, Session, Application 범위를 적절히 활용하여 최적의 구조를 설계하는 것이 중요합니다.

Spring Boot에서 빠르게 테스트하거나, 데이터 유지가 필요한 개발 환경을 위해 H2 Database를 설정하는 방법을 정리합니다. 별도의 데이터베이스 설치 없이 로컬에서 가볍게 사용할 수 있어 개발 및 테스트 환경에 최적화된 선택지입니다.

1. H2 Database란?

H2 Database는 가볍고 빠른 RDB로, Spring Boot와 쉽게 연동할 수 있습니다. 인메모리 모드, 파일 모드, TCP 서버 모드 등 다양한 실행 방식을 지원하며, 개발 및 테스트 환경에서 유용하게 활용됩니다.

특히, 별도의 설치 과정 없이 설정만으로 로컬에서 사용할 수 있어 개발 생산성을 높이는 데 유리합니다.

2. H2 Database 설정 방법

2.1 빠른 테스트용 (인메모리 모드)

  • 데이터가 애플리케이션 종료 시 삭제됨
  • 가장 빠른 속도를 제공하며, 테스트 환경에 적합

설정 (application.yml)

spring:
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
    username: sa
    password:
  h2:
    console:
      enabled: true

jdbc:h2:mem:testdb 를 사용하면 메모리에서만 동작하며, 애플리케이션이 종료되면 데이터가 삭제됩니다.

2.2 데이터 유지용 (파일 모드)

  • 데이터가 애플리케이션 종료 후에도 유지됨
  • 파일에 데이터가 저장되므로 로컬 개발 환경에서 지속적인 사용 가능

설정 (application.yml)

spring:
  datasource:
    url: jdbc:h2:file:~/testdb
    driver-class-name: org.h2.Driver
    username: sa
    password:
  h2:
    console:
      enabled: true

jdbc:h2:file:~/testdb 를 사용하면 ~/testdb.mv.db 파일에 데이터가 저장되며, 애플리케이션을 재시작해도 데이터가 유지됩니다.

3. H2 Console 활성화

Spring Boot에서 H2 Database를 쉽게 확인하려면 H2 콘솔을 활성화하는 것이 좋습니다.

H2 콘솔 접속 방법

  1. 브라우저에서 http://localhost:8080/h2-console 접속
  2. JDBC URL을 application.yml의 설정값과 동일하게 입력 (jdbc:h2:mem:testdb 또는 jdbc:h2:file:~/testdb)
  3. Connect 버튼 클릭

4. TCP 서버 모드 설정 (다중 접속 지원)

  • 여러 개의 애플리케이션에서 같은 H2 Database에 접근해야 할 경우 유용함
  • 파일 모드와 유사하지만 별도의 프로세스로 실행됨

설정 (application.yml)

spring:
  datasource:
    url: jdbc:h2:tcp://localhost/~/testdb
    driver-class-name: org.h2.Driver
    username: sa
    password:
  h2:
    console:
      enabled: true

TCP 서버 실행 방법

java -cp h2-*.jar org.h2.tools.Server -tcp -tcpAllowOthers -ifNotExists

이후 jdbc:h2:tcp://localhost/~/testdb URL을 사용해서 접속하면 됩니다.

5. 정리

실행 모드 url 설정데이터 유지 여부  용도
인메모리 jdbc:h2:mem:testdb ❌ (휘발성) 빠른 테스트
파일 jdbc:h2:file:~/testdb ✅ (유지됨) 로컬 개발 환경
TCP 서버 jdbc:h2:tcp://localhost/~/testdb ✅ (유지됨) 다중 애플리케이션 접근

H2 Database는 설정이 간단하면서도 강력한 기능을 제공하므로, 개발 중 필요에 따라 적절한 모드를 선택하여 사용하면 좋습니다.

 

+ Recent posts