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:




Published by

Alan Feekery

Developer, Gamer, Musician, Cyclist and big Motorsport fan... enjoys the odd cup of coffee :)

One thought on “Spring Boot component scanning for test libraries”

  1. Instead of that complex filter, you could replace the instruction as follows:

    Also, you should always use the “test” scope to include a test library, be it a spring boot app or any other app. If you don’t, the test library will leak in transitive dependencies of that module.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s