Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Spring component scan exclude

farenda 2015-12-21 1

How to exclude classes/packages from Component Scan in Spring Framework? The task is a bit tricky, especially when regexp is involved. See how it works!

Example Spring beans

Let’s say that we’ve got the following two classes in com.farenda.spring.tutorial.excludescan package:

package com.farenda.spring.tutorial.excludescan;

import org.springframework.stereotype.Service;

@Service
public class ExcludedService {

    public ExcludedService() {
        System.out.println("Instantiating " + getClass().getSimpleName());
    }
}
package com.farenda.spring.tutorial.excludescan;

import org.springframework.stereotype.Service;

@Service
public class IncludedService {

    public IncludedService() {
        System.out.println("Instantiating " + getClass().getSimpleName());
    }
}

We want to scan the whole package and include every component except ExcludedService. In our case included beans should contain only IncludedService.

ComponentScan exclude – using annotations

To exclude some beans we can use excludeFilters on the @ComponentScan annotation like this:

package com.farenda.spring.tutorial;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
import org.springframework.context.annotation.ComponentScan.Filter;

import java.util.Arrays;

@ComponentScan(basePackages = "com.farenda.spring.tutorial.excludescan",
        excludeFilters =@Filter(
                type = FilterType.REGEX,
                pattern = "com\\.farenda\\.spring\\.tutorial\\.excludescan\\.Excluded.*"))
@EnableAutoConfiguration
public class ExcludingFromComponentScanExample {

    public static void main(String[] args) throws Exception {
        ApplicationContext context =
                SpringApplication.run(ExcludingFromComponentScanExample.class, args);

        String[] beans = context.getBeanDefinitionNames();

        // sort names only to make output more readable:
        Arrays.sort(beans);

        System.out.println("Defined beans: ");
        for (String bean : beans) {
            System.out.println(bean);
        }
    }
}

We apply REGEX FilterType that allows us nicely exclude single classes and whole packages. When we run the application you can see that only includedService is among beans in ApplicationContext built from ComponentScan:

...
 :: Spring Boot ::        (v1.2.3.RELEASE)

2015-12-20 13:08:37.601  INFO 4077 --- [           main] .f.s.t.ExcludingFromComponentScanExample
2015-12-20 13:08:37.660  INFO 4077 --- [           main] s.c.a.AnnotationConfigApplicationContext
Instantiating IncludedService
...
2015-12-20 13:08:39.292  INFO 4077 --- [           main] .f.s.t.ExcludingFromComponentScanExample : Started ExcludingFromComponentScanExample in 2.204 seconds (JVM running for 2.841)
Defined beans:
excludingFromComponentScanExample
includedService
mbeanExporter
mbeanServer
objectNamingStrategy
org.springframework.boot.autoconfigure.AutoConfigurationPackages
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.condition.BeanTypeRegistry
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
propertySourcesPlaceholderConfigurer
2015-12-20 13:08:39.295  INFO 4077 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@7a187f14: startup date [Sun Dec 20 13:08:37 CET 2015]; root of context hierarchy
2015-12-20 13:08:39.298  INFO 4077 --- [       Thread-1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

Process finished with exit code 0

The same filtering mechanism can be used with includeFilters attribute, to select classes/packages that should be included in Spring ApplicationContext.

ComponentScan exclude – XML version

If you happen to still work with XML Spring Configuration, then the same thing can be done in the following way:

<context:component-scan
    base-package="com.farenda.spring.tutorial.excludescan">

  <context:exclude-filter type="regex"
      expression="com\.farenda\.spring\.tutorial\.excludescan\.Excluded.*"/>

</context:component-scan>

Resources

  • Check out Spring Framework Tutorial!
Share with the World!
Categories Spring Framework Tags spring, spring-core
Previous: Java ScheduledThreadPoolExecutor Example
Next: Java Console read password

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored