관리 메뉴

나만의공간

[Spring Batch] Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true 오류 해결 본문

IT/Spring

[Spring Batch] Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true 오류 해결

밥알이 2023. 9. 5. 09:08

스프링배치를 실행할려고 하니 아래와 같은 오류가 나타나 해결 방법을 찾으니 스프링 2.1버전부터는 Overrriding의 default값이 false로 나와서 생기는 오류라고 합니다.

Spring Bean은 ApplicationContext내에서 이름으로 식별됩니다.
따라서 Bean Overriding은 다른 Bean과 같은 이름을 가진 ApplicationContext내에서 Bean을 정의할 때 발생하는 기본 동작입니다.
이름이 충돌하는 경우 이전 빈을 간단히 대체하여 작동합니다.

Spring5.1부터 개발자가 예기치 않은 Bean 재정의를 방지하기 위해 예외를 자동으로 throw할 수 있도록 BeanDefinitionOverrideException이 도입되었습니다.
기본적으로 Bean 재정의를 허용하는 원래 동작을 계속 사용 할 수 있습니다.

충돌하는 Bean 테스트

@Configuration
public class TestConfiguration1 {

    class TestBean1 {
        private String name;

        // standard getters and setters

    }

    @Bean
    public TestBean1 testBean(){
        return new TestBean1();
    }
}
@Configuration
public class TestConfiguration2 {

    class TestBean2 {
        private String name;

        // standard getters and setters

    }

    @Bean
    public TestBean2 testBean(){
        return new TestBean2();
    }
}

위 두개 Bean을 테스트 하는 코드

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {TestConfiguration1.class, TestConfiguration2.class})
public class SpringBootBeanDefinitionOverrideExceptionIntegrationTest {

    @Test
    public void whenBeanOverridingAllowed_thenTestBean2OverridesTestBean1() {
        Object testBean = applicationContext.getBean("testBean");

        assertThat(testBean.getClass()).isEqualTo(TestConfiguration2.TestBean2.class);
    }
}

테스트 코드를 실행하면 아래와 같은 오류가 발생합니다.

Invalid bean definition with name 'testBean' defined in ... 
... com.baeldung.beandefinitionoverrideexception.TestConfiguration2 ...
Cannot register bean definition [ ... defined in ... 
... com.baeldung.beandefinitionoverrideexception.TestConfiguration2] for bean 'testBean' ...
There is already [ ... defined in ...
... com.baeldung.beandefinitionoverrideexception.TestConfiguration1] bound.

해결책

application.yml에 아래 옵션을 추가 하거나 Bean 이름을 변경합니다.

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

 

Comments