@ComponentScan includeFilters()方法指定Spring扫描的时候按照什么规则只需要包含哪些组件 excludeFilters()方法指定Spring扫描的时候按照什么规则排除哪些组件。两个方法的返回值都是Filter[]数组,在ComponentScan注解类的内部存在Filter注解类。 规则:FilterType 是枚举类, 包含了 FilterType.ANNOTATION 注解类型。 FilterType.ASSIGNABLE_TYPE 通过指定的类型。 FilterType.ASPECTJ 。 FilterType.REGEX 正则表达式。 FilterType.CUSTOM 自定义筛选器(下面有实例代码,实现TypeFilter)
类上面可以书写多个@ComponentScan,因为在jdk8中,@ComponentScan里面是@ComponentScans
package com.irving.aop.config;
import com.irving.aop.entity.User;
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.Service;
/*excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Service.class}) 不包含
}*/
@Configuration
@ComponentScan(value = "com.irving.aop",
includeFilters={
@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Service.class}),
},useDefaultFilters = false
)
public class AopConfig {
@Bean
public User getUser(){
return new User();
}
}
package com.irving.aop.config;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class MyTypeFilter implements TypeFilter {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
String className = annotationMetadata.getClassName();
if(className.contains("Service")){
return true;
}
return false;
}
}
Scope
@Conditional
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String property = environment.getProperty("os.name");
if (property.contains("Windows")){
return true;
}
return false;
}
}