如何解决此 Bean 定义覆盖?



我已经从Spring Boot 1.5升级到Spring Boot 2.1.8。 我有一些测试有效,但现在失败了。 我也在 2.9 版中使用了 maven-surefire 插件并且它有效,但如果这很重要,我也将其升级到 2.22.0。

@ExtendWith(SpringExtension.class)
@WebMvcTest(value = ElementController.class, secure = false)
@ContextConfiguration(classes = TestSite1Config.class)
public class ElementControllerSite1IT {
@Autowired
protected MockMvc mvc;
@MockBean
ElementService elementService;
@BeforeEach
public void setup() {
when(elementService.getElementTable( ... )) //skipping args for brevity
.thenReturn(new ElementTable());
}
@Configuration
public static class TestSite1Config {
@Bean
@Autowired
public ElementController elementController(final ElementService elementService) {
return new ElementController(elementService, new ElementControllerProperties(DeploymentLocation.SITE1));
}
@Test
public void failSite1ValidationWithoutId() throws Exception {
ElementParameters params = getParams(false);
mvc.perform(post("/element")
.contentType(JSON)
.andExpect(status().isBadRequest());
}
//more tests, but doesn't matter.
}

还有另一个类似上面的类,但将Site1替换为Site2。

还有一个ElementController&Service类。

我得到这个异常:

Caused by BeanDefinitionOverrideException: Invalid bean definition with name 'elementController' defined in class path resource [ui/v2/web/ElementControllerSite1IT$TestSite1Config.class]: Cannot register bean definition [Root bean: class [null]; ... defined in class path resource [ui/v2/web/ElementControllerSite1ITConfig.class] for bean 'elementController': There is already [Generic bean: class [ui.v2.web.ElementController]; .. defined in file [...ui/v2/web/ElementController.class]] bound.

我没有编写测试,而是我继承的代码,在我刚刚被假脱机的代码库中。

你可以试试@TestPropertySource(properties ="..."

@ExtendWith(SpringExtension.class)
@WebMvcTest(value = ElementController.class, secure = false)
@ContextConfiguration(classes = TestSite1Config.class)
@TestPropertySource(properties = {"spring.main.allow-bean-definition-overriding=true", "local.server.port=7777"})
public class ElementControllerSite1IT {
...
}

spring.main.allow-bean-definition-overriding=true添加到 application.properties

得到它处理这个:(对于任何偶然发现这个问题的人(

@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@WebMvcTest
@ContextConfiguration(classes = {ElementController.class,TestSite1Config.class})
public class ElementControllerSite1IT {
@Autowired
private MockMvc mvc;
...
@Configruation
public static class TestSite1Config {
@Bean
@Primary
public ElementControllerProperties elementControllerProperties() { return ... }
}
...
}

最新更新