logo
한달 포트폴리오 멘토링
블로그

목적

  • 개발 환경과 Product 실행 환경을 분리하기 위해서 사용
    • ex) 로컬 개발환경에서는 h2 데이터베이스를 사용하고, 실제 배포환경에서는 postgres db를 사용하는 경우
    • ex) 보안 파일이나 암호를 모든 개발자에게 공개할 수 없는 경우
    • ex) 로컬 개발환경에서는 oauth2 토큰 없이 로그인, 실제 배포환경에서는 토큰을 포함해서 로그인을 할 경우

Profile이란

  • Spring 실행 환경을 Profile이라 한다. Profile에 따라 다른 설정과, 다른 Bean을 주입할 수 있다.

properties 파일 분리하기

  • application-{개발환경}.properties를 만든다.
  • application.properties에는 기본으로 사용할 개발환경을 넣어준다.
  • ex) local에서는 h2 db, prod 에서는 postgres를 사용할 경우
  • ex) application.properties
# active profile spring.profiles.active=local # common JPA update option spring.jpa.show-sql=true

-> 기본 개발환경을 spring.profiles.active 에 넣어준다 여기에선 local로 정의하였다.

  • application-local.properties
# active profile # JPA Driver spring.jpa.database-platform=org.hibernate.dialect.H2Dialect # h2 connection info spring.datasource.url=jdbc:h2:mem:heroku spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= # h2 option spring.h2.console.enabled=true spring.h2.console.path=/h2-console spring.jpa.hibernate.ddl-auto=update
  • application-prod.properties
# JPA Driver spring.jpa.hibernate.dialect = org.hibernate.dialect.PostgreSQL10DialectDialect # Postgresql connection info spring.datasource.url=${DB_URL} spring.datasource.username=${DB_USER} spring.datasource.password=${DB_PASSSWORD} spring.jpa.hibernate.ddl-auto=none

**${} 를 통해 환경 변수를 읽어 올 수도 있다. 이를 통해 서버쪽 PASSWORD를 개발자들은 모르게 할 수 있다. **

yaml 사용시

  • 기본적으로 properties와 동일한 방식으로 사용하나, on-profile options을 넣어준다.
# application-local.yml profile spring: profiles: activate: on-profile: local
# application-prod.yml profile spring: profiles: activate: on-profile: prod
  • ---으로 구분하여 하나의 파일로 합칠 수도 있다.
spring: profiles: active: local --- spring: profiles: activate: on-profile: local local 환경 옵션 추가 --- spring: profiles: activate: on-profile: prod prod 환경 옵션 추가

실행시 Profile 변경하기

java -Dspring.profile.active=prod -jar project.jar

-Dspring.profile.active=prod 를 추가해주면 profile이 prod로 변경된다. 다른 옵션들도 D{propertiesName}={value} 으로 변경할 수 있다.

Profile에 따른 Bean 로딩하기

  • @Profile 을 통해 특정 프로파일에서만 동작하는 Bean 을 설정할 수 있다.
  • @Component, @Bean, @Configuration 등 Bean 생성하는 곳에 설정하면 특정 Profile에만 생성하게 만들 수 있고, Security 설정도 @Profile을 통해 분리할 수 있다.
  • 예제는 prod 환경에서만 Redis Session을 사용하는 예제이다. @EnableRedisHttpSession이 prod에만 적용되기 떄문에 로컬에서는 memory session , 개발환경에서는 Redis Session을 사용할 수 있다.
@Profile("prod") @Configuration @EnableRedisHttpSession class RedisConfig { @Bean public LettuceClientConfigurationBuilderCustomizer lettuceClientConfigurationBuilderCustomizer() { return clientConfigurationBuilder -> { if (clientConfigurationBuilder.build().isUseSsl()) { clientConfigurationBuilder.useSsl().disablePeerVerification(); } }; } @Bean public static ConfigureRedisAction configureRedisAction() { return ConfigureRedisAction.NO_OP; } }

@Profile 을 통해 특정 profile일때만 생성되는 Bean을 지정할 수 있다. 해당 샘플에서는 prod의 경우에서만 FirebaseConfig를 생성하게 하였다.

코드에서 Profile 읽기

Environments 객체를 통해 activeProfile을 알아낼 수 있다.

private String activeProfile; private final UserService userService; @Autowired public UserController(UserService userService, Environment environments) { this.userService = userService; this.activeProfile = environments.getActiveProfiles()[0]; log.info("activeProfile: {}", activeProfile); } @PostMapping("") public User signup(@RequestBody SignupDTO signupDTO, @RequestHeader("Authorization") String authorization) { String token = RequestUtil.getAuthorizationToken(authorization); if(activeProfile.equals("local")) { return userService.signupMock(signupDTO, token); } else { return userService.signup(signupDTO, token); } }

샘플 코드

https://github.com/Couch-Coders/heroku-sample 에서 로컬환겨에서는 h2, 배포시 postgres를 사용하는 예제를 볼 수 있다.

PortfolioAD
관련있는 글

couchcoding

2022-12-07

Firebase로 Google 로그인 구현하기 2 (Spring 파트)

이전 포스팅에 이어 구글 로그인응 이용하기 위하여 Java Backend(SpringBoot)를 통해 Resource Service를 구현하는 것을 배워보겠습니다. 예제는 자바로 진행하나 구조를 익히면 다른 백엔드 프레임워크에서도 사용할 수 있을 것입니다. ...

백엔드

spring
react
firebase
firebase auth
Oauth
JWT
SNS 로그인

couchcoding

2022-12-07

Spring Security (1) - 구조와 동작 방식

Spring Security는 Spring Application 개발시에 보안을 적용하기 위해 사용하는 보안 프레임워크 입니다. Spring Security는 웹 보안을 위하여 인증 및 보안 관련 로직을 제공합니다. 특히 Spring Security의 가장 중요한 기...

백엔드

spring
spring security
filter
보안
로그인

couchcoding

2022-12-07

[Spring] QueryDSL로 조건검색 API를 만들어보자(동적 쿼리)

조건 검색을 만들기 위해서 QueryDSL이라는 라이브러리를 사용하려고 합니다. QueryDSL은 JPA만으로는 복잡한 쿼리를 만들기 어렵고 JPQL과 같이 직접 SQL을 사용하는 방식은 SQL을 실행 전까지는 SQL을 검증할 수 없어 오류가 생기기 쉽습니다. ...

백엔드

spring
JPA
QueryDSL
조건 검색
동적 쿼리

couchcoding

카우치코딩 공식 계정입니다.