FrameWork/Spring&Spring-boot

Spring 기본 20 - 중복 등록과 충돌

Surge100 2023. 11. 14. 15:28

중복 등록과 충돌

컴포넌트 스캔에서 같은 빈 이름을 등록하려면 어떻게 될까?

 

수 빈 등록 vs 자동 빈 등록

  • 컴포넌트 스캔에 의해 자동으로 스프링 빈이 등록되는데, 그 이름이 같은 경우 스프링은 오류를 발생시킨다.
    • ConflictingBeanDefinitionException 예외 발생

 

수 빈 등록 vs 자동 빈 등록

만약 수동 빈 등록과 자동빈 등록에서 빈 이름이 충돌이 되면 어떻게 될까?

@Component
public class MemoryMemberRepository implements MemberRepository{}

 

@Configuration
@ComponentScan{
	excludeFilter = @Filter(type = Filtertype.ANNOTATION, classes = Configuration.class)
}

public class AutoAppConfig{
    
    @Bean(name = "memmoryMemberRepository")
    public MemberRepository memberRepository(){
    	return new MemoryMemberRepository();
    }
}

 

위와 같은 코드를 autoScan해서 스프링 컨테이너에 빈이 등록 될 때 수동 빈 등록이 우선권을 가진다. (수동 빈이 자동으로 빈을 오버라이딩 해버린다.)

 

수동 빈 등록 과 자동 빈 등록이 충돌해서  *수동 빈이 등록되었을 시* 남는 로그

 

물론 개발자가 의도적으로 이런 결과를 기대했다면, 자동 보다는 수동이 우선권을 가지는 것이 좋다. 하지만 현실은 개발자가 의도적으로 설정해서 이런 결과가 만들어지기 보다는 여러 설정들이 꼬여서 이런 결과가 만들어지는 경우가 대부분

➡️ 그러면 정말 잡기 어려운 버그가 만들어진다.(항상 잡기 어려운 버그는 애매한 버그)

그래서 최근 스프링 부트에서는 수동 빈 등록과 자동 빈 등록이 충돌나면 오류가 발생하도록 기본 값을 바꾸었다.

 

수동 빈 등록 과 자동 빈 등록이 충돌시 CoreApplication을 실행하면 오류가 발생한다.

⛔Spring-boot 에러 로그

Description
: The bean 'memoryMemberRepository', defined in class path resource [com/hello/core/AutoAppConfig.class], could not be registered. A bean with that name has already been defined in file [C:\Users\***\****\hello\out\production\classes\com\hello\core\member\MemoryMemberRepository.class] and overriding is disabled.


Action: Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

 

application.properties

spring.main.allow-bean-definition-overriding=true

 

 

[출처 - 스프링 핵심 원리 - 기본편]