Spring Boot component scanning for test libraries

Recently I had an issue where I was trying to use a custom test library I had built in Spring Boot within an existing Spring Boot app. I ran into a weird issue where by using the test library I broke the main app.

The issue was that the main app was trying to initialise the test library before it was ready, it was attempting to autowire beans within it… turned out the issue was because the test library used the same base package naming convention as the main app.

For example, if the main app was com.alanfeekery.app and the test library was com.alanfeekery.test and my application-context.xml looked like this:

<context:component-scan base-package="com.alanfeekery"></context:component-scan>

Then Spring would just go ahead and try configure everything under the package com.alanfeekery, this is bad as the app shouldn’t be configuring the test library. The solution looks like this:

<context:component-scan base-package="com.alanfeekery">
	<context:include-filter type="regex" expression=".*app"/>
	<context:exclude-filter type="regex" expression=".*test"/>

With these include & exclude filters my app no longer scanned into my test library automatically and everything worked as expected.


Another thing to be aware about, if are including a custom test library in your Spring Boot app, make sure you flag the dependency scope to test this means that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phase.

Here’s an example: