BackEnd/스프링

@Profile 대신 @ConditionalOnProperty 을 사용하라

ssseung 2022. 8. 3. 14:34

 

@Profile("local") 와 같은 사용은 

코드가 string 으로 정의한 Profile 에 의존하게 하며, 여기저기 퍼진 Profile 정의는

1. String 정의가 변경이 됐을 때 텍스트로 코드 전체 검색을 통해 수정을 해야한다.

2. 특정 환경에서 애플리케이션이 어떤 코드로 동작하는지 파악하기 어렵다.

3. test, h2, prod 등 여러 환경과 활성화시킬 데이터 베이스 등이 Profile로 정의되면

특정 profile 활성화, 비활성화 여부나 멀티 profile 활성화 시에 애플리케이션의 동작방식을

파악하기 어렵다.

4. @Profile("!test") 같은 코드까지 섞여있다면 더 파악하기 어려워질 수 있다.

 

그래서 Profile 대신에 

application-{profile}.yml/properties 파일을 보면  한눈에 애플리케이션이 어떻게 동작할지 예상가능하게 해준다.

 

@Configuration 파일에 정의한 빈 

upload.service 값이 havingValue 에 정의한 값과 동일할 때만 해당 클래스를 빈으로 등록해준다.

 @Bean
    @ConditionalOnProperty(prefix = "upload", name = "service", havingValue = "local")
    public UploadService DiskUploadServiceImpl(){
        return new DiskUploadServiceImpl(fileUtil);
    }

    @Bean
    @ConditionalOnProperty(prefix = "upload", name = "service", havingValue = "aws")
    public UploadService AWSUploadServiceImpl(){
        return new AWSUploadServiceImpl(amazonS3Client,fileUtil);
    }
}

 

application-prod.properties 

upload.service=aws

 

 

https://reflectoring.io/dont-use-spring-profile-annotation/

 

Don't Use the @Profile Annotation in a Spring Boot App!

Why using Spring's @Profile annotation is a bad idea and what to do instead.

reflectoring.io

https://www.baeldung.com/spring-conditionalonproperty

 

The Spring @ConditionalOnProperty Annotation | Baeldung

Learn all about the Spring @ConditionalOnProperty annotation.

www.baeldung.com

 

반응형