03--元件註冊-自定義TypeFilter指定過濾規則

wangyongxun1983發表於2020-10-09

//配置類==配置檔案(xml)
@Configuration   //告訴Spring這個一個配製類
@ComponentScan(value="com.ceshi",includeFilters={
		@Filter(type=FilterType.CUSTOM,classes={
				MyFilterType.class
		})
}) 
//value:指定要掃描的包。
//excludeFilters=Filter[] 掃描排除
//includeFilters=Filter[] 只掃描
//FilterType.ANNOTION:按照註解
//FilterType.ASSIGNABLE_TYPE:按照給定的型別
//FilterType.REGEX:正規表示式
//FilterType.CUSTOM:自定義
@ComponentScans(value={})//掃描多個包
public class BeanConfig {
	
	//給容器註冊一個Bean,型別class:預設為返回值的型別,標識id:預設為方法名
	@Bean("person")
	public PersonBean personBean(){
		return new PersonBean("lishi","20");
	}
}
import java.io.IOException;

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;

public class MyFilterType implements TypeFilter {
	
	/**
	 * MetadataReader:讀取當前正在掃描的類資訊
	 * MetadataReaderFactory:MetadataReader的工廠,根據工廠可以得到其他的MetadataReader類資訊
	 */
	@Override
	public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
			throws IOException {
		// TODO Auto-generated method stub
		//獲取當前類的註解資訊
		AnnotationMetadata AnnotationMetadata = metadataReader.getAnnotationMetadata();
		//獲取當前正在掃描的類資訊
		ClassMetadata classMetadata = metadataReader.getClassMetadata();
		//獲取當前類資源(類的路徑)
		Resource resource = metadataReader.getResource();
		
		System.out.println(classMetadata.getClassName());
		return true;
	}

}
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.ceshi.config.BeanConfig;

public class IOCTest {
	@Test
	public void test01(){
		ApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
		String[] names = annotationConfigApplicationContext.getBeanDefinitionNames();
		for(String name:names){
			System.out.println(name);
		}
		
		
		
	}
}
com.ceshi.bean.PersonBean
com.ceshi.demo.MyFilterType
com.ceshi.IOCTest
com.ceshi.MainTest
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
beanConfig
personBean
personController
personDao
myFilterType
IOCTest
mainTest
personService
person

 

相關文章