SPRING/스프링프레임워크 핵심개념
Environment - 프로파일
JUMP개발자
2021. 5. 14. 00:02
Environment : Application 환경을 나타내는 Interface로 Profile과 Property가 있다.
프로파일
profile은 Bean들의 그룹이라고 할 수있다.
각기 다른 환경에 따라 다른 Bean들을 사용해야 하는 경우에 프로파일을 사용하면 유용하다.
ex : Test 환경, 배포 환경에 따라 다른 빈들을 사용해야 하는 경우
@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()));
}
}
public interface BookRepository {
}
public class TestBookRepository implements BookRepository{
}
위와 같이 Bean등록을 하지 않을 상태에서 스프링어플리케이션을 실행하면 에러가 발생한다.
-> Consider defining a bean of type 'com.beanscope.demo.BookRepository' in your configuration.
@Configuration
@Profile("test")
public class TestConfiguration {
@Bean
public BookRepository bookRepository() {
return new TestBookRepository();
}
}
test프로파일 환경에서만 동작하는 환경설정 파일을 생성하고, active Profile을 등록하면 에러가 빈이 주입된다.

Bean설정파일을 별도로 생성하여 등록하는 것외에 아래와 같이 Profile을 설정할 수 있다.
@Repository
@Profile("test")
public class TestBookRepository implements BookRepository{
}
프로파일 활성화 방법
1. Edit configuration -> Active profiles -> Profile명 입력
2. Edit configuration -> VM options -> -Dspring.profile.active="test" 입력