Spring註解
一、組建註冊
包結構:
1.@Configuration和@ComponentScan
@ComponentScan的includeFilters用法
FilterType的類型
ANNOTATION,基於註解的過濾 ASSIGNABLE_TYPE,指定class ASPECTJ,ASPECTJ表達shi REGEX,正則表達式 CUSTOM;自定義
//相當於application-bean.xml
@Configuration
//配置掃描包的策略,當前註解爲只掃描加@Controller的組件
//注意useDefaultFilters要設置爲fasle,不然爲默認的Filters,@Service/@Repository都掃描
@ComponentScan(value = "com.gaoyuzhe",includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)
},
useDefaultFilters = false)
運行結果
excludeFilters用法:
注意:useDefaultFilters設置爲true,不然不會掃描到組件
package com.gaoyuzhe.config;
import com.gaoyuzhe.pojo.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
/**
* @author GaoYuzhe
* @date 2018/3/12.
*/
@Configuration
@ComponentScan(value = "com.gaoyuzhe",excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)
},
useDefaultFilters = true)
public class MainConfig {
@Bean
public Person person(){
return new Person("gaoyuzhe ",12);
}
}
運行結果
自定義Filter策略
/**
* 自定義的過濾規則
* @author GaoYuzhe
* @date 2018/3/12.
*/
public class MyTypeFilter implements TypeFilter {
/**
* 匹配規則
* @param metadataReader the metadata reader for the target class
* 當前類的信息
* @param metadataReaderFactory a factory for obtaining metadata readers
* for other classes (such as superclasses and interfaces)
* 當前類的父類或者接口的信息
* @return 是否匹配
* @throws IOException
*/
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
ClassMetadata classMetadata = metadataReader.getClassMetadata();
//當前類名稱
String className = classMetadata.getClassName();
System.out.println("className = " + className);
//當前類的資源路徑
Resource resource = metadataReader.getResource();
System.out.println("resource = " + resource);
//如果類名包含"Dao",則爲匹配成功
return className.contains("Dao");
}
}
配置類註解。
@Configuration
@ComponentScan(value = "com.gaoyuzhe",includeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM,classes = MyTypeFilter.class)
}, useDefaultFilters = false)
執行結果