【Springboot】@ComponentScan detailed explanation

@ComponentScan

@ComponentScanIt is an annotation in the Spring framework, used to automatically scan and register components in the container.

Using @ComponentScanannotations, you can tell Spring to scan components under the specified package or class path, and then automatically register the scanned components into the Spring container. The following is @ComponentScanthe detailed usage of annotations:

  1. Import necessary dependencies: Make sure that the relevant dependencies of the Spring framework have been introduced into your project in order to use @ComponentScanannotations.

  2. Add annotations to the configuration class: Add annotations to the Spring configuration class @ComponentScanand specify the package or class path to be scanned. For example:

@Configuration
@ComponentScan("com.example.package")
public class AppConfig {
    
    
    // 其他配置
}

@ComponentScan ANNOTATION 和 REGEX

@ComponentScanThe annotation provides includeFiltersand excludeFiltersproperties, and you can use these filters to precisely control which components will be scanned and registered in the Spring container. Here's an example of how to @ComponentScanuse filters in :

@Configuration
@ComponentScan(basePackages = "com.example.package",
    includeFilters = {
    
    
        @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = MyAnnotation.class),
        @ComponentScan.Filter(type = FilterType.REGEX, pattern = ".*ServiceImpl")
    },
    excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ExcludeComponent.class)
)
public class AppConfig {
    
    
    // 其他配置
}

In the above example, we added two filters using @ComponentScanthe annotation's properties:includeFilters

  • The first filter uses FilterType.ANNOTATIONtype and MyAnnotation.classannotation class, it will only include MyAnnotationcomponents with annotation.
  • The second filter uses FilterType.REGEXtype and regular expression ".*ServiceImpl"and will only include components whose names end with "ServiceImpl".

At the same time, we also added a filter using @ComponentScanthe annotation's attribute:excludeFilters

  • This filter uses FilterType.ASSIGNABLE_TYPEthe type and ExcludeComponent.classthe class, and it will exclude components that inherit from or implement ExcludeComponentthe class.

Depending on your needs, you can use different filter types ( FilterType.ANNOTATION, FilterType.REGEX, FilterType.ASSIGNABLE_TYPEetc.) to define your own filtering rules. This way you can control which components are scanned and registered into the Spring container.

@ComponentScan CUSTOM

When using @ComponentScanannotations, you can customize filters to further control which components will be scanned and registered into the Spring container. Here is an example showing how to create a custom filter:

First, create a custom filter class, implement TypeFilterthe interface, and override the methods in it match():

import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.TypeFilter;

public class CustomFilter implements TypeFilter {
    
    

    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) {
    
    
        // 在这里编写你的过滤逻辑,根据需要返回 true 或 false
        // metadataReader 可以获取到正在扫描的组件的元数据信息,例如类名、注解等
        // metadataReaderFactory 可以获取到其他类的元数据信息

        // 示例:只匹配类名以 "Service" 结尾的组件
        String className = metadataReader.getClassMetadata().getClassName();
        return className.endsWith("Service");
    }
}

Then, @ComponentScanuse the custom filter in the annotation:

@Configuration
@ComponentScan(basePackages = "com.example.package",
    includeFilters = @ComponentScan.Filter(type = FilterType.CUSTOM, classes = CustomFilter.class)
)
public class AppConfig {
    
    
    // 其他配置
}

In the above example, we are passing the annotation's property CustomFilter.classas a filter .@ComponentScanincludeFilters

Custom filter classes implement TypeFilterthe interface and override match()the method. In match()the method, you can write your own filtering logic and return true or false as needed to determine whether it matches the currently scanned component. The filtering logic in the above example only matches components whose class name ends with "Service".

By using custom filters, you can decide which components will be scanned and registered with the Spring container based on more complex conditions and logic. This allows for more precise component management and configuration.

In @ComponentScanannotations, FilterType.ASSIGNABLE_TYPEfilters of type can be used to scan and register components matching the specified type. This filter will register components of the same type as the specified type or its subclasses or implementation classes with the Spring container.

@ComponentScan ASSIGNABLE_TYPE

Here's an example showing how to @ComponentScanuse FilterType.ASSIGNABLE_TYPEthe filter in :

  1. Create a base class or interface that needs to be scanned and registered:
public interface MyInterface {
    
    
    // 接口方法
}

  1. Create concrete implementation classes that need to be scanned and registered:
@Component
public class MyImplementation implements MyInterface {
    
    
    // 实现类逻辑
}

  1. Use the annotation on the configuration class @ComponentScanand set includeFiltersthe attribute to include FilterType.ASSIGNABLE_TYPEa filter of type:
@Configuration
@ComponentScan(basePackages = "com.example.package",
    includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = MyInterface.class)
)
public class AppConfig {
    
    
    // 其他配置
}

In the above example, we MyInterface.classpass it as a filter to the @ComponentScanannotation includeFiltersproperty, indicating that only components that implement MyInterfacethe interface will be scanned and registered in the Spring container. In this way, MyImplementationthe class will be automatically registered in the container.

By using FilterType.ASSIGNABLE_TYPEfilters, you can easily scan and register components selectively based on class hierarchies. This allows you to automatically register components of a specific type or its subclass or implementation class into the Spring container, thereby achieving more flexible component management and configuration.

Guess you like

Origin blog.csdn.net/qq_39017153/article/details/132160902