SoFunction
Updated on 2025-04-05

The role and usage of TypeExcludeFilter in SpringBoot

Function and use of TypeExcludeFilter in SpringBoot

In Spring Boot app,TypeExcludeFilterIs a tool for filtering specific types of components so that they are not automatically scanned and registered as beans by Spring containers.

This is useful when you want to exclude certain classes or types (such as configuration classes, components, etc.) without wanting them to participate in Spring's auto-assembly.

effect

Normally, Spring Boot apps will automatically recognize and load them with@Component, @Service, @Repository, or@ConfigurationClasses with annotations.

However, in some scenarios, we may not want certain classes to be automatically loaded, such as special implementations in the test environment, or to exclude unnecessary components in order to optimize startup speed.

at this time,TypeExcludeFilterIt comes in handy, which allows developers to exclude these unwanted components based on their type.

Example of usage

Suppose we have a project structure as follows:

├── config
│   └── 
└── service
│   ├── 
│   └── 
└── 

Both Services will be automatically scanned by SpringBootApplication by default.

We can useTypeExcludeFilterCome and make sureMockServiceWill not be loaded in a non-test environment.

First, we need to create a custom filter that inherits fromTypeExcludeFilterAnd rewritematchesMethod to specify which types should be excluded.

Please note:

  • We inheritTypeExcludeFilterAnd rewrite the method instead of implementing it directlyTypeFilterThe matches method in the interface.
  • This is becauseTypeExcludeFilteryes@SpringBootApplicationAnnotation filter class that has been configured by default during automatic scanning

The following is the source code snippet:

@ComponentScan(excludeFilters = { @Filter(type = , classes = ),
		@Filter(type = , classes = ) })
public @interface SpringBootApplication {
   ...
}

Write custom filters

Create custom filter classes, inheritTypeExcludeFilterAnd rewritematchmethod:

package ;

import ;
import ;
import ;

public class MyTypeExcludeFilter extends TypeExcludeFilter {

    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        String className = ().getClassName();
        // Set exclusion logic as needed, for example, excluding specific classes here.  For example, you can also exclude all classes such as Test and Demo.        return ("");
    }
}

Register a custom filter

To ensure that our custom filters take effect when the application starts, we need to create an implementationApplicationContextInitializerclass of interface and register our filters in this class.

package ;

import ;
import ;
import ;
import ;
import ;

public class MyTypeExcludeFilterInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(@NonNull ConfigurableApplicationContext applicationContext) {
        ().registerSingleton("myTypeExcludeFilter", new MyTypeExcludeFilter());
    }
}

Configuration

The last step is toMETA-INF/Register our files in the fileApplicationContextInitializer, so that it can be loaded automatically when the application starts:

=\

This line of configuration tells Spring Boot that when the application starts, it should be found and initializedMyTypeExcludeFilterInitializer

The reason why it is necessaryIt is configured because we need to@ComponentScanRegister our custom filter class into the spring context before the annotation is executed, otherwise the custom class will be useless.

Summarize

Through the above steps, we successfullyTypeExcludeFilterIntegrated into Spring Boot applications and does not require explicit writing@ComponentScanAnnotate or modify any existing configuration.

This approach not only simplifies the code structure, but also allows us to have more flexibility in controlling which types of components should be excluded.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.