How to tell spring to only load the needed beans for the JUnit test?

SandMan picture SandMan · Aug 18, 2016 · Viewed 22.8k times · Source

A simple question that might have an advanced answer.

The Question: My question is, is there a way to instantiate only the classes, in your application context, needed for that specific JUnit test ?

The Reason: My application context is getting quite big. I also do a lot of integration tests so you I guess you would understand when I say that every time I run a test all the classes in my application context get instantiated and this takes time.

The Example:

Say class Foo inject only bar

public class Foo {

@Inject
Bar bar;

@Test
public void testrunSomeMethod() throws RegisterFault {
    bar.runSomeMethod();
}

but the application context has beans foobar and bar. I know this is not a vaild application context but rest assure all my code works.

<beans>
     <bean id="foobar" class="some.package.FooBar"/>
     <bean id="bar" class="some.package.Bar"/>
<beans>

So how do I tell spring to only instantiate Bar and ignore FooBar for the test class foo.

Thank you.

Answer

Deepak picture Deepak · May 2, 2017

Consider adding default-lazy-init="true" to your spring context xml beans tag (or add lazy-init="true" to those specific beans that take a long time starting up). This will ensure that only those beans are created that called with applicationContext.getBean(class-or-bean-name) or injected via @Autowired / @Inject into your tests. (Some other types of beans like @Scheduled beans will be created nevertheless but you need to check if that's a problem or not)

(if you use spring Java configuration, add @Lazy to the config files)

Caveat - If there is a bean that is not initialized explicitly with applicationContext.getBean() or injected as a dependency used by the bean obtained by using applicationContext.getBean(), then that bean will NO LONGER be constructed or initialized. Depending upon your application, that can cause things to fail OR not. Maybe you can selectively mark those beans as lazy-init="false"