Java/Spring framework

Spring framework core (4) - Environment

감동이중요해 2020. 1. 12. 22:17

IoC Container - Spring Environment

Environment는 Profile, Property를 다루는 Interface이다.

Profile

Bean의 그룹

  • Spring은 다양한 profile을 정의할 수 있으며 사용하는 profile에 따라 다른 bean을 불러와 사용할 수 있다.
  • @Profile("profile_name") 으로 지정한다.

Profile은 단순하게 이름만으로도 사용할 수 있지만 기술 문서에는 아래와 같은 옵션도 지원한다고 기술되어 있다.

  • ! : A logical "not" of the profile
  • & : A logical "and" of the profiles
  • | : A logical "or" of the profiles

@Profile("!dev") 인 경우 dev profile이 아닐 때만 사용한다는 의미이다.

Profile example

test, dev profile을 정의한다.

각 profile을 사용하는 클래스에서 myProfile이라는 이름의 String bean을 생성하고 AppRunner에서 현재 profile을 출력한다.

  1. DevProfile

     @Component @Profile("dev")
     public class DevProfile {
         @Bean(name = "myProfile")
         public String myProfile() {
             return "DEV";
         }
     }
  2. TestProfile

     @Component
     @Profile("test")
     public class TestProfile {
         @Bean(name = "myProfile")
         public String myProfile() {
             return "TEST";
         }
     }
  3. AppRunner

     @Component
     public class AppRunner implements ApplicationRunner {
         @Resource(name = "myProfile")
         private String myProfile;
    
         @Override
         public void run(ApplicationArguments args) throws Exception {
             System.out.println(myProfile);
         }
     }
  • Resource는 bean의 이름으로 가져오기 위해 사용했다.

위와 같이 작성하면 준비가 다 끝난 것이다.

Spring boot 앱을 실행시킬 때 VM 옵션을 부여할 수 있으며,

profile은 -Dspring.profiles.active 으로 활성화 시킬 수 있다.

Eclipse나 IntelliJ는 Run Configuration라는 메뉴에서 VM option을 사용한다.

-Dspring.profiles.active="dev" 을 기입하고 앱을 실행하면 DEV가 출력된다.

Property

key-value으로 값을 설정하고 Application을 정의할 수 있는 Spring의 요소

  • Spring boot에서는 src/resources 아래에 기본적으로 application.properties 가 생성된다. 이 파일에 property를 정의할 수 있다.

  • Property는 파일을 생성하여 사용할 수도 있고, VM option으로 주어도 가능하다. 물론 두 가지 방법을 동시에 적용해도 동작한다.

Property Example

파일 정의와 VM option을 다 사용해보도록 한다.

  1. application.properties

     property1=property11
  2. VM options

    -Dproperty2="property22"

  3. AppRunner

     @Component
     public class AppRunner implements ApplicationRunner {
    
         @Value("${property1}") String property1;
         @Value("${property2}") String property2;
    
         @Override
         public void run(ApplicationArguments args) throws Exception {
             System.out.println(property1);
             System.out.println(property2);
         }
     }

결과

property11
property22

작성한 소스 코드 전체는 아래 링크에서 확인해볼 수 있다.

https://github.com/dhmin5693/Spring-core-study/tree/master/Environment