@ComponentScan注解 -【Spring底层原理
@ComponentScan 是一个Spring框架的注解,它的主要目的是为了让Spring框架能够扫描指定的包路径下的类,并且将其上的注解(如@Controller,@Service,@Repository,@Component)标注的类注册为bean。
@ComponentScan 注解通常和 @Configuration 注解一起使用,所以它也可以被看作是 @Configuration 注解的一部分。
以下是 @ComponentScan 注解的一些常见用法:
- 基本用法:
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
//...
}在这个例子中,Spring将会扫描 "com.example" 包下的所有类,并且将其中标注为 @Component,@Service,@Repository 或 @Controller 的类注册为bean。
- 使用
basePackageClasses属性:
@Configuration
@ComponentScan(basePackageClasses = {ServiceImpl.class, Controller.class})
public class AppConfig {
//...
}在这个例子中,Spring将会扫描 ServiceImpl.class 和 Controller.class 所在的包,并且将其中标注为 @Component,@Service,@Repository 或 @Controller 的类注册为bean。
- 指定扫描的类或接口:
@Configuration
@ComponentScan(value = "com.example", includeFilters = @Filter(type = FilterType.ANNOTATION, classes = CustomAnnotation.class))
public class AppConfig {
//...
}在这个例子中,Spring将会扫描 "com.example" 包下的所有类,并且将其中标注为 CustomAnnotation 的类注册为bean。
- 排除指定的类或接口:
@Configuration
@ComponentScan(value = "com.example", excludeFilters = @Filter(type = FilterType.ANNOTATION, classes = CustomAnnotation.class))
public class AppConfig {
//...
}在这个例子中,Spring将会扫描 "com.example" 包下的所有类,但不会将其中标注为 CustomAnnotation 的类注册为bean。
- 使用
FilterType.ASSIGNABLE_TYPE来指定具体的类:
@Configuration
@ComponentScan(value = "com.example", includeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = ServiceImpl.class))
public class AppConfig {
//...
}在这个例子中,Spring将会扫描 ServiceImpl.class 所在的包,并且将 ServiceImpl.class 注册为bean。
- 使用
FilterType.CUSTOM来指定自定义的过滤器:
@Configuration
@ComponentScan(value = "com.example", includeFilters = @Filter(type = FilterType.CUSTOM, classes = MyTypeFilter.class))
public class AppConfig {
//...
}
public class MyTypeFilter implements TypeFilter {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
// 自定义过滤逻辑
return true;
}
}在这个例子中,Spring将会使用 MyTypeFilter 中定义的过滤逻辑来决定是否将 com.example 包下的类注册为bean。
以上就是 @ComponentScan 注解的一些常见用法和使用示例。
评论已关闭