简体   繁体   中英

Spring JUnit test runner @ContextConfiguration just loading a single file

I'm loading a spring bean from a test class using the bean factory

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?

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.

Spring Documentation sample:

<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. The lazy-initialized bean is injected into a singleton bean elsewhere that is not lazy-initialized.

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. In your test, just use the layer you're interested in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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