gpt4 book ai didi

java - spring 的无 XML 配置

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:16:49 24 4
gpt4 key购买 nike

我有以下用于非网络应用程序的配置 bean

@Configuration
public class MyBeans {

@Bean
@Scope(value="prototype")
MyObject myObject() {
return new MyObjectImpl();
}
}

在另一边我有我的课

public class MyCommand implements Command {

@Autowired
private MyObject myObject;

[...]

}

如何在不使用 XML 的情况下使 myCommand 与 MyBeans 中的配置 Autowiring ,以便我可以在我的其他测试类中注入(inject)模拟?

非常感谢。

最佳答案

对于基于 XML 的配置,您将使用 ContextConfiguration 注释。但是,ContextConfiguration 注释似乎不适用于 Java Config。这意味着您必须回退到在测试初始化​​中配置您的应用程序上下文。

假设 JUnit4:

@RunWith(SpringJUnit4ClassRunner.class)
public class MyTest{

private ApplicationContext applicationContext;

@Before
public void init(){
this.applicationContext =
new AnnotationConfigApplicationContext(MyBeans.class);

//not necessary if MyBeans defines a bean for MyCommand
//necessary if you need MyCommand - must be annotated @Component
this.applicationContext.scan("package.where.mycommand.is.located");
this.applicationContext.refresh();

//get any beans you need for your tests here
//and set them to private fields
}

@Test
public void fooTest(){
assertTrue(true);
}

}

关于java - spring 的无 XML 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6071467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com