0

In my unit tests I want to configure Spring in code (API, Annotations) so they will not depend on bean configuration files.

Can this be done?

For example:

Class Dependency {}

Class A
{
    @AutoWired
    Dependency d;
}

When testing A, I want to be able to create an instance of it with the Dependency member resolved, without having to use configuration files.

Thank you!

4

3 回答 3

1

简而言之,是的,您可以使用org.springframework.context.support.AbstractApplicationContext的任何实现来启动 spring 应用程序上下文。也就是说,如果您不想从 XML 文件加载定义,您可以使用org.springframework.context.support.StaticApplicationContextorg.springframework.context.support.GenericApplicationContext来启动上下文。

实例化上下文后,您可以开始使用 BeanFactory 创建 bean,无论是选择的默认上下文还是自定义上下文,都可以满足您的需求。

在实践中,它的工作量远不止于此。如果您只使用纯 XML 配置会更容易,但也可以做到。

于 2012-08-21T06:17:00.440 回答
0

您可以使用Java 配置而不是 XML 配置。

于 2012-08-21T06:14:25.433 回答
0

您可以使用AnnotationConfigApplicationContext以编程方式创建应用程序上下文,而无需 bean 配置文件。

于 2012-08-21T06:17:29.307 回答