我对 Spring 基于注解的配置感到困惑。
我有一个接口(interface) MyInterface 和两个实现此接口(interface)的类(MyClass1 和 MyClass2)。
@Component("MyInterface")
public class MyClass1 implements MyInterface {
public void execute() {
System.out.println("MyClass1 executed");
}
}
public class MyClass2 implements MyInterface {
public void execute() {
System.out.println("MyClass2 executed");
}
}
MyClass1是使用Component-Scan创建的,MyClass2定义为一个bean:
@Configuration
@ComponentScan(basePackageClasses = MyClass1Configuration.class)
public class MyClass1Configuration {
}
@Configuration
public class MyClass2Configuration {
@Bean(name = "MyInterface")
public MyInterface myClass2() {
return new MyClass2();
}
}
我使用 Spring Test 的 ContextConfiguration 注释构建应用程序上下文:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyClass1Configuration.class, MyClass2Configuration.class})
public class SpringTestCase1 {
@Autowired
private MyInterface myInterface;
@Test
public void testMethod() {
System.out.println("testMethod invoked");
Assert.assertEquals(MyClass2.class, myInterface.getClass());
myInterface.execute();
}
}
不幸的是,测试失败了,因为 Class1 是 Autowiring 的,而不是 Class2。预期的行为是 MyClass2Configuration 覆盖由 MyClass1Configuration 定义的 bean。我有什么错。
我在 GitHub 上创建了这个示例,如果您想看一下工作示例: https://github.com/OLibutzki/spring-test-configuration/tree/master/simple-sprint-test
感谢您的帮助。
亲切的问候 奥利弗
最佳答案
或者您可以使用覆盖它
spring.main.allow-bean-definition-overriding=true
在主/资源/application.properties
但它容易出错
关于spring - 覆盖 bean 定义不能按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31476848/