Spring @ComponentScan 自定义扫描规则

Spring @ComponentScan 组件中扫描规则使用场景:

package org.example.cap2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.FilterType;
import org.example.model.Person;

@Configuration
@ComponentScan(value = "org.example.cap2", includeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = MyTypeFilter.class)
}, useDefaultFilters = false)
// includeFilters = Filter[], 指定扫描的时候只需要包含哪些组件
// excludeFilters = Filter[], 指定扫描的时候按照什么规则排除哪些组件
// useDefaultFilters = false, 默认是true 扫描所有组件,要改成false
public class MainConfig2 {

    @Bean(value = "abcPerson")
    public Person person() {
        return new Person("abc", "30");
    }
}

 自定义扫描规则代码实现:

package org.example.config;

import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;

/**
 * 新增自定义过滤规则类
 */
public class MyTypeFilter implements TypeFilter {
    /**
     * @param metadataReader        读取当前正在扫描类的信息
     * @param metadataReaderFactory 可以获取到其他任何类信息
     * @return
     * @throws IOException
     */
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
            throws IOException {
        // 获取当前注解类的信息
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
        // 获取当前正在扫描的类的信息
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        // 获取当前类资源 类的路径
        Resource resource = metadataReader.getResource();

        String className = classMetadata.getClassName();
        System.out.println("------>" + className);
        if (className.contains("er")) { // 当前类名包含er,则匹配成功
            return true;
        }
        return false;
    }
}

你可能感兴趣的:(spring,java)