본문 바로가기

Spring/Spring

(SPRING) IoC 컨테이너 - Environment_프로파일

ApplicationContext는 BeanFactory 기능만 하는것이 아니다.

여러가지 다른 기능들을 제공

 

ApplicationContext의 프로파일

Bean들의 묶음(그룹)이다.

특정 환경에는 해당 환경에 맞는 Bean들의 사용을 정의

Environment의 역할은 활성화할 프로파일 확인 및 설정


Runner에 Environment를 가져와서 등록되어있는 프로파일을 출력

@Component
public class AppRunner implements ApplicationRunner {

    @Autowired
    ApplicationContext ctx;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Environment environment = ctx.getEnvironment();
        System.out.println(Arrays.toString(environment.getActiveProfiles()));
        System.out.println(Arrays.toString(environment.getDefaultProfiles()));
    }
}


특정 profile일때만 등록되는 Bean 만들기

 

BookRepository 인터페이스 생성

public interface BookRepository {
}

TestBookRepository 구현 클래스 생성

public class TestBookRepository implements BookRepository{
}

 

test profile일때만 해당 Bean 설정파일이 적용이 된다.

@Configuration
@Profile("test")
public class TestConfiguration {
    @Bean
    public BookRepository bookRepository() {
        return new TestBookRepository();
    }
}

 

만약 BookRepository를 주입받는다면?

@Component
public class AppRunner implements ApplicationRunner {

    @Autowired
    ApplicationContext ctx;
    
    @Autowired
    BookRepository bookRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Environment environment = ctx.getEnvironment();
        System.out.println(Arrays.toString(environment.getActiveProfiles()));
        System.out.println(Arrays.toString(environment.getDefaultProfiles()));
    }
}

실행 결과 에러 발생


프로파일 설정 방법

Edit Configuration에서 프로 파일을 활성화 시킨다.

 

Edit Configuration 설정 및 정상종료 확인

Active profiles가 없는경우 VM 옵션에 하위와 같이 설정하면 된다.

Dspring.profiles.avtive=”test,A,B,...


TestConfiguration 삭제 후 좀 더 나은 방법으로 개선

 

TestBookRepository를 애노테이션을 주어 Bean으로 등록하고 Profile을 설정한다.

@Repository
@Profile("test")
public class TestBookRepository implements BookRepository{
}

실행결과 정상

@Component에도 동일하게 적용될 수 있다.

 

VM 옵션을 제거하고 ! 을 이용해 설정하는 방법

@Repository
@Profile("!prod")
public class TestBookRepository implements BookRepository{
}

프로파일 표현식 

  • ! (not) 
  • & (and) 
  • | (or)

https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-definition-profiles

 

Core Technologies

In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do

docs.spring.io