Skip to content

Spring Boot component scanning without annotations

Published on
  • Spring Boot

Spring Boot has an interesting capability that I haven't discovered till very recently when going through Spring Cloud Function project source code - it can scan for components - meaning go through classpath to find beans - even for classes that are not annotated with any of the Spring stereotype annotations like @Component, @Service, @Repository, @Controller or @Configuration.

@ComponentScan annotation - that can be placed on any @Configuration class (including the main @SpringBootApplication annotated class) - can be configured with a filter that instead of looking for typical Spring annotations, looks for specific Java types.

In the following example, Spring will scan for components in package functions that implement java.util.Function interface:

java
@SpringBootApplication
@ComponentScan(
        basePackages = "functions",
        includeFilters = @ComponentScan.Filter(
                type = FilterType.ASSIGNABLE_TYPE,
                classes = Function.class
        )
)
public class MyApp {

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

Such configuration make it possible to scan for classes from a Spring unaware 3rd party jar without defining beans with @Bean annotation. Or it can save you from defining @Beans in configuration classes in case you want to keep your beans free from Spring classes or annotations.

Spring Cloud Function gives you exactly this option - you can define classes of type Function, Supplier or Consumer in a functions package, without annotating them with Spring annotations, and they will be registered as beans in the container.

While it is not useful in the great majority of regular applications I find it quite interesting and potentially useful when developing something more advanced or less typical than regular Spring Boot application.

Let's stay in touch and follow me on Twitter: @maciejwalkowiak

Subscribe to RSS feed