简体   繁体   English

Spring JUnit测试运行器@ContextConfiguration只是加载一个文件

[英]Spring JUnit test runner @ContextConfiguration just loading a single file

I'm loading a spring bean from a test class using the bean factory 我正在使用bean工厂从测试类加载一个spring bean

XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("my-bean-file.xml"))
MyBean bean = (MyBean) factory.getBean("myBean")

Can I use the Spring JUnit4TestRunner to load individual beans or is that only used to load an entire application context? 我可以使用Spring JUnit4TestRunner加载单个bean,还是仅用于加载整个应用程序上下文?

If you want to do this because your beans are too expensive to be all loaded, you could declare them lazy, meaning they will only be loaded when needed. 如果你想这样做是因为你的bean太昂贵而无法全部加载,你可以声明它们是懒惰的,这意味着它们只会在需要时加载。

Spring Documentation sample: Spring Documentation示例:

<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>

<bean name="not.lazy" class="com.foo.AnotherBean"/>

However, when a lazy-initialized bean is a dependency of a singleton bean that is not lazy-initialized, the ApplicationContext creates the lazy-initialized bean at startup, because it must satisfy the singleton's dependencies. 但是,当延迟初始化的bean是未进行延迟初始化的单例bean的依赖项时,ApplicationContext会在启动时创建延迟初始化的bean,因为它必须满足单例的依赖关系。 The lazy-initialized bean is injected into a singleton bean elsewhere that is not lazy-initialized. 惰性初始化的bean被注入到其他地方的单独的bean中,而这个bean并不是惰性初始化的。

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-lazy-init http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-lazy-init

It will load the entire application context. 它将加载整个应用程序上下文。 But you can split up your bean files (eg into DAOs, service layer, controllers), and in your main app include each file once. 但是您可以将bean文件拆分(例如分成DAO,服务层,控制器),并在主应用程序中包含每个文件一次。 In your test, just use the layer you're interested in. 在您的测试中,只需使用您感兴趣的图层。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM