파란하늘의 지식창고
반응형

AutoConfiguration bean 생성 순서에 따른 @ConditionalOnBean 조건 오류 문제

아래와 같은 경우가 있었다.

@Configuration
public class SampleAAutoConfiguration {

    @Bean
    public SomeAClass SomeAClass() {
    	return new SomeAClass();
    }
}

@Configuration
public class SampleBAutoConfiguration {

    @Bean
    @ConditionalOnBean(SomeAClass.class)
    public SomeBClass someBClass() {
    	return new SomeBClass();
    }
}

코드 상으로 보면 SampleBConfiguration의 SomeAClass가 있으니까 당연히 생성이 될 줄 알았다.

하지만 이 어플리케이션을 실행해보면 생성이 안되는 경우가 발생한다.

 

debug=true

위 옵션을 추가하고 spring boot report를 활성화 하여 확인해보면 SampleBAutoConfiguration은 활성화되었지만 SampleBAutoConfiguration의 someBClass method는 @ConditionalOnBean 조건이 맞지 않아 비활성화 되었다고 나와있다.

이유는 각 Spring Boot AutoConfiguration bean이 생성될 때 의존성을 확인하고 bean 생성 순서를 재정렬하지만 @ConditionalOnBean annotation 조건에 대해서는 의존성을 확인하지 않아 재정렬이 되지 않아서이다.

따라서 위의 설정은 아래처럼 각 AutoConfiguration 간 순서를 지정해주어야 올바르게 동작한다.

@Configuration
public class SampleAAutoConfiguration {

    @Bean
    public SomeAClass SomeAClass() {
    	return new SomeAClass();
    }
}

@Configuration
@AutoConfigureAfter(SampleAAutoConfiguration.class)
public class SampleBAutoConfiguration {

    @Bean
    @ConditionalOnBean(SomeAClass.class)
    public SomeBClass someBClass() {
    	return new SomeBClass();
    }
}

 

반응형
profile

파란하늘의 지식창고

@Bluesky_

내용이 유익했다면 광고 배너를 클릭 해주세요