spring 프로퍼티를 설정할때 중요정보를 보여주지 않고 따로 환경설정 파일로 분리하고 싶을때가 있을것이다.
그때 dotenv를 적용해서 env파일로 분리하는 방법을 아래 내용에 작성하려고 한다.
build.gradle.kts
//dotenv
implementation ("io.github.cdimascio:java-dotenv:5.2.2")
루트 디렉터리 경로에 .env 파일 생성
.env
SPRING_PROFILES_ACTIVE=local
SECRET=jwt시크릿키
application.yml
spring:
config:
import: optional:file:.env[.properties]
profiles:
active: ${SPRING_PROFILES_ACTIVE} # 기본적으로 local 프로파일 사용 (운영에서는 prod로 변경)
jwt:
expiration_time: 86400000 # 1일
secret: ${secret}
logging:
level:
org.hibernate.SQL: DEBUG # Hibernate 쿼리 로그 출력
config 아래 import 부분을 추가, .env에 설정한 key를 사용
application.kt
package com.contact.management
import io.github.cdimascio.dotenv.Dotenv
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.data.jpa.repository.config.EnableJpaAuditing
@SpringBootApplication
@EnableJpaAuditing
class ManagementApplication
fun main(args: Array<String>) {
runApplication<ManagementApplication>(*args)
val dotenv = Dotenv.load()
System.out.println("SPRING_PROFILES_ACTIVE: " + dotenv.get("SPRING_PROFILES_ACTIVE"));
System.out.println("SECRET: " + dotenv.get("SECRET"));
}
test 코드를 만들어도 되지만 간단하게 테스트 하기위해서 applicaiton.kt에 해당 코드 작성
.gitignore
.env*
- 깃에 커밋시 해당 환경설정 파일이 commit되면 안되므로 맨 아래 라인에 .env*을 추가
git ignore에 .env*을 포함해도 .env파일이 git staging에 보일경우 안보이게 하는법
1. .env 파일을 백업하고 프로젝트에 있는 .env 파일을 삭제
2. 아래 명령어 intelij 터미널에 입력
git rm .env --cached
git add .
git commit -m "remove .env file from git"
git push
3. 이후 다시 루트 디렉터리에 백업한 .env파일을 생성한후 git - commit 클릭
env 파일을 변경해도 커밋 changes에 안보이는것을 확인할수 있음
'backend > 코프링' 카테고리의 다른 글
[코프링] 12. Render 무료 호스팅서버에 Spring boot + Kotlin 배포하기 (1) | 2025.02.14 |
---|---|
[코프링] 11. Render 무료 호스팅서버 Postgres 데이터베이스 생성 (0) | 2025.02.14 |
[코프링] 10. application.yml 운영, 로컬 분리하기, postgres 설정 (1) | 2025.02.14 |
[코프링] 9. Spring Kotlin Jpa Querydsl Security Jwt 적용 (1) | 2025.02.11 |
[코프링] 8. Companion Object - 팩토리 메서드 패턴 설정 (0) | 2025.02.10 |