@Profile
은 Spring Framework의 어노테이션으로, 애플리케이션의 설정을 다양한 환경에서 다르게 구성할수 있게 도와줌. 이를 통해 개발, 테스트, 프로덕션 등 서로 다른 환경에서 서로 다른 빈(Bean)을 로드하거나 활성화할 수 있음
📌 @Profile 어노테이션의 주요 용도
- 환경에 따른 빈 등록 : 특정 프로파일이 활성화된 경우에만 빈이 등록되도록 설정할 수 있습니다. 예를 들어, 개발 환경과 프로덕션 환경에서 서로 다른 데이터베이스 설정을 사용할 수 있음.
- 환경 별 구성 분리 : 코드베이스에서 서로 다른 환경의 설정을 분리하여 관리할 수 있어, 유지보수와 테스트가 용이해짐
👉 사용법
- 프로파일 정의하기
application.properties
또는 appliaction.yml
파일에서 사용할 프로파일을 정의할 수 있음. 여러 프로파일을 지정할 때는 쉼표로 구분함
# application.properties
spring.profiles.active=dev
spring:
profiles:
active: dev
@Profile
어노테이션 사용하기
빈(Bean) 클래스나 메서드에 @Profile
어노테이션을 붙여서 특정 프로파일이 활성화된 경우에만 빈을 등록할 수 있음.
@Configuration
@Profile("dev")
public class DevConfig {
@Bean
public DataSource dataSource() {
return new newDataSource();
}
}
@Configuration
@Profile("prod")
public class ProdConfig {
@Bean
public DataSource dataSource() {
return new DBDateSource();
}
}
@Profile
어노테이션과 함께 @Component
, @Service
, @Repository
사용하기
특정 컴포넌트가 프로파일에 따라 로드되도록 설정할 수 있음
@Component
@Profile("test")
public class TestService {
}
- 테스트에서 프로파일 사용하기
테스트 클래스에서 @ActiveProfile
어노테이션을 사용하여 특정 프로파일을 활성화할 수 있음
@SpringBootTest
@ActivePrfiles("test")
public class MyServiceTest {
}