Steve
Steve

Reputation: 4691

Spring configuration in test overriden by regular configuration

I am having an issue where I've created a Configuration class for my source code, and a separate configuration class for my test package. I'd like some beans created differently in test than in other environments. However, when I run a build here's what's happening: (I have a bean called filesystem that gives me a virtual filesystem in test)

Overriding bean definition for bean 'fileSystem' with a different definition: replacing <testVersion from MockAppInjector> with <realVersionFromAppInjector>

I my test package I have

@Configuration
@ImportResource("classpath:/META-INF/fig-batch/spring-bootstrap.xml")
@ComponentScan(basePackages = "com.company")
class MockAppInjector {...}

and in my regular source package I have

@Configuration
@ImportResource("classpath:/META-INF/fig-batch/spring-bootstrap.xml")
@ComponentScan(basePackages = "com.company")
public class AppInjector {...}

And in my test I have @ContextConfiguration(classes = MockAppInjector.class)

Finally, all my xml has in it is <context:component-scan base-package="com.company" /> and a call to another xml that configures some data sources.

Upvotes: 0

Views: 127

Answers (2)

Steve
Steve

Reputation: 4691

The problem was that my Test configuration class was finding my real one. So I added a filter

@ComponentScan(basePackages = "com.vanguard", excludeFilters = @ComponentScan.Filter(value=Configuration.class, type = FilterType.ANNOTATION))

And removed the component scan from the xml, since it was superfluous. Now everything gets loaded one time.

Upvotes: 1

Andriy Kryvtsun
Andriy Kryvtsun

Reputation: 3344

The problem is any beans defined in XML have more priority than beans defined in Java configuration for some reason. So if you test beans are defined in Java configuration it's expected behavior.

To solve it you have to either put your test beans into XML file and put it in @ImportResource after your prod XML file or mark your beans in Java configuration with @Primary annotation.

Upvotes: 1

Related Questions