Spring - Using @ComponentScan to scan non component classes via includeFilters attribute

[Last Updated: Mar 27, 2021]

@ComponentScan#includeFilters can be used to scan classes which are not annotated with @Component and other stereotype annotation. It can be done by specifying a Filter with type as FilterType#ASSIGNABLE_TYPE and classes as non component classes to be scanned. For example:

@ComponentScan(includeFilters = @ComponentScan.Filter(
        type = FilterType.ASSIGNABLE_TYPE, classes = {OrderService.class}))


A non component class

package com.logicbig.example;

public class OrderService {

  public void placeOrder(String item) {
      System.out.printf("Retail order placed. Item: %s%n", item);

A component class

package com.logicbig.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class Buyer {
  private OrderService orderService;

  public void buySomething() {

Main class

package com.logicbig.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;

@ComponentScan(includeFilters = @ComponentScan.Filter(
      type = FilterType.ASSIGNABLE_TYPE, classes = {OrderService.class}))
public class OnlineOrderApp {

  public static void main(String... strings) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(OnlineOrderApp.class);
      System.out.println("-- Spring container started and is ready --");
      Buyer buyer = context.getBean(Buyer.class);


-- Spring container started and is ready --
Retail order placed. Item: Laptop

Example Project

Dependencies and Technologies Used:

  • spring-context 4.2.3.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.6.3

@ComponentScan#includeFilters example Select All Download
  • spring-component-scan-including-non-component-classes
    • src
      • main
        • java
          • com
            • logicbig
              • example

    See Also