Java/Spring Boot

[Spring Boot] 프로파일

hh_lin 2022. 3. 13. 16:37

1. 프로파일

  • Spring Framework에서 제공해주는 기능
  • 특정한 Profile에서만 특정한 Bean을 등록하고 싶다거나
    어플리케이션의 동작을 특정 Profile에서만 다르게 하고 싶을 때 사용

 

 

# Profile("prod")

@Profile("prod")
@Configuration
public class BaseConfiguration {

   @Bean
   public String hello() {
      return "hello";
   }

}

-> 이 Bean 설정파일 자체가 "prod" 라는 profile일 때 사용이 됨

 

 

 

# HumanRunner

@Component
public class HumanRunner implements ApplicationRunner {

   @Autowired
   private String hello;

   @Override
   public void run(ApplicationArguments args) throws Exception {
      System.out.println("================");
      System.out.println(hello);
      System.out.println("================");
   }
}

 

-> 이 상태로 실행하면 에러 발생 (String type의 Bean을 찾을 수 없음)

프로파일 활성화하고 실행하면 정상처리 됨

 

 

 

 

 

 

 

 

2. 프로파일 활성화

# application.properties

spring.profiles.active=prod

-> spring.profiles.active로 어떤 프로파일을 활성화할 것인지 명시해줘야 함

 

 

 

 

 

 

 

 

3. 프로파일용 프로퍼티 : application-{profile}.properties 

ex) application-prod.properties

-> 프로파일 관련된 properties가 기본적인 application.properties보다 우선순위가 높음

 

@Component
public class HumanRunner implements ApplicationRunner {

   @Autowired
   private String hello;
   
   @Autowired
   private HumanProperties humanProperties;
   
   @Override
   public void run(ApplicationArguments args) throws Exception {
       System.out.println("================");
       System.out.println(hello);
       System.out.println(humanProperties.getName());
       System.out.println("================");
   }
}

 

 

# application.properties

human.name = Hyelin
spring.profiles.active=prod

 

 

# application-prod.properties

human.name=prod!

 

 

# 실행 결과

 

 

 

 

 

 

 

 

4. 프로파일 추가 : spring.profiles.include

-> spring.profils.include 설정에 적힌 프로파일도 활성화하라는 의미

 

 

2.4 버전 이상부터는 include 대신에 group을 사용해야 함

 

 

# application.properties

spring.profiles.group.prod=proddb

-> application-prod.properties가 아닌 application.properties에 명시해야 함

 

 

# application-proddb.properties

human.fullName = hdhdlss

 

 

# 실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard

 

스프링 부트 개념과 활용 - 인프런 | 강의

스프링 부트의 원리 및 여러 기능을 코딩을 통해 쉽게 이해하고 보다 적극적으로 사용할 수 있는 방법을 학습합니다., - 강의 소개 | 인프런...

www.inflearn.com

https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.profiles

 

Core Features

Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources, include Java properties files, YAML files, environment variables, an

docs.spring.io

https://github.com/mindock/spring-boot-practice/wiki/4%EC%A3%BC%EC%B0%A8-%EC%8A%A4%ED%84%B0%EB%94%94

 

GitHub - mindock/spring-boot-practice

Contribute to mindock/spring-boot-practice development by creating an account on GitHub.

github.com